[Pkg-cmake-commits] [cmake] 01/09: New upstream version 3.7.0~rc2

Felix Geyer fgeyer at moszumanska.debian.org
Sun Oct 30 22:22:56 UTC 2016


This is an automated email from the git hooks/post-receive script.

fgeyer pushed a commit to branch experimental
in repository cmake.

commit b8500fbc107c3aac07700fee911fd81d77e41fb0
Author: Felix Geyer <fgeyer at debian.org>
Date:   Sun Oct 30 18:24:19 2016 +0100

    New upstream version 3.7.0~rc2
---
 .gitignore                                         |    7 +
 .hooks-config.bash                                 |   13 +-
 Auxiliary/CMakeLists.txt                           |    2 +-
 Auxiliary/bash-completion/cmake                    |    2 +-
 Auxiliary/cmake-help.vim                           |   21 -
 Auxiliary/cmake-indent.vim                         |   93 -
 Auxiliary/cmake-mode.el                            |   30 +-
 Auxiliary/cmake-syntax.vim                         |   89 -
 Auxiliary/cmake.m4                                 |   13 +-
 Auxiliary/vim/cmake.vim.in                         |   91 +
 Auxiliary/vim/extract-upper-case.pl                |  141 +
 Auxiliary/vim/indent/cmake.vim                     |   83 +
 Auxiliary/vim/syntax/cmake.vim                     |  554 +++
 CMakeCPack.cmake                                   |   69 +-
 CMakeCPackOptions.cmake.in                         |   33 +-
 CMakeLists.txt                                     |  116 +-
 CONTRIBUTING.rst                                   |   24 +-
 CTestConfig.cmake                                  |   14 +-
 CTestCustom.cmake.in                               |    8 +
 CompileFlags.cmake                                 |   22 +-
 Copyright.txt                                      |   85 +-
 DartConfig.cmake                                   |   14 +-
 Help/command/add_custom_command.rst                |    7 +
 Help/command/cmake_parse_arguments.rst             |   11 +
 Help/command/ctest_build.rst                       |    9 +-
 Help/command/ctest_configure.rst                   |   11 +-
 Help/command/ctest_coverage.rst                    |    9 +-
 Help/command/ctest_test.rst                        |    9 +-
 Help/command/ctest_upload.rst                      |    6 +-
 Help/command/export.rst                            |   15 +
 Help/command/file.rst                              |    6 +
 Help/command/find_library.rst                      |    7 +
 Help/command/find_package.rst                      |   35 +-
 Help/command/get_cmake_property.rst                |   11 +-
 Help/command/if.rst                                |   59 +-
 Help/command/include.rst                           |    6 +-
 Help/command/install.rst                           |   14 +-
 Help/command/math.rst                              |    9 +-
 Help/command/separate_arguments.rst                |   12 +-
 Help/command/set.rst                               |    4 +-
 Help/command/string.rst                            |    8 +-
 Help/command/target_link_libraries.rst             |    6 +
 Help/generator/CodeLite.rst                        |    6 +-
 Help/generator/Ninja.rst                           |   27 +-
 Help/generator/Visual Studio 10 2010.rst           |    2 +-
 Help/generator/Visual Studio 11 2012.rst           |    2 +-
 Help/generator/Visual Studio 12 2013.rst           |    2 +-
 Help/generator/Visual Studio 14 2015.rst           |    2 +-
 Help/generator/Visual Studio 15.rst                |   16 +
 Help/index.rst                                     |    1 +
 Help/manual/OPTIONS_BUILD.txt                      |    8 +-
 Help/manual/cmake-buildsystem.7.rst                |    2 +-
 Help/manual/cmake-developer.7.rst                  |   74 +-
 Help/manual/cmake-generator-expressions.7.rst      |    8 +-
 Help/manual/cmake-generators.7.rst                 |    1 +
 Help/manual/cmake-modules.7.rst                    |    4 +
 Help/manual/cmake-policies.7.rst                   |    8 +
 Help/manual/cmake-properties.7.rst                 |   12 +
 Help/manual/cmake-server.7.rst                     |  703 +++
 Help/manual/cmake-toolchains.7.rst                 |  204 +-
 Help/manual/cmake-variables.7.rst                  |   32 +-
 Help/manual/cmake.1.rst                            |   45 +
 Help/manual/ctest.1.rst                            |  104 +-
 Help/module/AndroidTestUtilities.rst               |    1 +
 Help/module/CPackProductBuild.rst                  |    1 +
 Help/module/FindICU.rst                            |    1 +
 Help/module/FindVulkan.rst                         |    1 +
 Help/policy/CMP0066.rst                            |   27 +
 Help/prop_dir/BINARY_DIR.rst                       |    5 +
 Help/prop_dir/BUILDSYSTEM_TARGETS.rst              |   11 +
 Help/prop_dir/SOURCE_DIR.rst                       |    5 +
 Help/prop_dir/SUBDIRECTORIES.rst                   |   15 +
 Help/prop_gbl/FIND_LIBRARY_USE_LIB32_PATHS.rst     |   10 +
 Help/prop_sf/VS_TOOL_OVERRIDE.rst                  |    5 +
 Help/prop_sf/XCODE_FILE_ATTRIBUTES.rst             |   11 +
 Help/prop_test/DEPENDS.rst                         |    6 +-
 Help/prop_test/FIXTURES_CLEANUP.rst                |   46 +
 Help/prop_test/FIXTURES_REQUIRED.rst               |   94 +
 Help/prop_test/FIXTURES_SETUP.rst                  |   47 +
 Help/prop_test/RESOURCE_LOCK.rst                   |    3 +
 Help/prop_tgt/ANDROID_API.rst                      |    9 +-
 Help/prop_tgt/ANDROID_ARCH.rst                     |    3 +-
 Help/prop_tgt/ANDROID_GUI.rst                      |    4 +-
 Help/prop_tgt/ANDROID_STL_TYPE.rst                 |   32 +-
 Help/prop_tgt/AUTORCC.rst                          |    5 +
 Help/prop_tgt/BUNDLE_EXTENSION.rst                 |    7 +-
 Help/prop_tgt/LINK_WHAT_YOU_USE.rst                |   15 +
 Help/prop_tgt/VS_SDK_REFERENCES.rst                |    7 +
 Help/prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS.rst       |    5 +-
 Help/release/3.7.rst                               |  320 ++
 Help/release/index.rst                             |    1 +
 Help/variable/ANDROID.rst                          |    5 +
 Help/variable/CMAKE_ANDROID_API.rst                |   10 +-
 Help/variable/CMAKE_ANDROID_ARCH.rst               |   18 +-
 Help/variable/CMAKE_ANDROID_ARCH_ABI.rst           |   17 +
 Help/variable/CMAKE_ANDROID_ARM_MODE.rst           |    7 +
 Help/variable/CMAKE_ANDROID_ARM_NEON.rst           |    6 +
 Help/variable/CMAKE_ANDROID_NDK.rst                |    7 +
 .../CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst        |   13 +
 .../CMAKE_ANDROID_STANDALONE_TOOLCHAIN.rst         |    6 +
 Help/variable/CMAKE_ANDROID_STL_TYPE.rst           |   35 +-
 Help/variable/CMAKE_CODELITE_USE_TARGETS.rst       |    8 +
 Help/variable/CMAKE_COMPILER_IS_GNUCC.rst          |    5 +
 Help/variable/CMAKE_COMPILER_IS_GNUCXX.rst         |    5 +
 Help/variable/CMAKE_COMPILER_IS_GNUG77.rst         |    5 +
 Help/variable/CMAKE_COMPILER_IS_GNULANG.rst        |   15 -
 .../CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT.rst         |   10 +
 Help/variable/CMAKE_EXE_LINKER_FLAGS_INIT.rst      |   11 +
 .../variable/CMAKE_FIND_PACKAGE_SORT_DIRECTION.rst |   16 +
 Help/variable/CMAKE_FIND_PACKAGE_SORT_ORDER.rst    |   36 +
 Help/variable/CMAKE_INSTALL_PREFIX.rst             |    2 +-
 .../CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst        |   11 +
 .../CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst        |    7 +
 Help/variable/CMAKE_LANG_FLAGS_DEBUG_INIT.rst      |   10 +
 Help/variable/CMAKE_LANG_FLAGS_INIT.rst            |   15 +
 Help/variable/CMAKE_LANG_FLAGS_MINSIZEREL_INIT.rst |   10 +
 Help/variable/CMAKE_LANG_FLAGS_RELEASE_INIT.rst    |   10 +
 .../CMAKE_LANG_FLAGS_RELWITHDEBINFO_INIT.rst       |   10 +
 Help/variable/CMAKE_LINK_WHAT_YOU_USE.rst          |    6 +
 .../CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT.rst      |   10 +
 Help/variable/CMAKE_MODULE_LINKER_FLAGS_INIT.rst   |   11 +
 Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst     |    2 +
 .../CMAKE_SHARED_LINKER_FLAGS_CONFIG_INIT.rst      |   10 +
 Help/variable/CMAKE_SHARED_LINKER_FLAGS_INIT.rst   |   11 +
 .../CMAKE_STATIC_LINKER_FLAGS_CONFIG_INIT.rst      |   10 +
 Help/variable/CMAKE_STATIC_LINKER_FLAGS_INIT.rst   |   11 +
 Help/variable/CMAKE_Swift_LANGUAGE_VERSION.rst     |    5 +
 Help/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.rst   |    6 +-
 Help/variable/CMAKE_VERSION.rst                    |   10 +-
 Help/variable/MSVC10.rst                           |    5 +-
 Help/variable/MSVC11.rst                           |    5 +-
 Help/variable/MSVC12.rst                           |    5 +-
 Help/variable/MSVC14.rst                           |    5 +-
 Help/variable/MSVC80.rst                           |    5 +-
 Help/variable/MSVC90.rst                           |    5 +-
 Help/variable/MSVC_VERSION.rst                     |    2 +-
 Help/variable/XCODE.rst                            |    4 +
 Licenses/LGPLv3.txt                                |  165 +
 Modules/AddFileDependencies.cmake                  |   16 +-
 Modules/AndroidTestUtilities.cmake                 |  157 +
 .../AndroidTestUtilities/PushToAndroidDevice.cmake |  174 +
 Modules/BundleUtilities.cmake                      |   16 +-
 Modules/CMake.cmake                                |   14 +-
 Modules/CMakeASM-ATTInformation.cmake              |   14 +-
 Modules/CMakeASMInformation.cmake                  |   23 +-
 Modules/CMakeASM_MASMInformation.cmake             |   14 +-
 Modules/CMakeASM_NASMInformation.cmake             |   14 +-
 Modules/CMakeAddFortranSubdirectory.cmake          |   17 +-
 Modules/CMakeBackwardCompatibilityC.cmake          |   14 +-
 Modules/CMakeBackwardCompatibilityCXX.cmake        |   18 +-
 Modules/CMakeBorlandFindMake.cmake                 |   14 +-
 Modules/CMakeCCompiler.cmake.in                    |    1 +
 Modules/CMakeCInformation.cmake                    |   23 +-
 Modules/CMakeCXXCompiler.cmake.in                  |    1 +
 Modules/CMakeCXXInformation.cmake                  |   23 +-
 Modules/CMakeCheckCompilerFlagCommonPatterns.cmake |   17 +-
 Modules/CMakeCommonLanguageInclude.cmake           |   28 +-
 Modules/CMakeCompilerIdDetection.cmake             |   22 +-
 Modules/CMakeDependentOption.cmake                 |   16 +-
 Modules/CMakeDetermineASM-ATTCompiler.cmake        |   14 +-
 Modules/CMakeDetermineASMCompiler.cmake            |   14 +-
 Modules/CMakeDetermineASM_MASMCompiler.cmake       |   14 +-
 Modules/CMakeDetermineASM_NASMCompiler.cmake       |   14 +-
 Modules/CMakeDetermineCCompiler.cmake              |   17 +-
 Modules/CMakeDetermineCXXCompiler.cmake            |   17 +-
 Modules/CMakeDetermineCompileFeatures.cmake        |   14 +-
 Modules/CMakeDetermineCompiler.cmake               |   14 +-
 Modules/CMakeDetermineCompilerABI.cmake            |   14 +-
 Modules/CMakeDetermineCompilerId.cmake             |   30 +-
 Modules/CMakeDetermineFortranCompiler.cmake        |   21 +-
 Modules/CMakeDetermineJavaCompiler.cmake           |   14 +-
 Modules/CMakeDetermineRCCompiler.cmake             |   14 +-
 Modules/CMakeDetermineSwiftCompiler.cmake          |   14 +-
 Modules/CMakeDetermineSystem.cmake                 |   15 +-
 Modules/CMakeDetermineVSServicePack.cmake          |   18 +-
 Modules/CMakeExpandImportedTargets.cmake           |   17 +-
 Modules/CMakeExportBuildSettings.cmake             |   14 +-
 ...atorDetermineCompilerMacrosAndIncludeDirs.cmake |   14 +-
 Modules/CMakeFindBinUtils.cmake                    |   16 +-
 Modules/CMakeFindCodeBlocks.cmake                  |   14 +-
 Modules/CMakeFindDependencyMacro.cmake             |   16 +-
 Modules/CMakeFindEclipseCDT4.cmake                 |   16 +-
 Modules/CMakeFindFrameworks.cmake                  |   20 +-
 Modules/CMakeFindJavaCommon.cmake                  |   14 +-
 Modules/CMakeFindKDevelop3.cmake                   |   14 +-
 Modules/CMakeFindKate.cmake                        |   14 +-
 Modules/CMakeFindPackageMode.cmake                 |   16 +-
 Modules/CMakeFindWMake.cmake                       |   14 +-
 Modules/CMakeFindXCode.cmake                       |   14 +-
 Modules/CMakeForceCompiler.cmake                   |   16 +-
 Modules/CMakeFortranCompiler.cmake.in              |    4 +
 Modules/CMakeFortranInformation.cmake              |   23 +-
 Modules/CMakeGenericSystem.cmake                   |   14 +-
 Modules/CMakeGraphVizOptions.cmake                 |   17 +-
 Modules/CMakeIOSInstallCombined.cmake              |   28 +-
 Modules/CMakeImportBuildSettings.cmake             |   14 +-
 Modules/CMakeJOMFindMake.cmake                     |   15 +-
 Modules/CMakeJavaInformation.cmake                 |   14 +-
 Modules/CMakeLanguageInformation.cmake             |   14 +-
 Modules/CMakeMSYSFindMake.cmake                    |   14 +-
 Modules/CMakeMinGWFindMake.cmake                   |   14 +-
 Modules/CMakeNMakeFindMake.cmake                   |   15 +-
 Modules/CMakeNinjaFindMake.cmake                   |   14 +-
 Modules/CMakePackageConfigHelpers.cmake            |   24 +-
 Modules/CMakeParseArguments.cmake                  |   16 +-
 Modules/CMakeParseImplicitLinkInfo.cmake           |   60 +-
 Modules/CMakePrintHelpers.cmake                    |   28 +-
 Modules/CMakePrintSystemInformation.cmake          |   16 +-
 Modules/CMakePushCheckState.cmake                  |   17 +-
 Modules/CMakeRCInformation.cmake                   |   19 +-
 Modules/CMakeSwiftInformation.cmake                |   15 +-
 Modules/CMakeSystem.cmake.in                       |    2 +-
 Modules/CMakeSystemSpecificInformation.cmake       |   14 +-
 Modules/CMakeSystemSpecificInitialize.cmake        |   14 +-
 Modules/CMakeTestASM-ATTCompiler.cmake             |   14 +-
 Modules/CMakeTestASMCompiler.cmake                 |   14 +-
 Modules/CMakeTestASM_MASMCompiler.cmake            |   14 +-
 Modules/CMakeTestASM_NASMCompiler.cmake            |   14 +-
 Modules/CMakeTestCCompiler.cmake                   |   14 +-
 Modules/CMakeTestCXXCompiler.cmake                 |   14 +-
 Modules/CMakeTestCompilerCommon.cmake              |   14 +-
 Modules/CMakeTestFortranCompiler.cmake             |   14 +-
 Modules/CMakeTestJavaCompiler.cmake                |   14 +-
 Modules/CMakeTestRCCompiler.cmake                  |   14 +-
 Modules/CMakeTestSwiftCompiler.cmake               |   14 +-
 Modules/CMakeUnixFindMake.cmake                    |   14 +-
 Modules/CMakeVS7BackwardCompatibility.cmake        |   14 +-
 Modules/CMakeVerifyManifest.cmake                  |   17 +-
 Modules/CPack.cmake                                |   37 +-
 Modules/CPackBundle.cmake                          |   16 +-
 Modules/CPackComponent.cmake                       |   50 +-
 Modules/CPackCygwin.cmake                          |   16 +-
 Modules/CPackDMG.cmake                             |   16 +-
 Modules/CPackDeb.cmake                             |   54 +-
 Modules/CPackIFW.cmake                             |  272 +-
 Modules/CPackNSIS.cmake                            |   21 +-
 Modules/CPackPackageMaker.cmake                    |   16 +-
 Modules/CPackProductBuild.cmake                    |   28 +
 Modules/CPackRPM.cmake                             |  614 ++-
 Modules/CPackWIX.cmake                             |   46 +-
 Modules/CPackZIP.cmake                             |   14 +-
 Modules/CTest.cmake                                |   28 +-
 Modules/CTestCoverageCollectGCOV.cmake             |   15 +-
 Modules/CTestScriptMode.cmake                      |   17 +-
 Modules/CTestTargets.cmake                         |   14 +-
 Modules/CTestUseLaunchers.cmake                    |   18 +-
 Modules/CheckCCompilerFlag.cmake                   |   18 +-
 Modules/CheckCSourceCompiles.cmake                 |   18 +-
 Modules/CheckCSourceRuns.cmake                     |   18 +-
 Modules/CheckCXXCompilerFlag.cmake                 |   18 +-
 Modules/CheckCXXSourceCompiles.cmake               |   18 +-
 Modules/CheckCXXSourceRuns.cmake                   |   18 +-
 Modules/CheckCXXSymbolExists.cmake                 |   16 +-
 Modules/CheckFortranCompilerFlag.cmake             |   19 +-
 Modules/CheckFortranFunctionExists.cmake           |   18 +-
 Modules/CheckFortranSourceCompiles.cmake           |   35 +-
 Modules/CheckFunctionExists.cmake                  |   18 +-
 Modules/CheckIncludeFile.cmake                     |   18 +-
 Modules/CheckIncludeFileCXX.cmake                  |   18 +-
 Modules/CheckIncludeFiles.cmake                    |   24 +-
 Modules/CheckLanguage.cmake                        |   16 +-
 Modules/CheckLibraryExists.cmake                   |   18 +-
 Modules/CheckPrototypeDefinition.cmake             |   20 +-
 Modules/CheckSizeOf.cmake                          |   14 +-
 Modules/CheckStructHasMember.cmake                 |   18 +-
 Modules/CheckSymbolExists.cmake                    |   24 +-
 Modules/CheckTypeSize.cmake                        |   26 +-
 Modules/CheckVariableExists.cmake                  |   18 +-
 Modules/Compiler/ARMCC.cmake                       |   10 +-
 Modules/Compiler/Absoft-Fortran.cmake              |   10 +-
 .../Compiler/AppleClang-DetermineCompiler.cmake    |    2 +-
 Modules/Compiler/Bruce-C.cmake                     |   10 +-
 Modules/Compiler/Clang.cmake                       |   14 +-
 Modules/Compiler/G95-Fortran.cmake                 |   10 +-
 Modules/Compiler/GHS-C.cmake                       |   10 +-
 Modules/Compiler/GHS-CXX.cmake                     |   10 +-
 Modules/Compiler/GNU-Fortran.cmake                 |    7 +-
 Modules/Compiler/GNU.cmake                         |   26 +-
 Modules/Compiler/IAR.cmake                         |    5 +-
 Modules/Compiler/Intel-ASM.cmake                   |   11 +-
 Modules/Compiler/Intel-C.cmake                     |   11 +-
 Modules/Compiler/Intel-CXX.cmake                   |   11 +-
 Modules/Compiler/Intel-Fortran.cmake               |   12 +-
 Modules/Compiler/Intel.cmake                       |   26 +
 Modules/Compiler/MSVC-CXX-FeatureTests.cmake       |    3 +
 Modules/Compiler/NAG-Fortran.cmake                 |    1 +
 Modules/Compiler/PGI-C.cmake                       |    4 +-
 Modules/Compiler/PGI-CXX.cmake                     |    4 +-
 Modules/Compiler/PGI-Fortran.cmake                 |    4 +-
 Modules/Compiler/PGI.cmake                         |   24 +-
 Modules/Compiler/PathScale-C.cmake                 |    4 +-
 Modules/Compiler/PathScale-CXX.cmake               |    4 +-
 Modules/Compiler/PathScale.cmake                   |   24 +-
 Modules/Compiler/QCC.cmake                         |   15 +-
 Modules/Compiler/SCO.cmake                         |   14 +-
 Modules/Compiler/SunPro-ASM.cmake                  |   10 +-
 Modules/Compiler/SunPro-C.cmake                    |   10 +-
 Modules/Compiler/SunPro-CXX.cmake                  |   10 +-
 Modules/Compiler/SunPro-Fortran.cmake              |   13 +-
 Modules/Compiler/TinyCC-C.cmake                    |   10 +-
 Modules/Compiler/XL-ASM.cmake                      |   10 +-
 Modules/Compiler/XL-C.cmake                        |    6 +-
 Modules/Compiler/XL-CXX.cmake                      |    6 +-
 Modules/Compiler/XL-Fortran.cmake                  |    2 +-
 Modules/Compiler/XL.cmake                          |   22 +-
 Modules/CompilerId/Xcode-3.pbxproj.in              |    1 +
 Modules/Dart.cmake                                 |   18 +-
 Modules/DeployQt4.cmake                            |   20 +-
 Modules/Documentation.cmake                        |   16 +-
 Modules/ExternalData.cmake                         |  111 +-
 Modules/ExternalProject-download.cmake.in          |  101 +-
 Modules/ExternalProject-verify.cmake.in            |   15 +-
 Modules/ExternalProject.cmake                      |  138 +-
 Modules/FLTKCompatibility.cmake                    |   14 +-
 Modules/FeatureSummary.cmake                       |  695 ++-
 Modules/FindALSA.cmake                             |   17 +-
 Modules/FindASPELL.cmake                           |   17 +-
 Modules/FindAVIFile.cmake                          |   16 +-
 Modules/FindArmadillo.cmake                        |   17 +-
 Modules/FindBISON.cmake                            |  152 +-
 Modules/FindBLAS.cmake                             |   16 +-
 Modules/FindBZip2.cmake                            |   56 +-
 Modules/FindBacktrace.cmake                        |   17 +-
 Modules/FindBoost.cmake                            |  180 +-
 Modules/FindBullet.cmake                           |   17 +-
 Modules/FindCABLE.cmake                            |   16 +-
 Modules/FindCUDA.cmake                             |  234 +-
 Modules/FindCUDA/make2cmake.cmake                  |    2 +-
 Modules/FindCUDA/run_nvcc.cmake                    |   19 +-
 Modules/FindCUDA/select_compute_arch.cmake         |  195 +
 Modules/FindCURL.cmake                             |   17 +-
 Modules/FindCVS.cmake                              |   16 +-
 Modules/FindCoin3D.cmake                           |   16 +-
 Modules/FindCups.cmake                             |   20 +-
 Modules/FindCurses.cmake                           |   16 +-
 Modules/FindCxxTest.cmake                          |   28 +-
 Modules/FindCygwin.cmake                           |   16 +-
 Modules/FindDCMTK.cmake                            |   18 +-
 Modules/FindDart.cmake                             |   16 +-
 Modules/FindDevIL.cmake                            |   17 +-
 Modules/FindDoxygen.cmake                          |   16 +-
 Modules/FindEXPAT.cmake                            |   24 +-
 Modules/FindFLEX.cmake                             |   17 +-
 Modules/FindFLTK.cmake                             |   16 +-
 Modules/FindFLTK2.cmake                            |   16 +-
 Modules/FindFreetype.cmake                         |   83 +-
 Modules/FindGCCXML.cmake                           |   16 +-
 Modules/FindGDAL.cmake                             |   16 +-
 Modules/FindGIF.cmake                              |   62 +-
 Modules/FindGLEW.cmake                             |   59 +-
 Modules/FindGLU.cmake                              |   14 +-
 Modules/FindGLUT.cmake                             |   16 +-
 Modules/FindGSL.cmake                              |   16 +-
 Modules/FindGTK.cmake                              |   16 +-
 Modules/FindGTK2.cmake                             |   17 +-
 Modules/FindGTest.cmake                            |   45 +-
 Modules/FindGettext.cmake                          |   17 +-
 Modules/FindGit.cmake                              |   17 +-
 Modules/FindGnuTLS.cmake                           |   19 +-
 Modules/FindGnuplot.cmake                          |   16 +-
 Modules/FindHDF5.cmake                             |   21 +-
 Modules/FindHSPELL.cmake                           |   17 +-
 Modules/FindHTMLHelp.cmake                         |   16 +-
 Modules/FindHg.cmake                               |   18 +-
 Modules/FindICU.cmake                              |  349 ++
 Modules/FindIce.cmake                              |   61 +-
 Modules/FindIcotool.cmake                          |   16 +-
 Modules/FindImageMagick.cmake                      |   18 +-
 Modules/FindIntl.cmake                             |   16 +-
 Modules/FindJNI.cmake                              |   25 +-
 Modules/FindJPEG.cmake                             |   16 +-
 Modules/FindJasper.cmake                           |   18 +-
 Modules/FindJava.cmake                             |   20 +-
 Modules/FindKDE3.cmake                             |   17 +-
 Modules/FindKDE4.cmake                             |   17 +-
 Modules/FindLAPACK.cmake                           |   16 +-
 Modules/FindLATEX.cmake                            |   17 +-
 Modules/FindLTTngUST.cmake                         |   17 +-
 Modules/FindLibArchive.cmake                       |   16 +-
 Modules/FindLibLZMA.cmake                          |   20 +-
 Modules/FindLibXml2.cmake                          |   17 +-
 Modules/FindLibXslt.cmake                          |   17 +-
 Modules/FindLua.cmake                              |  134 +-
 Modules/FindLua50.cmake                            |   16 +-
 Modules/FindLua51.cmake                            |   16 +-
 Modules/FindMFC.cmake                              |   16 +-
 Modules/FindMPEG.cmake                             |   16 +-
 Modules/FindMPEG2.cmake                            |   16 +-
 Modules/FindMPI.cmake                              |   26 +-
 Modules/FindMatlab.cmake                           |  182 +-
 Modules/FindMotif.cmake                            |   16 +-
 Modules/FindOpenAL.cmake                           |   16 +-
 Modules/FindOpenCL.cmake                           |   43 +-
 Modules/FindOpenGL.cmake                           |   16 +-
 Modules/FindOpenMP.cmake                           |  140 +-
 Modules/FindOpenSSL.cmake                          |   83 +-
 Modules/FindOpenSceneGraph.cmake                   |   17 +-
 Modules/FindOpenThreads.cmake                      |   17 +-
 Modules/FindPHP4.cmake                             |   24 +-
 Modules/FindPNG.cmake                              |   31 +-
 Modules/FindPackageHandleStandardArgs.cmake        |   34 +-
 Modules/FindPackageMessage.cmake                   |   16 +-
 Modules/FindPerl.cmake                             |   16 +-
 Modules/FindPerlLibs.cmake                         |   17 +-
 Modules/FindPhysFS.cmake                           |   16 +-
 Modules/FindPike.cmake                             |   16 +-
 Modules/FindPkgConfig.cmake                        |   29 +-
 Modules/FindPostgreSQL.cmake                       |   22 +-
 Modules/FindProducer.cmake                         |   16 +-
 Modules/FindProtobuf.cmake                         |   30 +-
 Modules/FindPythonInterp.cmake                     |   20 +-
 Modules/FindPythonLibs.cmake                       |   18 +-
 Modules/FindQt.cmake                               |   16 +-
 Modules/FindQt3.cmake                              |   16 +-
 Modules/FindQt4.cmake                              |   18 +-
 Modules/FindQuickTime.cmake                        |   16 +-
 Modules/FindRTI.cmake                              |   17 +-
 Modules/FindRuby.cmake                             |   17 +-
 Modules/FindSDL.cmake                              |   17 +-
 Modules/FindSDL_image.cmake                        |   17 +-
 Modules/FindSDL_mixer.cmake                        |   17 +-
 Modules/FindSDL_net.cmake                          |   17 +-
 Modules/FindSDL_sound.cmake                        |   21 +-
 Modules/FindSDL_ttf.cmake                          |   17 +-
 Modules/FindSWIG.cmake                             |   18 +-
 Modules/FindSelfPackers.cmake                      |   16 +-
 Modules/FindSquish.cmake                           |   18 +-
 Modules/FindSubversion.cmake                       |   17 +-
 Modules/FindTCL.cmake                              |   16 +-
 Modules/FindTIFF.cmake                             |   31 +-
 Modules/FindTclStub.cmake                          |   16 +-
 Modules/FindTclsh.cmake                            |   16 +-
 Modules/FindThreads.cmake                          |   17 +-
 Modules/FindUnixCommands.cmake                     |   16 +-
 Modules/FindVulkan.cmake                           |   75 +
 Modules/FindWget.cmake                             |   16 +-
 Modules/FindWish.cmake                             |   16 +-
 Modules/FindX11.cmake                              |   16 +-
 Modules/FindXCTest.cmake                           |   16 +-
 Modules/FindXMLRPC.cmake                           |   16 +-
 Modules/FindXalanC.cmake                           |   30 +-
 Modules/FindXercesC.cmake                          |   30 +-
 Modules/FindZLIB.cmake                             |   20 +-
 Modules/Findosg.cmake                              |   16 +-
 Modules/FindosgAnimation.cmake                     |   16 +-
 Modules/FindosgDB.cmake                            |   16 +-
 Modules/FindosgFX.cmake                            |   16 +-
 Modules/FindosgGA.cmake                            |   16 +-
 Modules/FindosgIntrospection.cmake                 |   16 +-
 Modules/FindosgManipulator.cmake                   |   16 +-
 Modules/FindosgParticle.cmake                      |   16 +-
 Modules/FindosgPresentation.cmake                  |   16 +-
 Modules/FindosgProducer.cmake                      |   16 +-
 Modules/FindosgQt.cmake                            |   16 +-
 Modules/FindosgShadow.cmake                        |   16 +-
 Modules/FindosgSim.cmake                           |   16 +-
 Modules/FindosgTerrain.cmake                       |   16 +-
 Modules/FindosgText.cmake                          |   16 +-
 Modules/FindosgUtil.cmake                          |   16 +-
 Modules/FindosgViewer.cmake                        |   16 +-
 Modules/FindosgVolume.cmake                        |   16 +-
 Modules/FindosgWidget.cmake                        |   16 +-
 Modules/Findosg_functions.cmake                    |   17 +-
 Modules/FindwxWidgets.cmake                        |   60 +-
 Modules/FindwxWindows.cmake                        |   19 +-
 Modules/FortranCInterface.cmake                    |   24 +-
 Modules/FortranCInterface/CMakeLists.txt           |   12 +-
 Modules/FortranCInterface/Detect.cmake             |   12 +-
 Modules/FortranCInterface/Verify/CMakeLists.txt    |   12 +-
 Modules/GNUInstallDirs.cmake                       |   97 +-
 Modules/GenerateExportHeader.cmake                 |   40 +-
 Modules/GetPrerequisites.cmake                     |   30 +-
 Modules/ITKCompatibility.cmake                     |   14 +-
 Modules/InstallRequiredSystemLibraries.cmake       |   16 +-
 Modules/KDE3Macros.cmake                           |   15 +-
 Modules/MacroAddFileDependencies.cmake             |   16 +-
 Modules/MatlabTestsRedirect.cmake                  |   60 +-
 Modules/NSIS.template.in                           |   11 +-
 Modules/Platform/AIX-Clang-C.cmake                 |    1 +
 Modules/Platform/AIX-Clang-CXX.cmake               |    1 +
 Modules/Platform/AIX-GNU-CXX.cmake                 |    1 +
 Modules/Platform/AIX-GNU.cmake                     |   21 +-
 Modules/Platform/AIX-XL.cmake                      |   20 +-
 Modules/Platform/ARTOS-GNU-C.cmake                 |   10 +-
 Modules/Platform/Android-Clang-C.cmake             |    2 +
 Modules/Platform/Android-Clang-CXX.cmake           |    2 +
 Modules/Platform/Android-Clang.cmake               |   42 +
 Modules/Platform/Android-Common.cmake              |  148 +
 Modules/Platform/Android-Determine-C.cmake         |    2 +
 Modules/Platform/Android-Determine-CXX.cmake       |    2 +
 Modules/Platform/Android-Determine.cmake           |  291 ++
 Modules/Platform/Android-GNU-C.cmake               |    2 +
 Modules/Platform/Android-GNU-CXX.cmake             |    2 +
 Modules/Platform/Android-GNU.cmake                 |   33 +
 Modules/Platform/Android-Initialize.cmake          |   41 +
 Modules/Platform/Android.cmake                     |    2 +
 .../Platform/Android/Determine-Compiler-NDK.cmake  |  246 +
 .../Android/Determine-Compiler-Standalone.cmake    |   59 +
 Modules/Platform/Android/Determine-Compiler.cmake  |   70 +
 Modules/Platform/Android/abi-arm64-v8a-Clang.cmake |    8 +
 Modules/Platform/Android/abi-arm64-v8a-GNU.cmake   |    6 +
 Modules/Platform/Android/abi-armeabi-Clang.cmake   |   20 +
 Modules/Platform/Android/abi-armeabi-GNU.cmake     |   18 +
 .../Platform/Android/abi-armeabi-v6-Clang.cmake    |   19 +
 Modules/Platform/Android/abi-armeabi-v6-GNU.cmake  |   17 +
 .../Platform/Android/abi-armeabi-v7a-Clang.cmake   |   29 +
 Modules/Platform/Android/abi-armeabi-v7a-GNU.cmake |   27 +
 Modules/Platform/Android/abi-common-Clang.cmake    |    6 +
 Modules/Platform/Android/abi-common-GNU.cmake      |    1 +
 Modules/Platform/Android/abi-common.cmake          |    4 +
 Modules/Platform/Android/abi-mips-Clang.cmake      |    8 +
 Modules/Platform/Android/abi-mips-GNU.cmake        |    6 +
 Modules/Platform/Android/abi-mips64-Clang.cmake    |    8 +
 Modules/Platform/Android/abi-mips64-GNU.cmake      |    6 +
 Modules/Platform/Android/abi-x86-Clang.cmake       |    8 +
 Modules/Platform/Android/abi-x86-GNU.cmake         |    2 +
 Modules/Platform/Android/abi-x86_64-Clang.cmake    |    8 +
 Modules/Platform/Android/abi-x86_64-GNU.cmake      |    2 +
 Modules/Platform/Android/ndk-stl-c++.cmake         |   21 +
 Modules/Platform/Android/ndk-stl-c++_shared.cmake  |    4 +
 Modules/Platform/Android/ndk-stl-c++_static.cmake  |    6 +
 Modules/Platform/Android/ndk-stl-gabi++.cmake      |    7 +
 .../Platform/Android/ndk-stl-gabi++_shared.cmake   |    4 +
 .../Platform/Android/ndk-stl-gabi++_static.cmake   |    4 +
 Modules/Platform/Android/ndk-stl-gnustl.cmake      |    9 +
 .../Platform/Android/ndk-stl-gnustl_shared.cmake   |    4 +
 .../Platform/Android/ndk-stl-gnustl_static.cmake   |    4 +
 Modules/Platform/Android/ndk-stl-none.cmake        |    2 +
 Modules/Platform/Android/ndk-stl-stlport.cmake     |    7 +
 .../Platform/Android/ndk-stl-stlport_shared.cmake  |    4 +
 .../Platform/Android/ndk-stl-stlport_static.cmake  |    4 +
 Modules/Platform/Android/ndk-stl-system.cmake      |    6 +
 Modules/Platform/BlueGeneP-base.cmake              |   15 +-
 Modules/Platform/BlueGeneP-dynamic-GNU-C.cmake     |   15 +-
 Modules/Platform/BlueGeneP-dynamic-GNU-CXX.cmake   |   15 +-
 .../Platform/BlueGeneP-dynamic-GNU-Fortran.cmake   |   15 +-
 Modules/Platform/BlueGeneP-dynamic-XL-C.cmake      |   15 +-
 Modules/Platform/BlueGeneP-dynamic-XL-CXX.cmake    |   15 +-
 .../Platform/BlueGeneP-dynamic-XL-Fortran.cmake    |   15 +-
 Modules/Platform/BlueGeneP-dynamic.cmake           |   15 +-
 Modules/Platform/BlueGeneP-static-GNU-C.cmake      |   15 +-
 Modules/Platform/BlueGeneP-static-GNU-CXX.cmake    |   15 +-
 .../Platform/BlueGeneP-static-GNU-Fortran.cmake    |   15 +-
 Modules/Platform/BlueGeneP-static-XL-C.cmake       |   15 +-
 Modules/Platform/BlueGeneP-static-XL-CXX.cmake     |   15 +-
 Modules/Platform/BlueGeneP-static-XL-Fortran.cmake |   15 +-
 Modules/Platform/BlueGeneP-static.cmake            |   15 +-
 Modules/Platform/BlueGeneQ-base.cmake              |   17 +-
 Modules/Platform/BlueGeneQ-dynamic-GNU-C.cmake     |   15 +-
 Modules/Platform/BlueGeneQ-dynamic-GNU-CXX.cmake   |   15 +-
 .../Platform/BlueGeneQ-dynamic-GNU-Fortran.cmake   |   15 +-
 Modules/Platform/BlueGeneQ-dynamic-XL-C.cmake      |   15 +-
 Modules/Platform/BlueGeneQ-dynamic-XL-CXX.cmake    |   15 +-
 .../Platform/BlueGeneQ-dynamic-XL-Fortran.cmake    |   15 +-
 Modules/Platform/BlueGeneQ-dynamic.cmake           |   15 +-
 Modules/Platform/BlueGeneQ-static-GNU-C.cmake      |   15 +-
 Modules/Platform/BlueGeneQ-static-GNU-CXX.cmake    |   15 +-
 .../Platform/BlueGeneQ-static-GNU-Fortran.cmake    |   15 +-
 Modules/Platform/BlueGeneQ-static-XL-C.cmake       |   15 +-
 Modules/Platform/BlueGeneQ-static-XL-CXX.cmake     |   15 +-
 Modules/Platform/BlueGeneQ-static-XL-Fortran.cmake |   15 +-
 Modules/Platform/BlueGeneQ-static.cmake            |   15 +-
 ...CYGWIN-CXX.cmake => CYGWIN-Determine-CXX.cmake} |    0
 Modules/Platform/CYGWIN-GNU.cmake                  |   16 +-
 Modules/Platform/Darwin-Absoft-Fortran.cmake       |   15 +-
 Modules/Platform/Darwin-Clang.cmake                |   14 +-
 ...Darwin-CXX.cmake => Darwin-Determine-CXX.cmake} |    0
 Modules/Platform/Darwin-GNU-Fortran.cmake          |   15 +-
 Modules/Platform/Darwin-GNU.cmake                  |   14 +-
 Modules/Platform/Darwin-Initialize.cmake           |    8 +-
 Modules/Platform/Darwin-Intel-Fortran.cmake        |   14 +-
 Modules/Platform/Darwin-Intel.cmake                |   14 +-
 Modules/Platform/Darwin-NAG-Fortran.cmake          |   15 +-
 Modules/Platform/GHS-MULTI-Initialize.cmake        |   14 +-
 Modules/Platform/GHS-MULTI.cmake                   |   14 +-
 Modules/Platform/Generic-ADSP-C.cmake              |    8 +-
 Modules/Platform/Generic-ADSP-CXX.cmake            |    8 +-
 Modules/Platform/Generic-SDCC-C.cmake              |    2 +-
 Modules/Platform/HP-UX-GNU-CXX.cmake               |    1 +
 Modules/Platform/HP-UX-GNU.cmake                   |   15 +-
 Modules/Platform/HP-UX-HP-CXX.cmake                |    8 +-
 Modules/Platform/HP-UX-HP.cmake                    |   16 +-
 .../{Linux-CXX.cmake => Linux-Determine-CXX.cmake} |    0
 Modules/Platform/Linux-GNU.cmake                   |   14 +-
 Modules/Platform/Linux-Intel-Fortran.cmake         |    2 +-
 Modules/Platform/Linux-Intel.cmake                 |   14 +-
 Modules/Platform/Linux-PGI.cmake                   |   14 +-
 Modules/Platform/Linux-PathScale.cmake             |   14 +-
 Modules/Platform/Linux.cmake                       |    3 +-
 Modules/Platform/OpenBSD.cmake                     |    1 +
 Modules/Platform/SCO_SV.cmake                      |    1 +
 Modules/Platform/SunOS-GNU.cmake                   |   14 +-
 Modules/Platform/SunOS-PathScale.cmake             |   14 +-
 Modules/Platform/UnixPaths.cmake                   |   17 +-
 Modules/Platform/Windows-Clang.cmake               |   14 +-
 ...ndows-CXX.cmake => Windows-Determine-CXX.cmake} |    0
 Modules/Platform/Windows-Embarcadero.cmake         |   38 +-
 Modules/Platform/Windows-GNU.cmake                 |   14 +-
 Modules/Platform/Windows-Intel-Fortran.cmake       |   10 +-
 Modules/Platform/Windows-Intel.cmake               |   14 +-
 Modules/Platform/Windows-MSVC.cmake                |   98 +-
 Modules/Platform/Windows-OpenWatcom-C.cmake        |    1 +
 Modules/Platform/Windows-OpenWatcom-CXX.cmake      |    1 +
 Modules/Platform/Windows-OpenWatcom.cmake          |  129 +
 Modules/Platform/Windows-Watcom-C.cmake            |    1 +
 Modules/Platform/Windows-Watcom-CXX.cmake          |    1 +
 Modules/Platform/Windows-wcl386.cmake              |  119 -
 Modules/Platform/WindowsPaths.cmake                |   14 +-
 Modules/ProcessorCount.cmake                       |   16 +-
 Modules/Qt4ConfigDependentSettings.cmake           |   17 +-
 Modules/Qt4Macros.cmake                            |   21 +-
 Modules/SelectLibraryConfigurations.cmake          |   17 +-
 Modules/SquishTestScript.cmake                     |   16 +-
 Modules/SystemInformation.cmake                    |   14 +-
 Modules/TestBigEndian.cmake                        |   16 +-
 Modules/TestCXXAcceptsFlag.cmake                   |   16 +-
 Modules/TestForANSIForScope.cmake                  |   16 +-
 Modules/TestForANSIStreamHeaders.cmake             |   16 +-
 Modules/TestForSSTREAM.cmake                       |   16 +-
 Modules/TestForSTDNamespace.cmake                  |   16 +-
 Modules/UseEcos.cmake                              |   16 +-
 Modules/UseJava.cmake                              |  187 +-
 Modules/UseJavaClassFilelist.cmake                 |   16 +-
 Modules/UseJavaSymlinks.cmake                      |   16 +-
 Modules/UsePkgConfig.cmake                         |   16 +-
 Modules/UseQt4.cmake                               |   16 +-
 Modules/UseSWIG.cmake                              |   29 +-
 Modules/Use_wxWindows.cmake                        |   19 +-
 Modules/UsewxWidgets.cmake                         |   19 +-
 Modules/VTKCompatibility.cmake                     |   14 +-
 Modules/WriteBasicConfigVersionFile.cmake          |   17 +-
 Modules/WriteCompilerDetectionHeader.cmake         |   72 +-
 Modules/ecos_clean.cmake                           |   14 +-
 Modules/exportheader.cmake.in                      |    2 +-
 Modules/javaTargets.cmake.in                       |   39 +
 Modules/kde3uic.cmake                              |   15 +-
 Source/.cvsignore                                  |    5 -
 Source/.gitattributes                              |    2 +
 Source/CMakeInstallDestinations.cmake              |    5 +
 Source/CMakeLists.txt                              |   76 +-
 Source/CMakeVersion.cmake                          |    6 +-
 Source/CMakeVersionCompute.cmake                   |   17 +-
 Source/CMakeVersionSource.cmake                    |    9 +-
 Source/CPack/IFW/cmCPackIFWGenerator.cxx           |   98 +-
 Source/CPack/IFW/cmCPackIFWGenerator.h             |   53 +-
 Source/CPack/IFW/cmCPackIFWInstaller.cxx           |  117 +-
 Source/CPack/IFW/cmCPackIFWInstaller.h             |   25 +-
 Source/CPack/IFW/cmCPackIFWPackage.cxx             |   86 +-
 Source/CPack/IFW/cmCPackIFWPackage.h               |   25 +-
 Source/CPack/IFW/cmCPackIFWRepository.cxx          |   63 +-
 Source/CPack/IFW/cmCPackIFWRepository.h            |   19 +-
 Source/CPack/OSXScriptLauncher.cxx                 |   15 +-
 Source/CPack/WiX/cmCPackWIXGenerator.cxx           |   79 +-
 Source/CPack/WiX/cmCPackWIXGenerator.h             |   16 +-
 Source/CPack/WiX/cmWIXAccessControlList.cxx        |   16 +-
 Source/CPack/WiX/cmWIXAccessControlList.h          |   14 +-
 Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx  |   30 +-
 Source/CPack/WiX/cmWIXDirectoriesSourceWriter.h    |   18 +-
 Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx     |   36 +-
 Source/CPack/WiX/cmWIXFeaturesSourceWriter.h       |   24 +-
 Source/CPack/WiX/cmWIXFilesSourceWriter.cxx        |   28 +-
 Source/CPack/WiX/cmWIXFilesSourceWriter.h          |   17 +-
 Source/CPack/WiX/cmWIXPatch.cxx                    |   14 +-
 Source/CPack/WiX/cmWIXPatch.h                      |   14 +-
 Source/CPack/WiX/cmWIXPatchParser.cxx              |   16 +-
 Source/CPack/WiX/cmWIXPatchParser.h                |   14 +-
 Source/CPack/WiX/cmWIXRichTextFormatWriter.cxx     |   14 +-
 Source/CPack/WiX/cmWIXRichTextFormatWriter.h       |   16 +-
 Source/CPack/WiX/cmWIXShortcut.cxx                 |   14 +-
 Source/CPack/WiX/cmWIXShortcut.h                   |   14 +-
 Source/CPack/WiX/cmWIXSourceWriter.cxx             |   35 +-
 Source/CPack/WiX/cmWIXSourceWriter.h               |   33 +-
 Source/CPack/cmCPack7zGenerator.cxx                |   17 +-
 Source/CPack/cmCPack7zGenerator.h                  |   22 +-
 Source/CPack/cmCPackArchiveGenerator.cxx           |   55 +-
 Source/CPack/cmCPackArchiveGenerator.h             |   33 +-
 Source/CPack/cmCPackBundleGenerator.cxx            |   22 +-
 Source/CPack/cmCPackBundleGenerator.h              |   22 +-
 Source/CPack/cmCPackComponentGroup.cxx             |   14 +-
 Source/CPack/cmCPackComponentGroup.h               |   23 +-
 Source/CPack/cmCPackConfigure.h.in                 |   13 +-
 Source/CPack/cmCPackCygwinBinaryGenerator.cxx      |   14 +-
 Source/CPack/cmCPackCygwinBinaryGenerator.h        |   14 +-
 Source/CPack/cmCPackCygwinSourceGenerator.cxx      |   14 +-
 Source/CPack/cmCPackCygwinSourceGenerator.h        |   14 +-
 Source/CPack/cmCPackDebGenerator.cxx               |  113 +-
 Source/CPack/cmCPackDebGenerator.h                 |   34 +-
 Source/CPack/cmCPackDragNDropGenerator.cxx         |   21 +-
 Source/CPack/cmCPackDragNDropGenerator.h           |   24 +-
 Source/CPack/cmCPackGenerator.cxx                  |   87 +-
 Source/CPack/cmCPackGenerator.h                    |   36 +-
 Source/CPack/cmCPackGeneratorFactory.cxx           |   26 +-
 Source/CPack/cmCPackGeneratorFactory.h             |   25 +-
 Source/CPack/cmCPackLog.cxx                        |   24 +-
 Source/CPack/cmCPackLog.h                          |   23 +-
 Source/CPack/cmCPackNSISGenerator.cxx              |   88 +-
 Source/CPack/cmCPackNSISGenerator.h                |   51 +-
 Source/CPack/cmCPackOSXX11Generator.cxx            |   47 +-
 Source/CPack/cmCPackOSXX11Generator.h              |   22 +-
 Source/CPack/cmCPackPKGGenerator.cxx               |  357 ++
 Source/CPack/cmCPackPKGGenerator.h                 |   86 +
 Source/CPack/cmCPackPackageMakerGenerator.cxx      |  409 +-
 Source/CPack/cmCPackPackageMakerGenerator.h        |   88 +-
 Source/CPack/cmCPackProductBuildGenerator.cxx      |  222 +
 Source/CPack/cmCPackProductBuildGenerator.h        |   48 +
 Source/CPack/cmCPackRPMGenerator.cxx               |   44 +-
 Source/CPack/cmCPackRPMGenerator.h                 |   33 +-
 Source/CPack/cmCPackSTGZGenerator.cxx              |   22 +-
 Source/CPack/cmCPackSTGZGenerator.h                |   30 +-
 Source/CPack/cmCPackTGZGenerator.cxx               |   17 +-
 Source/CPack/cmCPackTGZGenerator.h                 |   22 +-
 Source/CPack/cmCPackTXZGenerator.cxx               |   17 +-
 Source/CPack/cmCPackTXZGenerator.h                 |   22 +-
 Source/CPack/cmCPackTarBZip2Generator.cxx          |   17 +-
 Source/CPack/cmCPackTarBZip2Generator.h            |   22 +-
 Source/CPack/cmCPackTarCompressGenerator.cxx       |   17 +-
 Source/CPack/cmCPackTarCompressGenerator.h         |   24 +-
 Source/CPack/cmCPackZIPGenerator.cxx               |   17 +-
 Source/CPack/cmCPackZIPGenerator.h                 |   22 +-
 Source/CPack/cpack.cxx                             |   55 +-
 Source/CPack/cygwin.readme                         |   69 -
 Source/CTest/cmCTestBZR.cxx                        |   72 +-
 Source/CTest/cmCTestBZR.h                          |   39 +-
 Source/CTest/cmCTestBatchTestHandler.cxx           |   26 +-
 Source/CTest/cmCTestBatchTestHandler.h             |   27 +-
 Source/CTest/cmCTestBuildAndTestHandler.cxx        |   41 +-
 Source/CTest/cmCTestBuildAndTestHandler.h          |   33 +-
 Source/CTest/cmCTestBuildCommand.cxx               |   36 +-
 Source/CTest/cmCTestBuildCommand.h                 |   36 +-
 Source/CTest/cmCTestBuildHandler.cxx               |   61 +-
 Source/CTest/cmCTestBuildHandler.h                 |   31 +-
 Source/CTest/cmCTestCVS.cxx                        |   29 +-
 Source/CTest/cmCTestCVS.h                          |   34 +-
 Source/CTest/cmCTestCommand.h                      |   17 +-
 Source/CTest/cmCTestConfigureCommand.cxx           |   37 +-
 Source/CTest/cmCTestConfigureCommand.h             |   27 +-
 Source/CTest/cmCTestConfigureHandler.cxx           |   20 +-
 Source/CTest/cmCTestConfigureHandler.h             |   23 +-
 Source/CTest/cmCTestCoverageCommand.cxx            |   17 +-
 Source/CTest/cmCTestCoverageCommand.h              |   32 +-
 Source/CTest/cmCTestCoverageHandler.cxx            |   80 +-
 Source/CTest/cmCTestCoverageHandler.h              |   32 +-
 Source/CTest/cmCTestCurl.cxx                       |   64 +-
 Source/CTest/cmCTestCurl.h                         |   19 +-
 .../CTest/cmCTestEmptyBinaryDirectoryCommand.cxx   |   19 +-
 Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h  |   30 +-
 Source/CTest/cmCTestGIT.cxx                        |   66 +-
 Source/CTest/cmCTestGIT.h                          |   41 +-
 Source/CTest/cmCTestGenericHandler.cxx             |   22 +-
 Source/CTest/cmCTestGenericHandler.h               |   28 +-
 Source/CTest/cmCTestGlobalVC.cxx                   |   16 +-
 Source/CTest/cmCTestGlobalVC.h                     |   26 +-
 Source/CTest/cmCTestHG.cxx                         |   47 +-
 Source/CTest/cmCTestHG.h                           |   37 +-
 Source/CTest/cmCTestHandlerCommand.cxx             |  139 +-
 Source/CTest/cmCTestHandlerCommand.h               |   26 +-
 Source/CTest/cmCTestLaunch.cxx                     |   55 +-
 Source/CTest/cmCTestLaunch.h                       |   18 +-
 Source/CTest/cmCTestMemCheckCommand.cxx            |   13 +-
 Source/CTest/cmCTestMemCheckCommand.h              |   25 +-
 Source/CTest/cmCTestMemCheckHandler.cxx            |  121 +-
 Source/CTest/cmCTestMemCheckHandler.h              |   31 +-
 Source/CTest/cmCTestMultiProcessHandler.cxx        |   65 +-
 Source/CTest/cmCTestMultiProcessHandler.h          |   25 +-
 Source/CTest/cmCTestP4.cxx                         |   52 +-
 Source/CTest/cmCTestP4.h                           |   38 +-
 Source/CTest/cmCTestReadCustomFilesCommand.cxx     |   19 +-
 Source/CTest/cmCTestReadCustomFilesCommand.h       |   30 +-
 Source/CTest/cmCTestRunScriptCommand.cxx           |   22 +-
 Source/CTest/cmCTestRunScriptCommand.h             |   30 +-
 Source/CTest/cmCTestRunTest.cxx                    |   66 +-
 Source/CTest/cmCTestRunTest.h                      |   27 +-
 Source/CTest/cmCTestSVN.cxx                        |   70 +-
 Source/CTest/cmCTestSVN.h                          |   43 +-
 Source/CTest/cmCTestScriptHandler.cxx              |   96 +-
 Source/CTest/cmCTestScriptHandler.h                |   31 +-
 Source/CTest/cmCTestSleepCommand.cxx               |   22 +-
 Source/CTest/cmCTestSleepCommand.h                 |   30 +-
 Source/CTest/cmCTestStartCommand.cxx               |   31 +-
 Source/CTest/cmCTestStartCommand.h                 |   31 +-
 Source/CTest/cmCTestSubmitCommand.cxx              |   24 +-
 Source/CTest/cmCTestSubmitCommand.h                |   39 +-
 Source/CTest/cmCTestSubmitHandler.cxx              |   95 +-
 Source/CTest/cmCTestSubmitHandler.h                |   29 +-
 Source/CTest/cmCTestTestCommand.cxx                |   21 +-
 Source/CTest/cmCTestTestCommand.h                  |   27 +-
 Source/CTest/cmCTestTestHandler.cxx                |  313 +-
 Source/CTest/cmCTestTestHandler.h                  |   42 +-
 Source/CTest/cmCTestUpdateCommand.cxx              |   21 +-
 Source/CTest/cmCTestUpdateCommand.h                |   27 +-
 Source/CTest/cmCTestUpdateHandler.cxx              |   45 +-
 Source/CTest/cmCTestUpdateHandler.h                |   25 +-
 Source/CTest/cmCTestUploadCommand.cxx              |   41 +-
 Source/CTest/cmCTestUploadCommand.h                |   33 +-
 Source/CTest/cmCTestUploadHandler.cxx              |   17 +-
 Source/CTest/cmCTestUploadHandler.h                |   23 +-
 Source/CTest/cmCTestVC.cxx                         |   21 +-
 Source/CTest/cmCTestVC.h                           |   27 +-
 Source/CTest/cmParseBlanketJSCoverage.cxx          |   21 +-
 Source/CTest/cmParseBlanketJSCoverage.h            |   23 +-
 Source/CTest/cmParseCacheCoverage.cxx              |    6 +-
 Source/CTest/cmParseCacheCoverage.h                |   24 +-
 Source/CTest/cmParseCoberturaCoverage.cxx          |   15 +-
 Source/CTest/cmParseCoberturaCoverage.h            |   23 +-
 Source/CTest/cmParseDelphiCoverage.cxx             |    5 +-
 Source/CTest/cmParseDelphiCoverage.h               |   23 +-
 Source/CTest/cmParseGTMCoverage.cxx                |    6 +-
 Source/CTest/cmParseGTMCoverage.h                  |   23 +-
 Source/CTest/cmParseJacocoCoverage.cxx             |   15 +-
 Source/CTest/cmParseJacocoCoverage.h               |   24 +-
 Source/CTest/cmParseMumpsCoverage.cxx              |   32 +-
 Source/CTest/cmParseMumpsCoverage.h                |   22 +-
 Source/CTest/cmParsePHPCoverage.cxx                |   10 +-
 Source/CTest/cmParsePHPCoverage.h                  |   22 +-
 Source/CTest/cmProcess.cxx                         |   28 +-
 Source/CTest/cmProcess.h                           |   17 +-
 Source/Checks/cm_cxx11_unordered_map.cmake         |   25 -
 Source/Checks/cm_cxx_auto_ptr.cxx                  |   18 +
 Source/Checks/cm_cxx_features.cmake                |   45 +
 Source/Checks/cm_cxx_make_unique.cxx               |    6 +
 Source/Checks/cm_cxx_nullptr.cxx                   |   14 +
 Source/Checks/cm_cxx_override.cxx                  |   24 +
 Source/Checks/cm_cxx_unique_ptr.cxx                |    6 +
 ..._unordered_map.cpp => cm_cxx_unordered_map.cxx} |    0
 Source/Checks/cm_cxx_unordered_set.cxx             |    7 +
 Source/CursesDialog/CMakeLists.txt                 |   15 +-
 Source/CursesDialog/ccmake.cxx                     |   67 +-
 Source/CursesDialog/cmCursesBoolWidget.cxx         |   33 +-
 Source/CursesDialog/cmCursesBoolWidget.h           |   18 +-
 .../CursesDialog/cmCursesCacheEntryComposite.cxx   |   30 +-
 Source/CursesDialog/cmCursesCacheEntryComposite.h  |   21 +-
 Source/CursesDialog/cmCursesDummyWidget.cxx        |   19 +-
 Source/CursesDialog/cmCursesDummyWidget.h          |   18 +-
 Source/CursesDialog/cmCursesFilePathWidget.cxx     |   16 +-
 Source/CursesDialog/cmCursesFilePathWidget.h       |   15 +-
 Source/CursesDialog/cmCursesForm.cxx               |   19 +-
 Source/CursesDialog/cmCursesForm.h                 |   15 +-
 Source/CursesDialog/cmCursesLabelWidget.cxx        |   18 +-
 Source/CursesDialog/cmCursesLabelWidget.h          |   22 +-
 Source/CursesDialog/cmCursesLongMessageForm.cxx    |   37 +-
 Source/CursesDialog/cmCursesLongMessageForm.h      |   27 +-
 Source/CursesDialog/cmCursesMainForm.cxx           |   92 +-
 Source/CursesDialog/cmCursesMainForm.h             |   33 +-
 Source/CursesDialog/cmCursesOptionsWidget.cxx      |   64 +-
 Source/CursesDialog/cmCursesOptionsWidget.h        |   21 +-
 Source/CursesDialog/cmCursesPathWidget.cxx         |   17 +-
 Source/CursesDialog/cmCursesPathWidget.h           |   26 +-
 Source/CursesDialog/cmCursesStandardIncludes.h     |   19 +-
 Source/CursesDialog/cmCursesStringWidget.cxx       |   52 +-
 Source/CursesDialog/cmCursesStringWidget.h         |   24 +-
 Source/CursesDialog/cmCursesWidget.cxx             |   17 +-
 Source/CursesDialog/cmCursesWidget.h               |   18 +-
 Source/CursesDialog/form/CMakeLists.txt            |   14 +-
 Source/CursesDialog/form/cmFormConfigure.h.in      |   14 +-
 Source/CursesDialog/form/form.h                    |    4 -
 Source/Modules/FindJsonCpp.cmake                   |   16 +-
 Source/Modules/FindLibUV.cmake                     |  121 +
 Source/QtDialog/AddCacheEntry.cxx                  |   17 +-
 Source/QtDialog/AddCacheEntry.h                    |   14 +-
 Source/QtDialog/CMakeLists.txt                     |   25 +-
 Source/QtDialog/CMakeSetup.cxx                     |   37 +-
 Source/QtDialog/CMakeSetup64.png                   |  Bin 0 -> 7213 bytes
 Source/QtDialog/CMakeSetupDialog.cxx               |   64 +-
 Source/QtDialog/CMakeSetupDialog.h                 |   16 +-
 Source/QtDialog/CMakeSetupDialog.ui                |    7 +
 Source/QtDialog/Compilers.h                        |    4 +-
 Source/QtDialog/FirstConfigure.cxx                 |   21 +-
 Source/QtDialog/QCMake.cxx                         |   14 +-
 Source/QtDialog/QCMake.h                           |   18 +-
 Source/QtDialog/QCMakeCacheView.cxx                |   47 +-
 Source/QtDialog/QCMakeCacheView.h                  |   14 +-
 Source/QtDialog/QCMakeWidgets.cxx                  |   20 +-
 Source/QtDialog/QCMakeWidgets.h                    |   21 +-
 Source/QtDialog/RegexExplorer.cxx                  |   14 +-
 Source/QtDialog/RegexExplorer.h                    |   14 +-
 Source/QtDialog/WarningMessagesDialog.cxx          |   14 +-
 Source/QtDialog/WarningMessagesDialog.h            |   14 +-
 Source/QtIFW/CMake.DeveloperReference.HTML.qs.in   |   21 +
 Source/QtIFW/cmake.org.html                        |    2 +-
 Source/QtIFW/installscript.qs.in                   |    3 +-
 Source/bindexplib.cxx                              |   17 +-
 Source/bindexplib.h                                |   16 +-
 Source/cmAddCompileOptionsCommand.cxx              |   15 +-
 Source/cmAddCompileOptionsCommand.h                |   21 +-
 Source/cmAddCustomCommandCommand.cxx               |   38 +-
 Source/cmAddCustomCommandCommand.h                 |   21 +-
 Source/cmAddCustomTargetCommand.cxx                |   17 +-
 Source/cmAddCustomTargetCommand.h                  |   21 +-
 Source/cmAddDefinitionsCommand.cxx                 |   15 +-
 Source/cmAddDefinitionsCommand.h                   |   21 +-
 Source/cmAddDependenciesCommand.cxx                |   13 +-
 Source/cmAddDependenciesCommand.h                  |   21 +-
 Source/cmAddExecutableCommand.cxx                  |   13 +-
 Source/cmAddExecutableCommand.h                    |   21 +-
 Source/cmAddLibraryCommand.cxx                     |   15 +-
 Source/cmAddLibraryCommand.h                       |   21 +-
 Source/cmAddSubDirectoryCommand.cxx                |   15 +-
 Source/cmAddSubDirectoryCommand.h                  |   21 +-
 Source/cmAddTestCommand.cxx                        |   13 +-
 Source/cmAddTestCommand.h                          |   21 +-
 Source/cmAlgorithms.h                              |   15 +-
 Source/cmArchiveWrite.cxx                          |   34 +-
 Source/cmArchiveWrite.h                            |   31 +-
 Source/cmAuxSourceDirectoryCommand.cxx             |   25 +-
 Source/cmAuxSourceDirectoryCommand.h               |   21 +-
 Source/cmBase32.cxx                                |   99 +
 Source/cmBase32.h                                  |   33 +
 Source/cmBootstrapCommands1.cxx                    |   13 +-
 Source/cmBootstrapCommands2.cxx                    |   13 +-
 Source/cmBreakCommand.cxx                          |   15 +-
 Source/cmBreakCommand.h                            |   23 +-
 Source/cmBuildCommand.cxx                          |   42 +-
 Source/cmBuildCommand.h                            |   21 +-
 Source/cmBuildNameCommand.cxx                      |   15 +-
 Source/cmBuildNameCommand.h                        |   23 +-
 Source/cmCLocaleEnvironmentScope.cxx               |   24 +-
 Source/cmCLocaleEnvironmentScope.h                 |   19 +-
 Source/cmCMakeHostSystemInformationCommand.cxx     |   19 +-
 Source/cmCMakeHostSystemInformationCommand.h       |   23 +-
 Source/cmCMakeMinimumRequired.cxx                  |   13 +-
 Source/cmCMakeMinimumRequired.h                    |   23 +-
 Source/cmCMakePolicyCommand.cxx                    |   30 +-
 Source/cmCMakePolicyCommand.h                      |   23 +-
 Source/cmCPackPropertiesGenerator.cxx              |    7 +-
 Source/cmCPackPropertiesGenerator.h                |   26 +-
 Source/cmCPluginAPI.cxx                            |   48 +-
 Source/cmCPluginAPI.h                              |   13 +-
 Source/cmCTest.cxx                                 |  447 +-
 Source/cmCTest.h                                   |  221 +-
 Source/cmCacheManager.cxx                          |   45 +-
 Source/cmCacheManager.h                            |   33 +-
 Source/cmCallVisualStudioMacro.cxx                 |   17 +-
 Source/cmCallVisualStudioMacro.h                   |   15 +-
 Source/cmCommand.h                                 |   17 +-
 Source/cmCommandArgumentLexer.cxx                  |   26 +-
 Source/cmCommandArgumentLexer.h                    |   13 +-
 Source/cmCommandArgumentLexer.in.l                 |   13 +-
 Source/cmCommandArgumentParser.cxx                 |   26 +-
 Source/cmCommandArgumentParser.y                   |   13 +-
 Source/cmCommandArgumentParserHelper.cxx           |   53 +-
 Source/cmCommandArgumentParserHelper.h             |   18 +-
 Source/cmCommandArgumentParserTokens.h             |   13 +-
 Source/cmCommandArgumentsHelper.cxx                |   51 +-
 Source/cmCommandArgumentsHelper.h                  |   41 +-
 Source/cmCommands.cxx.in                           |   13 +-
 Source/cmCommands.h                                |   15 +-
 Source/cmCommandsForBootstrap.cxx                  |   13 +-
 Source/cmCommonTargetGenerator.cxx                 |  226 +-
 Source/cmCommonTargetGenerator.h                   |   41 +-
 Source/cmComputeComponentGraph.cxx                 |   13 +-
 Source/cmComputeComponentGraph.h                   |   16 +-
 Source/cmComputeLinkDepends.cxx                    |   28 +-
 Source/cmComputeLinkDepends.h                      |   24 +-
 Source/cmComputeLinkInformation.cxx                |   46 +-
 Source/cmComputeLinkInformation.h                  |   28 +-
 Source/cmComputeTargetDepends.cxx                  |   28 +-
 Source/cmComputeTargetDepends.h                    |   22 +-
 Source/cmConditionEvaluator.cxx                    |   73 +-
 Source/cmConditionEvaluator.h                      |   13 +-
 Source/cmConfigure.cmake.h.in                      |   48 +-
 Source/cmConfigureFileCommand.cxx                  |   13 +-
 Source/cmConfigureFileCommand.h                    |   23 +-
 Source/cmContinueCommand.cxx                       |   13 +-
 Source/cmContinueCommand.h                         |   23 +-
 Source/cmCoreTryCompile.cxx                        |   55 +-
 Source/cmCoreTryCompile.h                          |   13 +-
 Source/cmCreateTestSourceList.cxx                  |   13 +-
 Source/cmCreateTestSourceList.h                    |   21 +-
 Source/cmCryptoHash.cxx                            |  160 +-
 Source/cmCryptoHash.h                              |   69 +-
 Source/cmCurl.cxx                                  |   26 +-
 Source/cmCurl.h                                    |   20 +-
 Source/cmCustomCommand.cxx                         |   29 +-
 Source/cmCustomCommand.h                           |   26 +-
 Source/cmCustomCommandGenerator.cxx                |   26 +-
 Source/cmCustomCommandGenerator.h                  |   20 +-
 Source/cmCustomCommandLines.h                      |   29 +
 Source/cmDefinePropertyCommand.cxx                 |   15 +-
 Source/cmDefinePropertyCommand.h                   |   21 +-
 Source/cmDefinitions.cxx                           |   17 +-
 Source/cmDefinitions.h                             |   26 +-
 Source/cmDepends.cxx                               |   37 +-
 Source/cmDepends.h                                 |   24 +-
 Source/cmDependsC.cxx                              |   60 +-
 Source/cmDependsC.h                                |   31 +-
 Source/cmDependsFortran.cxx                        |  116 +-
 Source/cmDependsFortran.h                          |   33 +-
 Source/cmDependsJava.cxx                           |   24 +-
 Source/cmDependsJava.h                             |   33 +-
 Source/cmDependsJavaLexer.cxx                      |   15 +-
 Source/cmDependsJavaLexer.h                        |   13 +-
 Source/cmDependsJavaLexer.in.l                     |   13 +-
 Source/cmDependsJavaParser.cxx                     |   13 +-
 Source/cmDependsJavaParser.y                       |   13 +-
 Source/cmDependsJavaParserHelper.cxx               |   69 +-
 Source/cmDependsJavaParserHelper.h                 |   35 +-
 Source/cmDocumentation.cxx                         |   45 +-
 Source/cmDocumentation.h                           |   29 +-
 Source/cmDocumentationEntry.h                      |   36 +
 Source/cmDocumentationFormatter.cxx                |   19 +-
 Source/cmDocumentationFormatter.h                  |   17 +-
 Source/cmDocumentationSection.cxx                  |   13 +-
 Source/cmDocumentationSection.h                    |   20 +-
 Source/cmDynamicLoader.cxx                         |   28 +-
 Source/cmDynamicLoader.h                           |   15 +-
 Source/cmELF.cxx                                   |  112 +-
 Source/cmELF.h                                     |   18 +-
 Source/cmElseCommand.cxx                           |   13 +-
 Source/cmElseCommand.h                             |   23 +-
 Source/cmElseIfCommand.cxx                         |   13 +-
 Source/cmElseIfCommand.h                           |   23 +-
 Source/cmEnableLanguageCommand.cxx                 |   15 +-
 Source/cmEnableLanguageCommand.h                   |   21 +-
 Source/cmEnableTestingCommand.cxx                  |   13 +-
 Source/cmEnableTestingCommand.h                    |   21 +-
 Source/cmEndForEachCommand.cxx                     |   13 +-
 Source/cmEndForEachCommand.h                       |   26 +-
 Source/cmEndFunctionCommand.cxx                    |   13 +-
 Source/cmEndFunctionCommand.h                      |   26 +-
 Source/cmEndIfCommand.cxx                          |   13 +-
 Source/cmEndIfCommand.h                            |   23 +-
 Source/cmEndMacroCommand.cxx                       |   13 +-
 Source/cmEndMacroCommand.h                         |   26 +-
 Source/cmEndWhileCommand.cxx                       |   13 +-
 Source/cmEndWhileCommand.h                         |   26 +-
 Source/cmExecProgramCommand.cxx                    |   23 +-
 Source/cmExecProgramCommand.h                      |   26 +-
 Source/cmExecuteProcessCommand.cxx                 |   24 +-
 Source/cmExecuteProcessCommand.h                   |   23 +-
 Source/cmExecutionStatus.h                         |   15 +-
 Source/cmExpandedCommandArgument.cxx               |   14 +-
 Source/cmExpandedCommandArgument.h                 |   15 +-
 Source/cmExportBuildAndroidMKGenerator.cxx         |  196 +
 Source/cmExportBuildAndroidMKGenerator.h           |   60 +
 Source/cmExportBuildFileGenerator.cxx              |   38 +-
 Source/cmExportBuildFileGenerator.h                |   39 +-
 Source/cmExportCommand.cxx                         |   45 +-
 Source/cmExportCommand.h                           |   22 +-
 Source/cmExportFileGenerator.cxx                   |   83 +-
 Source/cmExportFileGenerator.h                     |   66 +-
 Source/cmExportInstallAndroidMKGenerator.cxx       |  137 +
 Source/cmExportInstallAndroidMKGenerator.h         |   64 +
 Source/cmExportInstallFileGenerator.cxx            |  175 +-
 Source/cmExportInstallFileGenerator.h              |   53 +-
 Source/cmExportLibraryDependenciesCommand.cxx      |   27 +-
 Source/cmExportLibraryDependenciesCommand.h        |   31 +-
 Source/cmExportSet.cxx                             |   14 +-
 Source/cmExportSet.h                               |   20 +-
 Source/cmExportSetMap.cxx                          |   16 +-
 Source/cmExportSetMap.h                            |   18 +-
 Source/cmExportTryCompileFileGenerator.cxx         |   35 +-
 Source/cmExportTryCompileFileGenerator.h           |   39 +-
 Source/cmExprLexer.cxx                             |   15 +-
 Source/cmExprLexer.h                               |   13 +-
 Source/cmExprLexer.in.l                            |   13 +-
 Source/cmExprParser.cxx                            |   13 +-
 Source/cmExprParser.y                              |   13 +-
 Source/cmExprParserHelper.cxx                      |   26 +-
 Source/cmExprParserHelper.h                        |   21 +-
 Source/cmExternalMakefileProjectGenerator.cxx      |   68 +-
 Source/cmExternalMakefileProjectGenerator.h        |   74 +-
 Source/cmExtraCodeBlocksGenerator.cxx              |  138 +-
 Source/cmExtraCodeBlocksGenerator.h                |   36 +-
 Source/cmExtraCodeLiteGenerator.cxx                |  393 +-
 Source/cmExtraCodeLiteGenerator.h                  |   59 +-
 Source/cmExtraEclipseCDT4Generator.cxx             |   93 +-
 Source/cmExtraEclipseCDT4Generator.h               |   47 +-
 Source/cmExtraKateGenerator.cxx                    |   56 +-
 Source/cmExtraKateGenerator.h                      |   37 +-
 Source/cmExtraSublimeTextGenerator.cxx             |  100 +-
 Source/cmExtraSublimeTextGenerator.h               |   42 +-
 Source/cmFLTKWrapUICommand.cxx                     |   17 +-
 Source/cmFLTKWrapUICommand.h                       |   25 +-
 Source/cmFileCommand.cxx                           |  225 +-
 Source/cmFileCommand.h                             |   23 +-
 Source/cmFileLock.cxx                              |   14 +-
 Source/cmFileLock.h                                |   18 +-
 Source/cmFileLockPool.cxx                          |   19 +-
 Source/cmFileLockPool.h                            |   18 +-
 Source/cmFileLockResult.cxx                        |   15 +-
 Source/cmFileLockResult.h                          |   18 +-
 Source/cmFileLockUnix.cxx                          |   23 +-
 Source/cmFileLockWin32.cxx                         |   14 +-
 Source/cmFileMonitor.cxx                           |  389 ++
 Source/cmFileMonitor.h                             |   28 +
 Source/cmFilePathUuid.cxx                          |  118 +
 Source/cmFilePathUuid.h                            |   69 +
 Source/cmFileTimeComparison.cxx                    |   59 +-
 Source/cmFileTimeComparison.h                      |   15 +-
 Source/cmFindBase.cxx                              |   16 +-
 Source/cmFindBase.h                                |   13 +-
 Source/cmFindCommon.cxx                            |   17 +-
 Source/cmFindCommon.h                              |   15 +-
 Source/cmFindFileCommand.cxx                       |   13 +-
 Source/cmFindFileCommand.h                         |   17 +-
 Source/cmFindLibraryCommand.cxx                    |   28 +-
 Source/cmFindLibraryCommand.h                      |   23 +-
 Source/cmFindPackageCommand.cxx                    |  268 +-
 Source/cmFindPackageCommand.h                      |   65 +-
 Source/cmFindPathCommand.cxx                       |   18 +-
 Source/cmFindPathCommand.h                         |   23 +-
 Source/cmFindProgramCommand.cxx                    |   16 +-
 Source/cmFindProgramCommand.h                      |   23 +-
 Source/cmForEachCommand.cxx                        |   27 +-
 Source/cmForEachCommand.h                          |   31 +-
 Source/cmFortranLexer.cxx                          | 2357 +++++-----
 Source/cmFortranLexer.h                            |  147 +-
 Source/cmFortranLexer.in.l                         |   43 +-
 Source/cmFortranParser.cxx                         |  668 +--
 Source/cmFortranParser.h                           |   21 +-
 Source/cmFortranParser.y                           |  236 +-
 Source/cmFortranParserImpl.cxx                     |   98 +-
 Source/cmFortranParserTokens.h                     |   52 +-
 Source/cmFunctionBlocker.h                         |   15 +-
 Source/cmFunctionCommand.cxx                       |   37 +-
 Source/cmFunctionCommand.h                         |   31 +-
 Source/cmGeneratedFileStream.cxx                   |   21 +-
 Source/cmGeneratedFileStream.h                     |   18 +-
 Source/cmGeneratorExpression.cxx                   |   30 +-
 Source/cmGeneratorExpression.h                     |   47 +-
 Source/cmGeneratorExpressionContext.cxx            |   16 +-
 Source/cmGeneratorExpressionContext.h              |   13 +-
 Source/cmGeneratorExpressionDAGChecker.cxx         |   24 +-
 Source/cmGeneratorExpressionDAGChecker.h           |   26 +-
 Source/cmGeneratorExpressionEvaluationFile.cxx     |   46 +-
 Source/cmGeneratorExpressionEvaluationFile.h       |   29 +-
 Source/cmGeneratorExpressionEvaluator.cxx          |   53 +-
 Source/cmGeneratorExpressionEvaluator.h            |   35 +-
 Source/cmGeneratorExpressionLexer.cxx              |   13 +-
 Source/cmGeneratorExpressionLexer.h                |   17 +-
 Source/cmGeneratorExpressionNode.cxx               |  355 +-
 Source/cmGeneratorExpressionNode.h                 |   33 +-
 Source/cmGeneratorExpressionParser.cxx             |   17 +-
 Source/cmGeneratorExpressionParser.h               |   18 +-
 Source/cmGeneratorTarget.cxx                       |  466 +-
 Source/cmGeneratorTarget.h                         |   41 +-
 Source/cmGetCMakePropertyCommand.cxx               |   15 +-
 Source/cmGetCMakePropertyCommand.h                 |   23 +-
 Source/cmGetDirectoryPropertyCommand.cxx           |   15 +-
 Source/cmGetDirectoryPropertyCommand.h             |   23 +-
 Source/cmGetFilenameComponentCommand.cxx           |   13 +-
 Source/cmGetFilenameComponentCommand.h             |   23 +-
 Source/cmGetPropertyCommand.cxx                    |   58 +-
 Source/cmGetPropertyCommand.h                      |   23 +-
 Source/cmGetSourceFilePropertyCommand.cxx          |   15 +-
 Source/cmGetSourceFilePropertyCommand.h            |   24 +-
 Source/cmGetTargetPropertyCommand.cxx              |   37 +-
 Source/cmGetTargetPropertyCommand.h                |   21 +-
 Source/cmGetTestPropertyCommand.cxx                |   15 +-
 Source/cmGetTestPropertyCommand.h                  |   21 +-
 Source/cmGhsMultiGpj.cxx                           |   13 +-
 Source/cmGhsMultiGpj.h                             |   15 +-
 Source/cmGhsMultiTargetGenerator.cxx               |   16 +-
 Source/cmGhsMultiTargetGenerator.h                 |   17 +-
 Source/cmGlobalBorlandMakefileGenerator.cxx        |   13 +-
 Source/cmGlobalBorlandMakefileGenerator.h          |   13 +-
 Source/cmGlobalCommonGenerator.cxx                 |   15 +-
 Source/cmGlobalCommonGenerator.h                   |   19 +-
 Source/cmGlobalGenerator.cxx                       |  393 +-
 Source/cmGlobalGenerator.h                         |  113 +-
 Source/cmGlobalGeneratorFactory.h                  |   39 +-
 Source/cmGlobalGhsMultiGenerator.cxx               |   14 +-
 Source/cmGlobalGhsMultiGenerator.h                 |   19 +-
 Source/cmGlobalJOMMakefileGenerator.cxx            |   13 +-
 Source/cmGlobalJOMMakefileGenerator.h              |   13 +-
 Source/cmGlobalKdevelopGenerator.cxx               |   72 +-
 Source/cmGlobalKdevelopGenerator.h                 |   34 +-
 Source/cmGlobalMSYSMakefileGenerator.cxx           |   13 +-
 Source/cmGlobalMSYSMakefileGenerator.h             |   13 +-
 Source/cmGlobalMinGWMakefileGenerator.cxx          |   13 +-
 Source/cmGlobalMinGWMakefileGenerator.h            |   13 +-
 Source/cmGlobalNMakeMakefileGenerator.cxx          |   13 +-
 Source/cmGlobalNMakeMakefileGenerator.h            |   13 +-
 Source/cmGlobalNinjaGenerator.cxx                  |  705 ++-
 Source/cmGlobalNinjaGenerator.h                    |  134 +-
 Source/cmGlobalUnixMakefileGenerator3.cxx          |   72 +-
 Source/cmGlobalUnixMakefileGenerator3.h            |  115 +-
 Source/cmGlobalVisualStudio10Generator.cxx         |   58 +-
 Source/cmGlobalVisualStudio10Generator.h           |   13 +-
 Source/cmGlobalVisualStudio11Generator.cxx         |   24 +-
 Source/cmGlobalVisualStudio11Generator.h           |   13 +-
 Source/cmGlobalVisualStudio12Generator.cxx         |   24 +-
 Source/cmGlobalVisualStudio12Generator.h           |   13 +-
 Source/cmGlobalVisualStudio14Generator.cxx         |   24 +-
 Source/cmGlobalVisualStudio14Generator.h           |   13 +-
 Source/cmGlobalVisualStudio15Generator.cxx         |  142 +
 Source/cmGlobalVisualStudio15Generator.h           |   37 +
 Source/cmGlobalVisualStudio71Generator.cxx         |   14 +-
 Source/cmGlobalVisualStudio71Generator.h           |   13 +-
 Source/cmGlobalVisualStudio7Generator.cxx          |   50 +-
 Source/cmGlobalVisualStudio7Generator.h            |   19 +-
 Source/cmGlobalVisualStudio8Generator.cxx          |   25 +-
 Source/cmGlobalVisualStudio8Generator.h            |   13 +-
 Source/cmGlobalVisualStudio9Generator.cxx          |   24 +-
 Source/cmGlobalVisualStudio9Generator.h            |   13 +-
 Source/cmGlobalVisualStudioGenerator.cxx           |   20 +-
 Source/cmGlobalVisualStudioGenerator.h             |   18 +-
 Source/cmGlobalWatcomWMakeGenerator.cxx            |   17 +-
 Source/cmGlobalWatcomWMakeGenerator.h              |   33 +-
 Source/cmGlobalXCodeGenerator.cxx                  |  221 +-
 Source/cmGlobalXCodeGenerator.h                    |   19 +-
 Source/cmGraphAdjacencyList.h                      |   15 +-
 Source/cmGraphVizWriter.cxx                        |   64 +-
 Source/cmGraphVizWriter.h                          |   25 +-
 Source/cmHexFileConverter.cxx                      |   28 +-
 Source/cmHexFileConverter.h                        |   15 +-
 Source/cmIDEFlagTable.h                            |   13 +-
 Source/cmIDEOptions.cxx                            |   13 +-
 Source/cmIDEOptions.h                              |   15 +-
 Source/cmIfCommand.cxx                             |   25 +-
 Source/cmIfCommand.h                               |   34 +-
 Source/cmIncludeCommand.cxx                        |   17 +-
 Source/cmIncludeCommand.h                          |   23 +-
 Source/cmIncludeDirectoryCommand.cxx               |   15 +-
 Source/cmIncludeDirectoryCommand.h                 |   21 +-
 Source/cmIncludeExternalMSProjectCommand.cxx       |   13 +-
 Source/cmIncludeExternalMSProjectCommand.h         |   27 +-
 Source/cmIncludeRegularExpressionCommand.cxx       |   15 +-
 Source/cmIncludeRegularExpressionCommand.h         |   27 +-
 Source/cmInstallCommand.cxx                        |  186 +-
 Source/cmInstallCommand.h                          |   22 +-
 Source/cmInstallCommandArguments.cxx               |   35 +-
 Source/cmInstallCommandArguments.h                 |   16 +-
 Source/cmInstallDirectoryGenerator.cxx             |   33 +-
 Source/cmInstallDirectoryGenerator.h               |   33 +-
 Source/cmInstallExportAndroidMKGenerator.cxx       |  140 +
 Source/cmInstallExportAndroidMKGenerator.h         |   37 +
 Source/cmInstallExportGenerator.cxx                |   83 +-
 Source/cmInstallExportGenerator.h                  |   41 +-
 Source/cmInstallFilesCommand.cxx                   |   23 +-
 Source/cmInstallFilesCommand.h                     |   25 +-
 Source/cmInstallFilesGenerator.cxx                 |   27 +-
 Source/cmInstallFilesGenerator.h                   |   34 +-
 Source/cmInstallGenerator.cxx                      |   15 +-
 Source/cmInstallGenerator.h                        |   36 +-
 Source/cmInstallProgramsCommand.cxx                |   23 +-
 Source/cmInstallProgramsCommand.h                  |   25 +-
 Source/cmInstallScriptGenerator.cxx                |   18 +-
 Source/cmInstallScriptGenerator.h                  |   22 +-
 Source/cmInstallTargetGenerator.cxx                |   44 +-
 Source/cmInstallTargetGenerator.h                  |   32 +-
 Source/cmInstallTargetsCommand.cxx                 |   30 +-
 Source/cmInstallTargetsCommand.h                   |   21 +-
 Source/cmInstallType.h                             |   13 +-
 Source/cmInstalledFile.cxx                         |   19 +-
 Source/cmInstalledFile.h                           |   22 +-
 Source/cmLinkDirectoriesCommand.cxx                |   15 +-
 Source/cmLinkDirectoriesCommand.h                  |   21 +-
 Source/cmLinkItem.h                                |   18 +-
 Source/cmLinkLibrariesCommand.cxx                  |   15 +-
 Source/cmLinkLibrariesCommand.h                    |   21 +-
 Source/cmLinkedTree.h                              |   21 +-
 Source/cmListCommand.cxx                           |   13 +-
 Source/cmListCommand.h                             |   23 +-
 Source/cmListFileCache.cxx                         |  223 +-
 Source/cmListFileCache.h                           |   25 +-
 Source/cmListFileLexer.c                           |   13 +-
 Source/cmListFileLexer.h                           |   13 +-
 Source/cmListFileLexer.in.l                        |   13 +-
 Source/cmLoadCacheCommand.cxx                      |   15 +-
 Source/cmLoadCacheCommand.h                        |   21 +-
 Source/cmLoadCommandCommand.cxx                    |   39 +-
 Source/cmLoadCommandCommand.h                      |   21 +-
 Source/cmLocalCommonGenerator.cxx                  |   70 +-
 Source/cmLocalCommonGenerator.h                    |   34 +-
 Source/cmLocalGenerator.cxx                        |  285 +-
 Source/cmLocalGenerator.h                          |   72 +-
 Source/cmLocalGhsMultiGenerator.cxx                |   13 +-
 Source/cmLocalGhsMultiGenerator.h                  |   13 +-
 Source/cmLocalNinjaGenerator.cxx                   |   82 +-
 Source/cmLocalNinjaGenerator.h                     |   54 +-
 Source/cmLocalUnixMakefileGenerator3.cxx           |  267 +-
 Source/cmLocalUnixMakefileGenerator3.h             |   89 +-
 Source/cmLocalVisualStudio10Generator.cxx          |   15 +-
 Source/cmLocalVisualStudio10Generator.h            |   13 +-
 Source/cmLocalVisualStudio7Generator.cxx           |   59 +-
 Source/cmLocalVisualStudio7Generator.h             |   13 +-
 Source/cmLocalVisualStudioGenerator.cxx            |   30 +-
 Source/cmLocalVisualStudioGenerator.h              |   20 +-
 Source/cmLocalXCodeGenerator.cxx                   |   14 +-
 Source/cmLocalXCodeGenerator.h                     |   13 +-
 Source/cmLocale.h                                  |   17 +-
 Source/cmMachO.cxx                                 |   13 +-
 Source/cmMachO.h                                   |   13 +-
 Source/cmMacroCommand.cxx                          |   37 +-
 Source/cmMacroCommand.h                            |   31 +-
 Source/cmMakeDirectoryCommand.cxx                  |   13 +-
 Source/cmMakeDirectoryCommand.h                    |   23 +-
 Source/cmMakefile.cxx                              |  547 ++-
 Source/cmMakefile.h                                |  135 +-
 Source/cmMakefileExecutableTargetGenerator.cxx     |  154 +-
 Source/cmMakefileExecutableTargetGenerator.h       |   21 +-
 Source/cmMakefileLibraryTargetGenerator.cxx        |  224 +-
 Source/cmMakefileLibraryTargetGenerator.h          |   23 +-
 Source/cmMakefileTargetGenerator.cxx               |  403 +-
 Source/cmMakefileTargetGenerator.h                 |   42 +-
 Source/cmMakefileUtilityTargetGenerator.cxx        |   36 +-
 Source/cmMakefileUtilityTargetGenerator.h          |   21 +-
 Source/cmMarkAsAdvancedCommand.cxx                 |   17 +-
 Source/cmMarkAsAdvancedCommand.h                   |   23 +-
 Source/cmMathCommand.cxx                           |   15 +-
 Source/cmMathCommand.h                             |   23 +-
 Source/cmMessageCommand.cxx                        |   33 +-
 Source/cmMessageCommand.h                          |   23 +-
 Source/cmMessenger.cxx                             |  203 +
 Source/cmMessenger.h                               |   39 +
 Source/cmNewLineStyle.cxx                          |   30 +-
 Source/cmNewLineStyle.h                            |   18 +-
 Source/cmNinjaNormalTargetGenerator.cxx            |  120 +-
 Source/cmNinjaNormalTargetGenerator.h              |   27 +-
 Source/cmNinjaTargetGenerator.cxx                  |  431 +-
 Source/cmNinjaTargetGenerator.h                    |   50 +-
 Source/cmNinjaTypes.h                              |   16 +-
 Source/cmNinjaUtilityTargetGenerator.cxx           |   56 +-
 Source/cmNinjaUtilityTargetGenerator.h             |   24 +-
 Source/cmOSXBundleGenerator.cxx                    |   39 +-
 Source/cmOSXBundleGenerator.h                      |   24 +-
 Source/cmObject.h                                  |   15 +-
 Source/cmOptionCommand.cxx                         |   13 +-
 Source/cmOptionCommand.h                           |   23 +-
 Source/cmOrderDirectories.cxx                      |   27 +-
 Source/cmOrderDirectories.h                        |   26 +-
 Source/cmOutputConverter.cxx                       |  426 +-
 Source/cmOutputConverter.h                         |  100 +-
 Source/cmOutputRequiredFilesCommand.cxx            |   42 +-
 Source/cmOutputRequiredFilesCommand.h              |   21 +-
 Source/cmParseArgumentsCommand.cxx                 |   97 +-
 Source/cmParseArgumentsCommand.h                   |   24 +-
 Source/cmPathLabel.cxx                             |   14 +-
 Source/cmPathLabel.h                               |   15 +-
 Source/cmPolicies.cxx                              |   34 +-
 Source/cmPolicies.h                                |   22 +-
 Source/cmProcessTools.cxx                          |   28 +-
 Source/cmProcessTools.h                            |   27 +-
 Source/cmProjectCommand.cxx                        |   15 +-
 Source/cmProjectCommand.h                          |   21 +-
 Source/cmProperty.cxx                              |   17 +-
 Source/cmProperty.h                                |   17 +-
 Source/cmPropertyDefinition.cxx                    |   15 +-
 Source/cmPropertyDefinition.h                      |   17 +-
 Source/cmPropertyDefinitionMap.cxx                 |   23 +-
 Source/cmPropertyDefinitionMap.h                   |   19 +-
 Source/cmPropertyMap.cxx                           |   33 +-
 Source/cmPropertyMap.h                             |   21 +-
 Source/cmQTWrapCPPCommand.cxx                      |   15 +-
 Source/cmQTWrapCPPCommand.h                        |   21 +-
 Source/cmQTWrapUICommand.cxx                       |   17 +-
 Source/cmQTWrapUICommand.h                         |   21 +-
 Source/cmQtAutoGeneratorInitializer.cxx            |  214 +-
 Source/cmQtAutoGeneratorInitializer.h              |   22 +-
 Source/cmQtAutoGenerators.cxx                      |  199 +-
 Source/cmQtAutoGenerators.h                        |   24 +-
 Source/cmRST.cxx                                   |   18 +-
 Source/cmRST.h                                     |   20 +-
 Source/cmRemoveCommand.cxx                         |   15 +-
 Source/cmRemoveCommand.h                           |   23 +-
 Source/cmRemoveDefinitionsCommand.cxx              |   15 +-
 Source/cmRemoveDefinitionsCommand.h                |   21 +-
 Source/cmReturnCommand.cxx                         |   13 +-
 Source/cmReturnCommand.h                           |   23 +-
 Source/cmScriptGenerator.cxx                       |   25 +-
 Source/cmScriptGenerator.h                         |   19 +-
 Source/cmSearchPath.cxx                            |   26 +-
 Source/cmSearchPath.h                              |   21 +-
 Source/cmSeparateArgumentsCommand.cxx              |   13 +-
 Source/cmSeparateArgumentsCommand.h                |   23 +-
 Source/cmServer.cxx                                |  379 ++
 Source/cmServer.h                                  |   94 +
 Source/cmServerConnection.cxx                      |  377 ++
 Source/cmServerConnection.h                        |   95 +
 Source/cmServerDictionary.h                        |   94 +
 Source/cmServerProtocol.cxx                        | 1077 +++++
 Source/cmServerProtocol.h                          |  134 +
 Source/cmSetCommand.cxx                            |   28 +-
 Source/cmSetCommand.h                              |   23 +-
 Source/cmSetDirectoryPropertiesCommand.cxx         |   18 +-
 Source/cmSetDirectoryPropertiesCommand.h           |   29 +-
 Source/cmSetPropertyCommand.cxx                    |   23 +-
 Source/cmSetPropertyCommand.h                      |   23 +-
 Source/cmSetSourceFilesPropertiesCommand.cxx       |   13 +-
 Source/cmSetSourceFilesPropertiesCommand.h         |   27 +-
 Source/cmSetTargetPropertiesCommand.cxx            |   13 +-
 Source/cmSetTargetPropertiesCommand.h              |   21 +-
 Source/cmSetTestsPropertiesCommand.cxx             |   15 +-
 Source/cmSetTestsPropertiesCommand.h               |   21 +-
 Source/cmSiteNameCommand.cxx                       |   16 +-
 Source/cmSiteNameCommand.h                         |   23 +-
 Source/cmSourceFile.cxx                            |   29 +-
 Source/cmSourceFile.h                              |   25 +-
 Source/cmSourceFileLocation.cxx                    |   27 +-
 Source/cmSourceFileLocation.h                      |   17 +-
 Source/cmSourceGroup.cxx                           |   25 +-
 Source/cmSourceGroup.h                             |   21 +-
 Source/cmSourceGroupCommand.cxx                    |   17 +-
 Source/cmSourceGroupCommand.h                      |   21 +-
 Source/cmStandardIncludes.h                        |   97 +-
 Source/cmStandardLexer.h                           |   13 +-
 Source/cmState.cxx                                 |  142 +-
 Source/cmState.h                                   |   40 +-
 Source/cmStringCommand.cxx                         |   94 +-
 Source/cmStringCommand.h                           |   23 +-
 Source/cmSubdirCommand.cxx                         |   15 +-
 Source/cmSubdirCommand.h                           |   21 +-
 Source/cmSubdirDependsCommand.cxx                  |   13 +-
 Source/cmSubdirDependsCommand.h                    |   21 +-
 Source/cmSystemTools.cxx                           |  293 +-
 Source/cmSystemTools.h                             |   78 +-
 Source/cmTarget.cxx                                |  282 +-
 Source/cmTarget.h                                  |   63 +-
 Source/cmTargetCompileDefinitionsCommand.cxx       |   13 +-
 Source/cmTargetCompileDefinitionsCommand.h         |   40 +-
 Source/cmTargetCompileFeaturesCommand.cxx          |   13 +-
 Source/cmTargetCompileFeaturesCommand.h            |   33 +-
 Source/cmTargetCompileOptionsCommand.cxx           |   13 +-
 Source/cmTargetCompileOptionsCommand.h             |   34 +-
 Source/cmTargetDepend.h                            |   15 +-
 Source/cmTargetExport.h                            |   15 +-
 Source/cmTargetIncludeDirectoriesCommand.cxx       |   13 +-
 Source/cmTargetIncludeDirectoriesCommand.h         |   46 +-
 Source/cmTargetLinkLibrariesCommand.cxx            |   26 +-
 Source/cmTargetLinkLibrariesCommand.h              |   21 +-
 Source/cmTargetLinkLibraryType.h                   |   13 +
 Source/cmTargetPropCommandBase.cxx                 |   14 +-
 Source/cmTargetPropCommandBase.h                   |   14 +-
 Source/cmTargetSourcesCommand.cxx                  |   13 +-
 Source/cmTargetSourcesCommand.h                    |   34 +-
 Source/cmTest.cxx                                  |   19 +-
 Source/cmTest.h                                    |   20 +-
 Source/cmTestGenerator.cxx                         |   26 +-
 Source/cmTestGenerator.h                           |   39 +-
 Source/cmTimestamp.cxx                             |   30 +-
 Source/cmTimestamp.h                               |   15 +-
 Source/cmTryCompileCommand.cxx                     |   13 +-
 Source/cmTryCompileCommand.h                       |   21 +-
 Source/cmTryRunCommand.cxx                         |   38 +-
 Source/cmTryRunCommand.h                           |   21 +-
 Source/cmTypeMacro.h                               |   31 +
 Source/cmUnsetCommand.cxx                          |   29 +-
 Source/cmUnsetCommand.h                            |   23 +-
 Source/cmUseMangledMesaCommand.cxx                 |   13 +-
 Source/cmUseMangledMesaCommand.h                   |   23 +-
 Source/cmUtilitySourceCommand.cxx                  |   17 +-
 Source/cmUtilitySourceCommand.h                    |   21 +-
 Source/cmUtils.hxx                                 |   17 +
 Source/cmUuid.cxx                                  |   26 +-
 Source/cmUuid.h                                    |   18 +-
 Source/cmVS140CLFlagTable.h                        |  237 +
 Source/cmVS141CLFlagTable.h                        |  249 +
 Source/cmVS14CLFlagTable.h                         |  237 -
 Source/cmVS14LinkFlagTable.h                       |   17 +-
 Source/cmVariableRequiresCommand.cxx               |   13 +-
 Source/cmVariableRequiresCommand.h                 |   21 +-
 Source/cmVariableWatch.cxx                         |   19 +-
 Source/cmVariableWatch.h                           |   30 +-
 Source/cmVariableWatchCommand.cxx                  |   15 +-
 Source/cmVariableWatchCommand.h                    |   27 +-
 Source/cmVersion.cxx                               |   15 +-
 Source/cmVersion.h                                 |   15 +-
 Source/cmVersionConfig.h.in                        |   15 +-
 Source/cmVersionMacros.h                           |   13 +-
 Source/cmVisualStudio10TargetGenerator.cxx         |  100 +-
 Source/cmVisualStudio10TargetGenerator.h           |   15 +-
 Source/cmVisualStudioGeneratorOptions.cxx          |    1 +
 Source/cmVisualStudioGeneratorOptions.h            |   13 +-
 Source/cmVisualStudioSlnData.cxx                   |   13 +-
 Source/cmVisualStudioSlnData.h                     |   15 +-
 Source/cmVisualStudioSlnParser.cxx                 |   13 +-
 Source/cmVisualStudioSlnParser.h                   |   15 +-
 Source/cmVisualStudioWCEPlatformParser.cxx         |   13 +-
 Source/cmVisualStudioWCEPlatformParser.h           |   15 +-
 Source/cmWhileCommand.cxx                          |   23 +-
 Source/cmWhileCommand.h                            |   34 +-
 Source/cmWriteFileCommand.cxx                      |   13 +-
 Source/cmWriteFileCommand.h                        |   23 +-
 Source/cmXCode21Object.cxx                         |   13 +-
 Source/cmXCode21Object.h                           |   13 +-
 Source/cmXCodeObject.cxx                           |   29 +-
 Source/cmXCodeObject.h                             |   61 +-
 Source/cmXMLParser.cxx                             |   33 +-
 Source/cmXMLParser.h                               |   17 +-
 Source/cmXMLSafe.cxx                               |   15 +-
 Source/cmXMLSafe.h                                 |   15 +-
 Source/cmXMLWriter.cxx                             |   19 +-
 Source/cmXMLWriter.h                               |   15 +-
 Source/cm_auto_ptr.hxx                             |  220 +
 Source/cm_get_date.c                               |   13 +-
 Source/cm_get_date.h                               |   13 +-
 Source/cm_sha2_mangle.h                            |   13 +-
 Source/cm_utf8.c                                   |   13 +-
 Source/cm_utf8.h                                   |   13 +-
 Source/cmake.cxx                                   |  630 ++-
 Source/cmake.h                                     |  101 +-
 Source/cmakemain.cxx                               |   71 +-
 Source/cmakexbuild.cxx                             |   13 +-
 Source/cmcldeps.cxx                                |    3 +-
 Source/cmcmd.cxx                                   |  263 +-
 Source/cmcmd.h                                     |   19 +-
 Source/cmparseMSBuildXML.py                        |    3 +
 Source/ctest.cxx                                   |   38 +-
 Source/dir.dox                                     |    7 +
 Source/dir.dox.in                                  |    7 +
 Source/kwsys/CMakeLists.txt                        |   27 +-
 Source/kwsys/Configure.hxx.in                      |    7 +-
 Source/kwsys/ConsoleBuf.hxx.in                     |  348 ++
 Source/kwsys/Directory.cxx                         |   31 +-
 Source/kwsys/FStream.hxx.in                        |  234 +-
 Source/kwsys/SystemInformation.cxx                 |   15 +-
 Source/kwsys/SystemTools.cxx                       |  408 +-
 Source/kwsys/SystemTools.hxx.in                    |   19 +-
 Source/kwsys/auto_ptr.hxx.in                       |  219 -
 Source/kwsys/kwsysPlatformTestsCXX.cxx             |    5 +
 Source/kwsys/testAutoPtr.cxx                       |  166 -
 Source/kwsys/testConsoleBuf.cxx                    |  719 +++
 Source/kwsys/testConsoleBuf.hxx                    |   25 +
 Source/kwsys/testConsoleBufChild.cxx               |   63 +
 Source/kwsys/testSystemTools.cxx                   |   55 +-
 Templates/TestDriver.cxx.in                        |   10 +-
 Templates/cygwin-package.sh.in                     |  103 -
 Tests/AliasTarget/CMakeLists.txt                   |   15 +-
 Tests/AliasTarget/commandgenerator.cpp             |    3 +-
 Tests/AliasTarget/targetgenerator.cpp              |    3 +-
 Tests/CFBundleTest/CMakeLists.txt                  |    1 -
 Tests/CMakeLib/CMakeLists.txt                      |    1 +
 Tests/CMakeLib/PseudoMemcheck/memtester.cxx.in     |   32 +-
 Tests/CMakeLib/run_compile_commands.cxx            |   39 +-
 Tests/CMakeLib/testFindPackageCommand.cxx          |   67 +
 Tests/CMakeLib/testGeneratedFileStream.cxx         |   20 +-
 Tests/CMakeLib/testRST.cxx                         |   22 +-
 Tests/CMakeLib/testSystemTools.cxx                 |   94 +-
 Tests/CMakeLib/testUTF8.cxx                        |   17 +-
 Tests/CMakeLib/testXMLParser.cxx                   |    2 +-
 Tests/CMakeLib/testXMLSafe.cxx                     |   23 +-
 Tests/CMakeLists.txt                               |  182 +-
 .../CMakeOnly/CheckCXXSymbolExists/CMakeLists.txt  |    2 +-
 .../CMakeOnly/CheckStructHasMember/CMakeLists.txt  |    2 +-
 Tests/CMakeOnly/CheckSymbolExists/CMakeLists.txt   |    2 +-
 Tests/CMakeOnly/find_library/CMakeLists.txt        |    7 +
 .../CMakeOnly/find_library/lib/32/libtest5.a       |    0
 .../CMakeOnly/find_library/lib/A/lib32/libtest3.a  |    0
 .../CMakeOnly/find_library/lib32/A/lib/libtest2.a  |    0
 .../find_library/lib32/A/lib32/libtest4.a          |    0
 .../CMakeOnly/find_library/lib32/A/libtest4.a      |    0
 .../CMakeOnly/find_library/lib32/libtest4.a        |    0
 Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in     |    6 +
 Tests/CMakeTests/ModuleNoticesTest.cmake.in        |   25 +-
 .../String-TIMESTAMP-MonthWeekNames.cmake          |   11 +
 Tests/CMakeTests/StringTest.cmake.in               |    3 +
 Tests/CMakeTests/VersionTest.cmake.in              |   14 +
 Tests/CMakeTests/WhileTest.cmake.in                |    6 +-
 Tests/CPackComponents/Issue 7470.html              |    4 +-
 ...yResult-components-lintian-dpkgdeb-checks.cmake |    2 +-
 .../CPackComponentsDEB/RunCPackVerifyResult.cmake  |    2 +-
 Tests/CTestLimitDashJ/CMakeLists.txt               |    2 +-
 Tests/CTestTestStopTime/GetDate.cmake              |    4 +-
 Tests/CTestUpdateBZR.cmake.in                      |    2 +-
 Tests/CTestUpdateCVS.cmake.in                      |    2 +-
 Tests/CTestUpdateCommon.cmake                      |   12 +-
 Tests/CTestUpdateGIT.cmake.in                      |    2 +-
 Tests/CTestUpdateHG.cmake.in                       |    2 +-
 Tests/CTestUpdateP4.cmake.in                       |    8 +-
 Tests/CTestUpdateSVN.cmake.in                      |    2 +-
 Tests/CheckFortran.cmake                           |   17 +-
 Tests/Complex/CMakeLists.txt                       |   12 +-
 Tests/Complex/Executable/CMakeLists.txt            |    4 +-
 Tests/Complex/Executable/complex.cxx               |  200 +-
 Tests/Complex/Library/CMakeLists.txt               |    2 +-
 Tests/Complex/VarTests.cmake                       |   80 +-
 Tests/ComplexOneConfig/CMakeLists.txt              |    6 +-
 Tests/ComplexOneConfig/Executable/CMakeLists.txt   |    4 +-
 Tests/ComplexOneConfig/Executable/complex.cxx      |  194 +-
 Tests/ComplexOneConfig/Library/CMakeLists.txt      |    2 +-
 Tests/ComplexOneConfig/VarTests.cmake              |   80 +-
 Tests/CustomCommand/CMakeLists.txt                 |    6 +-
 Tests/ExternalProjectSourceSubdir/CMakeLists.txt   |   10 +
 .../Example/subdir/CMakeLists.txt                  |    2 +
 Tests/FindBZip2/CMakeLists.txt                     |   10 +
 Tests/FindBZip2/Test/CMakeLists.txt                |   16 +
 Tests/FindBZip2/Test/main.c                        |   23 +
 Tests/FindICU/CMakeLists.txt                       |   10 +
 Tests/FindICU/Test/CMakeLists.txt                  |   14 +
 Tests/FindICU/Test/main.cpp                        |   24 +
 Tests/FindLibUV/CMakeLists.txt                     |   10 +
 Tests/FindLibUV/Test/CMakeLists.txt                |   17 +
 Tests/FindLibUV/Test/main.c                        |    7 +
 Tests/FindMatlab/components_checks/CMakeLists.txt  |   23 +
 Tests/FindOpenCL/CMakeLists.txt                    |   10 +
 Tests/FindOpenCL/Test/CMakeLists.txt               |   14 +
 Tests/FindOpenCL/Test/main.c                       |   17 +
 .../Baz 1.3/lib/cmake/Baz/BazConfig.cmake          |    1 +
 .../Baz 1.3/lib/cmake/Baz/BazConfigVersion.cmake   |    7 +
 .../Baz 2.0/share/Baz 2/BazConfig.cmake            |    1 +
 .../Baz 2.0/share/Baz 2/BazConfigVersion.cmake     |    7 +
 .../Baz 2.1/lib/Baz 2/cmake/BazConfig.cmake        |    1 +
 .../Baz 2.1/lib/Baz 2/cmake/BazConfigVersion.cmake |    7 +
 Tests/FindPackageTest/CMakeLists.txt               |   44 +-
 .../SortLib-3.1.1/SortLibConfig.cmake              |    2 +
 .../SortLib-3.1.1/SortLibConfigVersion.cmake       |    9 +
 .../SortLib-3.10.1/SortLibConfig.cmake             |    2 +
 .../SortLib-3.10.1/SortLibConfigVersion.cmake      |    9 +
 Tests/FindTIFF/Test/CMakeLists.txt                 |   14 +-
 Tests/FindVulkan/CMakeLists.txt                    |   10 +
 Tests/FindVulkan/Test/CMakeLists.txt               |   15 +
 Tests/FindVulkan/Test/main.c                       |   29 +
 Tests/Fortran/CMakeLists.txt                       |   89 +-
 Tests/Fortran/External/CMakeLists.txt              |    4 -
 Tests/FortranModules/CMakeLists.txt                |  111 +
 .../Executable/CMakeLists.txt                      |    0
 .../Executable/main.f90                            |    0
 Tests/FortranModules/External/CMakeLists.txt       |    3 +
 Tests/{Fortran => FortranModules}/External/a.f90   |    0
 .../Library/CMakeLists.txt                         |    0
 Tests/{Fortran => FortranModules}/Library/a.f90    |    0
 Tests/{Fortran => FortranModules}/Library/b.f90    |    0
 Tests/{Fortran => FortranModules}/Library/main.f90 |    0
 .../Subdir/CMakeLists.txt                          |    0
 .../{Fortran => FortranModules}/Subdir/subdir.f90  |    0
 Tests/FortranModules/Submodules/CMakeLists.txt     |    1 +
 Tests/FortranModules/Submodules/main.f90           |    5 +
 Tests/FortranModules/Submodules/provide.f90        |   57 +
 .../in_interface/main.f90                          |    0
 .../in_interface/module.f90                        |    0
 .../include/test_preprocess.h                      |    0
 Tests/FortranModules/non_pp_include.f90            |    3 +
 .../test_module_implementation.f90                 |    0
 .../test_module_interface.f90                      |    0
 .../test_module_main.f90                           |    0
 Tests/FortranModules/test_non_pp_include_main.f90  |    5 +
 .../test_preprocess.F90                            |    0
 .../test_preprocess_module.F90                     |    0
 .../test_use_in_comment_fixedform.f                |    0
 .../test_use_in_comment_freeform.f90               |    0
 Tests/Framework/CMakeLists.txt                     |    5 +
 Tests/IncludeDirectories/CMakeLists.txt            |    8 +-
 .../SystemIncludeDirectories/CMakeLists.txt        |   15 +-
 Tests/Java/A.java                                  |   10 +-
 Tests/Java/HelloWorld.java                         |   14 +-
 Tests/JavaExportImport/BuildExport/CMakeLists.txt  |   10 +
 Tests/JavaExportImport/BuildExport/Foo.java        |   11 +
 Tests/JavaExportImport/CMakeLists.txt              |  104 +
 Tests/JavaExportImport/Import/CMakeLists.txt       |   14 +
 Tests/JavaExportImport/Import/Import.java          |   10 +
 Tests/JavaExportImport/InitialCache.cmake.in       |    5 +
 Tests/JavaExportImport/InstallExport/Bar.java      |   11 +
 .../JavaExportImport/InstallExport/CMakeLists.txt  |   14 +
 Tests/JavaExportImport/main.c                      |    4 +
 Tests/MakeClean/CMakeLists.txt                     |    2 +-
 Tests/MathTest/CMakeLists.txt                      |    2 +-
 Tests/Module/ExternalData/CMakeLists.txt           |    1 +
 Tests/Module/ExternalData/Data5/CMakeLists.txt     |   22 +
 Tests/Module/ExternalData/Data5/Data5Check.cmake   |    4 +
 Tests/Module/GenerateExportHeader/CMakeLists.txt   |  139 -
 .../c_identifier/CMakeLists.txt                    |   13 -
 .../GenerateExportHeader/c_identifier/main.cpp     |    8 -
 .../GenerateExportHeader/exportheader_test.cpp     |  137 -
 .../lib_shared_and_static/CMakeLists.txt           |   35 -
 .../lib_shared_and_static/libshared_and_static.cpp |  102 -
 .../lib_shared_and_static/libshared_and_static.h   |   66 -
 .../GenerateExportHeader/libshared/CMakeLists.txt  |   16 -
 .../GenerateExportHeader/libshared/libshared.cpp   |  102 -
 .../GenerateExportHeader/libshared/libshared.h     |   57 -
 .../GenerateExportHeader/libstatic/CMakeLists.txt  |   18 -
 .../GenerateExportHeader/libstatic/libstatic.cpp   |   97 -
 .../GenerateExportHeader/libstatic/libstatic.h     |   57 -
 .../nodeprecated/CMakeLists.txt                    |   26 -
 .../nodeprecated/CMakeLists.txt.in                 |   15 -
 .../GenerateExportHeader/nodeprecated/src/main.cpp |    9 -
 Tests/Plugin/CMakeLists.txt                        |    2 +-
 Tests/Plugin/src/example_exe.cxx                   |    1 +
 Tests/Preprocess/CMakeLists.txt                    |   30 +-
 Tests/QtAutogen/CMakeLists.txt                     |   10 +
 Tests/QtAutogen/abc.cpp                            |   15 +-
 Tests/QtAutogen/abc.h                              |   15 +-
 Tests/QtAutogen/abc_p.h                            |   15 +-
 Tests/QtAutogen/bar.cpp                            |   15 +-
 Tests/QtAutogen/blub.cpp                           |   15 +-
 Tests/QtAutogen/blub.h                             |   15 +-
 Tests/QtAutogen/foo.cpp                            |   15 +-
 Tests/QtAutogen/foo.h                              |   15 +-
 Tests/QtAutogen/rcc_empty.cpp                      |    9 +
 Tests/QtAutogen/rcc_empty_resource.qrc             |    4 +
 Tests/QtAutogen/sameName/CMakeLists.txt            |   21 +
 Tests/QtAutogen/sameName/aaa/bbb/data.qrc          |    6 +
 Tests/QtAutogen/sameName/aaa/bbb/item.cpp          |   10 +
 Tests/QtAutogen/sameName/aaa/bbb/item.hpp          |   18 +
 Tests/QtAutogen/sameName/aaa/data.qrc              |    6 +
 Tests/QtAutogen/sameName/aaa/item.cpp              |    8 +
 Tests/QtAutogen/sameName/aaa/item.hpp              |   16 +
 Tests/QtAutogen/sameName/bbb/aaa/data.qrc          |    6 +
 Tests/QtAutogen/sameName/bbb/aaa/item.cpp          |   10 +
 Tests/QtAutogen/sameName/bbb/aaa/item.hpp          |   18 +
 Tests/QtAutogen/sameName/bbb/data.qrc              |    6 +
 Tests/QtAutogen/sameName/bbb/item.cpp              |    8 +
 Tests/QtAutogen/sameName/bbb/item.hpp              |   16 +
 Tests/QtAutogen/sameName/ccc/data.qrc              |    6 +
 Tests/QtAutogen/sameName/ccc/item.cpp              |   23 +
 Tests/QtAutogen/sameName/ccc/item.hpp              |   16 +
 Tests/QtAutogen/sameName/data.qrc                  |    5 +
 Tests/QtAutogen/sameName/item.cpp                  |    5 +
 Tests/QtAutogen/sameName/item.hpp                  |   13 +
 Tests/QtAutogen/sameName/main.cpp                  |   16 +
 Tests/QtAutogen/sub/bar.h                          |   15 +-
 Tests/QtAutogen/xyz.cpp                            |   15 +-
 Tests/QtAutogen/xyz.h                              |   15 +-
 Tests/QtAutogen/yaf.cpp                            |   15 +-
 Tests/QtAutogen/yaf.h                              |   15 +-
 Tests/QtAutogen/yaf_p.h                            |   15 +-
 Tests/RunCMake/Android/BadSYSROOT-result.txt       |    1 +
 Tests/RunCMake/Android/BadSYSROOT-stderr.txt       |   20 +
 .../RunCMake/Android/BadSYSROOT.cmake              |    0
 Tests/RunCMake/Android/CMakeLists.txt              |    3 +
 Tests/RunCMake/Android/RunCMakeTest.cmake          |  218 +
 Tests/RunCMake/Android/android.c                   |    6 +
 Tests/RunCMake/Android/android.cxx                 |   48 +
 Tests/RunCMake/Android/android.h                   |  103 +
 Tests/RunCMake/Android/common.cmake                |   62 +
 Tests/RunCMake/Android/ndk-arm64-v8a-stdout.txt    |    2 +
 Tests/RunCMake/Android/ndk-arm64-v8a.cmake         |    1 +
 Tests/RunCMake/Android/ndk-armeabi-arm-stdout.txt  |    3 +
 Tests/RunCMake/Android/ndk-armeabi-arm.cmake       |    1 +
 .../RunCMake/Android/ndk-armeabi-thumb-stdout.txt  |    3 +
 Tests/RunCMake/Android/ndk-armeabi-thumb.cmake     |    1 +
 .../Android/ndk-armeabi-v7a-neon-stdout.txt        |    3 +
 Tests/RunCMake/Android/ndk-armeabi-v7a-neon.cmake  |    1 +
 Tests/RunCMake/Android/ndk-armeabi-v7a-stdout.txt  |    3 +
 Tests/RunCMake/Android/ndk-armeabi-v7a.cmake       |    1 +
 Tests/RunCMake/Android/ndk-badabi-result.txt       |    1 +
 Tests/RunCMake/Android/ndk-badabi-stderr.txt       |    5 +
 .../RunCMake/Android/ndk-badabi.cmake              |    0
 Tests/RunCMake/Android/ndk-badarm-result.txt       |    1 +
 Tests/RunCMake/Android/ndk-badarm-stderr.txt       |    6 +
 .../RunCMake/Android/ndk-badarm.cmake              |    0
 Tests/RunCMake/Android/ndk-badneon-result.txt      |    1 +
 Tests/RunCMake/Android/ndk-badneon-stderr.txt      |    6 +
 .../RunCMake/Android/ndk-badneon.cmake             |    0
 Tests/RunCMake/Android/ndk-badstl-result.txt       |    1 +
 Tests/RunCMake/Android/ndk-badstl-stderr.txt       |    9 +
 Tests/RunCMake/Android/ndk-badstl.cmake            |    1 +
 Tests/RunCMake/Android/ndk-badver-result.txt       |    1 +
 Tests/RunCMake/Android/ndk-badver-stderr.txt       |   12 +
 Tests/RunCMake/Android/ndk-badver.cmake            |    1 +
 Tests/RunCMake/Android/ndk-badvernum-result.txt    |    1 +
 Tests/RunCMake/Android/ndk-badvernum-stderr.txt    |   13 +
 Tests/RunCMake/Android/ndk-badvernum.cmake         |    1 +
 Tests/RunCMake/Android/ndk-mips-stdout.txt         |    2 +
 Tests/RunCMake/Android/ndk-mips.cmake              |    1 +
 Tests/RunCMake/Android/ndk-mips64-stdout.txt       |    2 +
 Tests/RunCMake/Android/ndk-mips64.cmake            |    1 +
 .../Android/ndk-sysroot-armeabi-stdout.txt         |    1 +
 .../RunCMake/Android/ndk-sysroot-armeabi.cmake     |    0
 Tests/RunCMake/Android/ndk-x86-stdout.txt          |    2 +
 Tests/RunCMake/Android/ndk-x86.cmake               |    1 +
 Tests/RunCMake/Android/ndk-x86_64-stdout.txt       |    2 +
 Tests/RunCMake/Android/ndk-x86_64.cmake            |    1 +
 Tests/RunCMake/Android/standalone-stdout.txt       |    1 +
 .../RunCMake/Android/standalone-sysroot-stdout.txt |    1 +
 .../RunCMake/Android/standalone-sysroot.cmake      |    0
 Tests/RunCMake/Android/standalone.cmake            |    1 +
 Tests/RunCMake/AndroidMK/AndroidMK-check.cmake     |   30 +
 Tests/RunCMake/AndroidMK/AndroidMK.cmake           |   11 +
 Tests/RunCMake/AndroidMK/CMakeLists.txt            |    3 +
 Tests/RunCMake/AndroidMK/RunCMakeTest.cmake        |    2 +
 Tests/RunCMake/AndroidMK/bar.c                     |    3 +
 .../RunCMake/AndroidMK/expectedBuildAndroidMK.txt  |   26 +
 .../AndroidMK/expectedInstallAndroidMK.txt         |   28 +
 Tests/RunCMake/AndroidMK/foo.cxx                   |    3 +
 Tests/RunCMake/AndroidTestUtilities/CMakeLists.txt |    3 +
 .../AndroidTestUtilities/RunCMakeTest.cmake        |   20 +
 .../RunCMake/AndroidTestUtilities/SetupTest1.cmake |   17 +
 .../SetupTest1Build-check.cmake                    |    5 +
 .../RunCMake/AndroidTestUtilities/SetupTest2.cmake |   30 +
 .../SetupTest2Build-check.cmake                    |    7 +
 .../RunCMake/AndroidTestUtilities/SetupTest3.cmake |   33 +
 .../SetupTest3Build-check.cmake                    |    6 +
 Tests/RunCMake/AndroidTestUtilities/check.cmake    |   20 +
 Tests/RunCMake/AndroidTestUtilities/data/a.txt     |    1 +
 .../RunCMake/AndroidTestUtilities/data/proto.proto |    1 +
 .../AndroidTestUtilities/data/subfolder/b.txt      |    1 +
 .../data/subfolder/protobuffer.p                   |    1 +
 .../AndroidTestUtilities/libs/exampleLib.so        |    1 +
 .../AndroidTestUtilities/libs/exampleLib.txt       |    1 +
 Tests/RunCMake/AutoExportDll/AutoExport.cmake      |   10 +-
 Tests/RunCMake/AutoExportDll/hello2.c              |    8 +
 Tests/RunCMake/AutoExportDll/objlib.c              |    4 +
 Tests/RunCMake/AutoExportDll/say.cxx               |   10 +
 Tests/RunCMake/BuildDepends/check.cmake            |    8 +-
 .../CMP0040/CMP0040-NEW-existing-target.cmake      |    2 +-
 .../CMP0040/CMP0040-NEW-missing-target.cmake       |    2 +-
 .../CMP0040/CMP0040-OLD-existing-target.cmake      |    2 +-
 .../CMP0040/CMP0040-OLD-missing-target.cmake       |    2 +-
 .../CMP0040/CMP0040-WARN-missing-target.cmake      |    2 +-
 .../CMP0054/CMP0054-policy-while-scope.cmake       |    4 +-
 Tests/RunCMake/CMP0065/WARN-ON-stderr.txt          |    2 +-
 Tests/RunCMake/CMakeLists.txt                      |   40 +-
 Tests/RunCMake/CPack/CMakeLists.txt                |    6 +-
 Tests/RunCMake/CPack/CPackTestHelpers.cmake        |   55 +-
 Tests/RunCMake/CPack/DEB/Helpers.cmake             |   10 +-
 .../CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake   |    5 +
 .../CPack/DEB/LONG_FILENAMES-Prerequirements.cmake |    7 +
 .../CPack/DEB/LONG_FILENAMES-VerifyResult.cmake    |   26 +
 .../CPack/DEB/LONG_FILENAMES-specifics.cmake       |    3 +
 Tests/RunCMake/CPack/DEB/Prerequirements.cmake     |    7 +
 Tests/RunCMake/CPack/DEBUGINFO.cmake               |   34 +
 Tests/RunCMake/CPack/LONG_FILENAMES.cmake          |   10 +
 Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake        |    4 +
 .../CPack/RPM/DEBUGINFO-ExpectedFiles.cmake        |   14 +
 Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt      |    3 +
 .../CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake   |    5 +
 .../CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake    |   63 +
 Tests/RunCMake/CPack/RunCMakeTest.cmake            |    4 +
 Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake          |    9 +
 .../CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake |    9 +
 .../CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake  |   14 +
 .../CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt  |    2 +
 Tests/RunCMake/CPack/VerifyResult.cmake            |   12 +-
 Tests/RunCMake/CTest/BeforeProject-stderr.txt      |    6 +-
 .../CommandLine/E_capabilities-arg-result.txt      |    1 +
 .../CommandLine/E_capabilities-arg-stderr.txt      |    1 +
 .../RunCMake/CommandLine/E_capabilities-stdout.txt |    1 +
 Tests/RunCMake/CommandLine/E_server-arg-result.txt |    1 +
 Tests/RunCMake/CommandLine/E_server-arg-stderr.txt |    1 +
 .../RunCMake/CommandLine/E_server-pipe-result.txt  |    1 +
 .../RunCMake/CommandLine/E_server-pipe-stderr.txt  |    1 +
 Tests/RunCMake/CommandLine/RunCMakeTest.cmake      |    8 +
 .../CommandLine/trace-only-this-file.cmake         |    1 +
 Tests/RunCMake/CommandLine/trace-source-stderr.txt |    1 +
 Tests/RunCMake/CommandLine/trace-source.cmake      |    3 +
 .../Configure/ContinueAfterError-result.txt        |    1 +
 .../Configure/ContinueAfterError-stderr.txt        |   13 +
 .../Configure/ContinueAfterError-stdout.txt        |   11 +
 Tests/RunCMake/Configure/ContinueAfterError.cmake  |   19 +
 Tests/RunCMake/Configure/RunCMakeTest.cmake        |    1 +
 .../ExternalProject/CMAKE_CACHE_ARGS-check.cmake   |    9 +
 .../ExternalProject/CMAKE_CACHE_ARGS.cmake         |    4 +-
 .../CMAKE_CACHE_DEFAULT_ARGS-check.cmake           |    9 +
 .../ExternalProject/CMAKE_CACHE_DEFAULT_ARGS.cmake |    4 +-
 .../FindPkgConfig_CMAKE_APPBUNDLE_PATH.cmake       |   11 +-
 .../FindPkgConfig_CMAKE_FRAMEWORK_PATH.cmake       |   11 +-
 .../FindPkgConfig_NO_PKGCONFIG_PATH.cmake          |    3 -
 .../FindPkgConfig_PKGCONFIG_PATH.cmake             |   11 +-
 ..._PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake |   11 +-
 ...indPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake |   11 +-
 .../pc-bar/lib32/pkgconfig/.placeholder            |    0
 .../pc-foo/lib32/pkgconfig/.placeholder            |    0
 Tests/RunCMake/Framework/RunCMakeTest.cmake        |    2 +-
 Tests/RunCMake/GenerateExportHeader/CMakeLists.txt |    3 +
 .../GenerateExportHeader/GEH-build-stderr.txt      |    1 +
 .../GenerateExportHeader/GEH-failures.cmake        |   67 +
 .../GenerateExportHeader/GEH-link-error-result.txt |    1 +
 .../GenerateExportHeader/GEH-link-error-stderr.txt |    1 +
 Tests/RunCMake/GenerateExportHeader/GEH.cmake      |  127 +
 .../GenerateExportHeader/RunCMakeTest.cmake        |   27 +
 .../c_identifier/CMakeLists.txt                    |   11 +
 .../c_identifier/c_identifier_class.cpp            |    0
 .../c_identifier/c_identifier_class.h              |    0
 .../GenerateExportHeader/c_identifier/main.cpp     |    8 +
 .../GenerateExportHeader/exportheader_test.cpp     |  169 +
 .../lib_shared_and_static/CMakeLists.txt           |   33 +
 .../lib_shared_and_static/libshared_and_static.cpp |  121 +
 .../lib_shared_and_static/libshared_and_static.h   |   83 +
 .../GenerateExportHeader/libshared/CMakeLists.txt  |   11 +
 .../GenerateExportHeader/libshared/libshared.cpp   |  117 +
 .../GenerateExportHeader/libshared/libshared.h     |   82 +
 .../GenerateExportHeader/libstatic/CMakeLists.txt  |   13 +
 .../GenerateExportHeader/libstatic/libstatic.cpp   |  125 +
 .../GenerateExportHeader/libstatic/libstatic.h     |   86 +
 .../nodeprecated/CMakeLists.txt                    |   22 +
 .../nodeprecated/CMakeLists.txt.in                 |   15 +
 .../GenerateExportHeader/nodeprecated/src/main.cpp |    9 +
 .../nodeprecated/src/someclass.cpp                 |    0
 .../nodeprecated/src/someclass.h                   |    0
 .../reference/Empty/libshared_export.h             |    0
 .../reference/Empty/libstatic_export.h             |    0
 .../reference/MinGW/libshared_export.h             |    0
 .../reference/MinGW/libstatic_export.h             |    0
 .../reference/UNIX/libshared_export.h              |    0
 .../reference/UNIX/libstatic_export.h              |    0
 .../UNIX_DeprecatedOnly/libshared_export.h         |    0
 .../UNIX_DeprecatedOnly/libstatic_export.h         |    0
 .../reference/Win32-Clang/libshared_export.h       |    0
 .../reference/Win32-Clang/libstatic_export.h       |    0
 .../reference/Win32/libshared_export.h             |    0
 .../reference/Win32/libstatic_export.h             |    0
 .../reference/WinEmpty/libshared_export.h          |    0
 .../reference/WinEmpty/libstatic_export.h          |    0
 .../LINK_ONLY-not-linking-result.txt               |    1 +
 .../LINK_ONLY-not-linking-stderr.txt               |    8 +
 .../LINK_ONLY-not-linking.cmake                    |    1 +
 .../GeneratorExpression/RunCMakeTest.cmake         |    1 +
 .../RunCMake/GeneratorPlatform/RunCMakeTest.cmake  |    4 +-
 Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake |    4 +-
 Tests/RunCMake/LinkWhatYouUse/C-Build-stdout.txt   |    2 +
 .../LinkWhatYouUse/C-launch-Build-stdout.txt       |    2 +
 Tests/RunCMake/LinkWhatYouUse/C-launch.cmake       |    3 +
 Tests/RunCMake/LinkWhatYouUse/C.cmake              |    4 +
 Tests/RunCMake/LinkWhatYouUse/CMakeLists.txt       |    3 +
 Tests/RunCMake/LinkWhatYouUse/CXX-Build-stdout.txt |    2 +
 .../LinkWhatYouUse/CXX-launch-Build-stdout.txt     |    2 +
 Tests/RunCMake/LinkWhatYouUse/CXX-launch.cmake     |    3 +
 Tests/RunCMake/LinkWhatYouUse/CXX.cmake            |    4 +
 Tests/RunCMake/LinkWhatYouUse/RunCMakeTest.cmake   |   21 +
 .../{try_compile/src.c => LinkWhatYouUse/main.c}   |    0
 Tests/RunCMake/LinkWhatYouUse/main.cxx             |    4 +
 .../Make/CustomCommandDepfile-ERROR-result.txt     |    1 +
 .../Make/CustomCommandDepfile-ERROR-stderr.txt     |    5 +
 .../RunCMake/Make/CustomCommandDepfile-ERROR.cmake |    8 +
 Tests/RunCMake/Make/RunCMakeTest.cmake             |    2 +
 .../Ninja/CustomCommandDepfile-check.cmake         |    5 +
 Tests/RunCMake/Ninja/CustomCommandDepfile.cmake    |   11 +
 Tests/RunCMake/Ninja/RunCMakeTest.cmake            |    8 +
 Tests/RunCMake/Ninja/SubDir-install-stdout.txt     |    1 +
 Tests/RunCMake/Ninja/SubDir-test-stdout.txt        |    1 +
 Tests/RunCMake/Ninja/SubDir.cmake                  |    5 +
 Tests/RunCMake/Ninja/SubDir/CMakeLists.txt         |    4 +
 Tests/RunCMake/RunCMake.cmake                      |    6 +-
 Tests/RunCMake/Syntax/BOM-UTF-16-BE-stderr.txt     |    6 +-
 Tests/RunCMake/Syntax/BOM-UTF-16-LE-stderr.txt     |    6 +-
 Tests/RunCMake/Syntax/BOM-UTF-32-BE-stderr.txt     |    6 +-
 Tests/RunCMake/Syntax/BOM-UTF-32-LE-stderr.txt     |    6 +-
 Tests/RunCMake/Syntax/BracketComment4-stderr.txt   |   11 +-
 Tests/RunCMake/Syntax/BracketNoSpace0-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/BracketNoSpace1-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/BracketNoSpace2-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/BracketNoSpace3-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/BracketNoSpace4-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/BracketNoSpace5-stderr.txt   |    6 +-
 Tests/RunCMake/Syntax/CommandEOF-result.txt        |    1 +
 Tests/RunCMake/Syntax/CommandEOF-stderr.txt        |    6 +
 Tests/RunCMake/Syntax/CommandEOF.cmake             |    1 +
 Tests/RunCMake/Syntax/CommandError0-stderr.txt     |   12 +-
 Tests/RunCMake/Syntax/CommandError1-stderr.txt     |   11 +-
 Tests/RunCMake/Syntax/CommandError2-stderr.txt     |   12 +-
 Tests/RunCMake/Syntax/ParenInENV-stderr.txt        |    8 +-
 Tests/RunCMake/Syntax/ParenNoSpace1-stderr.txt     |   18 +-
 Tests/RunCMake/Syntax/RunCMakeTest.cmake           |    1 +
 Tests/RunCMake/Syntax/StringNoSpace-stderr.txt     |   12 +-
 .../Syntax/UnterminatedBracket0-stderr.txt         |   13 +-
 .../Syntax/UnterminatedBracket1-stderr.txt         |   13 +-
 .../Syntax/UnterminatedBracketComment-stderr.txt   |   13 +-
 Tests/RunCMake/Syntax/UnterminatedCall1-stderr.txt |   11 +-
 Tests/RunCMake/Syntax/UnterminatedCall2-stderr.txt |   11 +-
 .../RunCMake/Syntax/UnterminatedString-stderr.txt  |   13 +-
 Tests/RunCMake/ToolchainFile/FlagsInit-stdout.txt  |   30 +
 .../ToolchainFile/FlagsInit-toolchain.cmake        |    7 +
 Tests/RunCMake/ToolchainFile/FlagsInit.cmake       |    7 +
 .../ToolchainFile/LinkFlagsInit-stdout.txt         |   60 +
 .../ToolchainFile/LinkFlagsInit-toolchain.cmake    |    5 +
 Tests/RunCMake/ToolchainFile/LinkFlagsInit.cmake   |    7 +
 Tests/RunCMake/ToolchainFile/RunCMakeTest.cmake    |    2 +
 Tests/RunCMake/XcodeProject/RunCMakeTest.cmake     |   21 +-
 .../XcodeAttributeLocation-check.cmake             |    7 +
 .../XcodeProject/XcodeAttributeLocation.cmake      |    3 +
 .../XcodeProject/XcodeBundles-install-check.cmake  |    8 +
 Tests/RunCMake/XcodeProject/XcodeBundles.cmake     |   40 +
 .../add_custom_command/AppendNotOutput-stderr.txt  |    5 +-
 .../RunCMake/add_custom_target/RunCMakeTest.cmake  |   14 +
 Tests/RunCMake/add_custom_target/TargetOrder.cmake |   31 +
 .../RunCMake/add_subdirectory/ExcludeFromAll.cmake |    6 +
 .../add_subdirectory/ExcludeFromAll/CMakeLists.txt |    4 +
 .../add_subdirectory/ExcludeFromAll/bar.cpp        |    1 +
 .../add_subdirectory/ExcludeFromAll/foo.cpp        |    6 +
 .../RunCMake/add_subdirectory/ExcludeFromAll/foo.h |    1 +
 Tests/RunCMake/add_subdirectory/RunCMakeTest.cmake |   12 +
 Tests/RunCMake/add_subdirectory/main.cpp           |    6 +
 Tests/RunCMake/cmake_parse_arguments/ArgvN.cmake   |   38 +
 .../cmake_parse_arguments/BadArgvN1-result.txt     |    1 +
 .../cmake_parse_arguments/BadArgvN1-stderr.txt     |    5 +
 .../RunCMake/cmake_parse_arguments/BadArgvN1.cmake |    4 +
 .../cmake_parse_arguments/BadArgvN2-result.txt     |    1 +
 .../cmake_parse_arguments/BadArgvN2-stderr.txt     |    5 +
 .../RunCMake/cmake_parse_arguments/BadArgvN2.cmake |    4 +
 .../cmake_parse_arguments/BadArgvN3-result.txt     |    1 +
 .../cmake_parse_arguments/BadArgvN3-stderr.txt     |    4 +
 .../RunCMake/cmake_parse_arguments/BadArgvN3.cmake |    1 +
 .../cmake_parse_arguments/BadArgvN4-result.txt     |    1 +
 .../cmake_parse_arguments/BadArgvN4-stderr.txt     |    4 +
 .../RunCMake/cmake_parse_arguments/BadArgvN4.cmake |    3 +
 .../cmake_parse_arguments/CornerCasesArgvN.cmake   |   53 +
 .../cmake_parse_arguments/RunCMakeTest.cmake       |    6 +
 Tests/RunCMake/cmake_parse_arguments/Utils.cmake   |    1 +
 .../cmake_parse_arguments/test_utils.cmake         |   44 +-
 Tests/RunCMake/continue/ContinueWhile.cmake        |    2 +-
 Tests/RunCMake/ctest_cmake_error/CMakeLists.txt.in |    4 +
 .../CTestCaptureErrorNonZero-stderr.txt            |    4 +
 .../CTestCaptureErrorZero-stderr.txt               |    4 +
 .../CTestCaptureErrorZero-stdout.txt               |    1 +
 .../ctest_cmake_error/CTestConfig.cmake.in         |    1 +
 .../ctest_cmake_error/CoverageQuiet-stdout.txt     |    1 +
 .../RunCMake/ctest_cmake_error/RunCMakeTest.cmake  |   10 +
 Tests/RunCMake/ctest_cmake_error/test.cmake.in     |   22 +
 Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in    |   81 +
 Tests/RunCMake/ctest_fixtures/CTestConfig.cmake.in |    1 +
 Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake   |   36 +
 .../ctest_fixtures/cyclicCleanup-result.txt        |    1 +
 .../ctest_fixtures/cyclicCleanup-stderr.txt        |    3 +
 .../ctest_fixtures/cyclicCleanup-stdout.txt        |    1 +
 .../RunCMake/ctest_fixtures/cyclicSetup-result.txt |    1 +
 .../RunCMake/ctest_fixtures/cyclicSetup-stderr.txt |    3 +
 .../RunCMake/ctest_fixtures/cyclicSetup-stdout.txt |    1 +
 Tests/RunCMake/ctest_fixtures/one-stdout.txt       |   13 +
 Tests/RunCMake/ctest_fixtures/setupFoo-stdout.txt  |    7 +
 Tests/RunCMake/ctest_fixtures/test.cmake.in        |   16 +
 Tests/RunCMake/ctest_fixtures/three-stdout.txt     |   17 +
 Tests/RunCMake/ctest_fixtures/two-stdout.txt       |   11 +
 Tests/RunCMake/ctest_fixtures/wontRun-stdout.txt   |   14 +
 .../file/DOWNLOAD-httpheader-not-set-result.txt    |    1 +
 .../file/DOWNLOAD-httpheader-not-set-stderr.txt    |    4 +
 .../file/DOWNLOAD-httpheader-not-set.cmake         |    1 +
 .../RunCMake/file/DOWNLOAD-pass-not-set-result.txt |    1 +
 .../RunCMake/file/DOWNLOAD-pass-not-set-stderr.txt |    4 +
 Tests/RunCMake/file/DOWNLOAD-pass-not-set.cmake    |    1 +
 .../file/DOWNLOAD-unused-argument-result.txt       |    0
 .../file/DOWNLOAD-unused-argument-stderr.txt       |    5 +
 Tests/RunCMake/file/DOWNLOAD-unused-argument.cmake |    5 +
 .../RunCMake/file/DOWNLOAD-unused-argument.txt     |    0
 Tests/RunCMake/file/LOCK-lowercase.cmake           |   11 +
 Tests/RunCMake/file/RunCMakeTest.cmake             |    7 +
 .../file/UPLOAD-httpheader-not-set-result.txt      |    1 +
 .../file/UPLOAD-httpheader-not-set-stderr.txt      |    4 +
 .../RunCMake/file/UPLOAD-httpheader-not-set.cmake  |    1 +
 Tests/RunCMake/file/UPLOAD-pass-not-set-result.txt |    1 +
 Tests/RunCMake/file/UPLOAD-pass-not-set-stderr.txt |    4 +
 Tests/RunCMake/file/UPLOAD-pass-not-set.cmake      |    1 +
 .../file/UPLOAD-unused-argument-result.txt         |    0
 .../file/UPLOAD-unused-argument-stderr.txt         |    5 +
 Tests/RunCMake/file/UPLOAD-unused-argument.cmake   |    5 +
 .../RunCMake/file/UPLOAD-unused-argument.txt       |    0
 .../Foo.framework/Headers/Some/Dir/Header.h        |    0
 .../find_path/FrameworksWithSubdirs-stdout.txt     |    1 +
 .../RunCMake/find_path/FrameworksWithSubdirs.cmake |    3 +
 Tests/RunCMake/find_path/RunCMakeTest.cmake        |    4 +
 .../get_filename_component/KnownComponents.cmake   |   12 +-
 .../get_property/directory_properties-stderr.txt   |   18 +-
 .../get_property/directory_properties.cmake        |   15 +
 .../directory_properties/CMakeLists.txt            |    6 +
 .../directory_properties/sub1/CMakeLists.txt       |    0
 .../directory_properties/sub2/CMakeLists.txt       |    0
 Tests/RunCMake/if/IsDirectoryLong.cmake            |    2 +-
 .../include_external_msproject/check_utils.cmake   |    6 +-
 .../install/DIRECTORY-MESSAGE_NEVER-check.cmake    |    8 +-
 .../RunCMake/install/DIRECTORY-message-check.cmake |   12 +-
 .../install/DIRECTORY-message-lazy-check.cmake     |   12 +-
 Tests/RunCMake/message/RunCMakeTest.cmake          |    2 +
 .../message/message-internal-warning-stderr.txt    |   13 +
 .../message/message-internal-warning.cmake         |    5 +
 .../message/nomessage-internal-warning-stderr.txt  |    0
 .../message/nomessage-internal-warning.cmake       |    5 +
 Tests/RunCMake/project/ExplicitRC.cmake            |    1 +
 Tests/RunCMake/project/RunCMakeTest.cmake          |    3 +
 Tests/RunCMake/try_compile/CMP0066-stderr.txt      |   15 +
 Tests/RunCMake/try_compile/CMP0066-stdout.txt      |    4 +
 Tests/RunCMake/try_compile/CMP0066.cmake           |   58 +
 Tests/RunCMake/try_compile/RunCMakeTest.cmake      |    1 +
 Tests/RunCMake/try_compile/src.c                   |    3 +
 Tests/Server/CMakeLists.txt                        |   26 +
 Tests/Server/buildsystem1/CMakeLists.txt           |   22 +
 Tests/Server/buildsystem1/foo.cpp                  |    5 +
 Tests/Server/buildsystem1/main.cpp                 |    5 +
 Tests/Server/buildsystem1/subdir/CMakeLists.txt    |    5 +
 Tests/Server/buildsystem1/subdir/empty.cpp         |    5 +
 Tests/Server/cmakelib.py                           |  198 +
 Tests/Server/cmakelib.pyc                          |  Bin 0 -> 7544 bytes
 Tests/Server/empty.cpp                             |    5 +
 Tests/Server/server-test.py                        |  119 +
 Tests/Server/tc_buildsystem1.json                  |   27 +
 Tests/Server/tc_globalSettings.json                |  140 +
 Tests/Server/tc_handshake.json                     |   71 +
 Tests/SimpleInstall/CMakeLists.txt                 |    4 +-
 Tests/SimpleInstallS2/CMakeLists.txt               |    4 +-
 Tests/SwiftOnly/CMakeLists.txt                     |    4 +
 Tests/TryCompile/CMakeLists.txt                    |    4 +-
 Tests/VSExternalInclude/CMakeLists.txt             |    4 +-
 Tests/VSMASM/CMakeLists.txt                        |    2 +-
 Tests/VSNsightTegra/CMakeLists.txt                 |    2 +-
 Tests/VSWinStorePhone/CMakeLists.txt               |    9 +-
 .../Direct3DApp1/Strings/en-US/Resources.resw      |  123 +
 Utilities/CMakeLists.txt                           |   14 +-
 Utilities/Doxygen/CMakeLists.txt                   |  105 +-
 Utilities/Doxygen/DeveloperReference/mainpage.dox  |    8 +
 Utilities/Doxygen/authors.txt                      |   17 -
 Utilities/Doxygen/doc_makeall.sh.in                |  248 -
 Utilities/Doxygen/doxyfile.in                      |   35 +-
 Utilities/Git/commit-msg                           |   13 +-
 Utilities/Git/pre-commit                           |   13 +-
 Utilities/Git/prepare-commit-msg                   |   13 +-
 Utilities/KWIML/Copyright.txt                      |    2 +-
 Utilities/KWIML/include/kwiml/abi.h                |    6 +-
 Utilities/KWIML/include/kwiml/int.h                |    2 +-
 Utilities/KWIML/src/version.h.in                   |    2 +-
 Utilities/KWStyle/CMakeLists.txt                   |   13 +-
 Utilities/KWStyle/Headers/CMakeHeader.h            |   11 -
 Utilities/Release/Cygwin/CMakeLists.txt            |   25 -
 Utilities/Release/Cygwin/README.cygwin.in          |   42 -
 Utilities/Release/Cygwin/cygwin-package.sh.in      |   90 -
 Utilities/Release/Cygwin/cygwin-setup.hint.in      |    5 -
 Utilities/Release/README                           |    3 -
 Utilities/Release/create-cmake-release.cmake       |    3 -
 Utilities/Release/cygwin_release.cmake             |   32 -
 Utilities/Release/linux32_release.cmake            |   25 -
 Utilities/Release/linux64_release.cmake            |   31 +-
 Utilities/Release/osx_release.cmake                |    7 +-
 Utilities/Release/release_cmake.cmake              |    4 -
 Utilities/Release/upload_release.cmake             |    2 +-
 Utilities/Release/win32_release.cmake              |    7 +-
 Utilities/Release/win64_release.cmake              |    7 +-
 Utilities/Scripts/BoostScanDeps.cmake              |   16 +-
 Utilities/Scripts/clang-format.bash                |    2 +-
 Utilities/Scripts/update-curl.bash                 |    2 +-
 Utilities/Scripts/update-kwiml.bash                |    2 +-
 Utilities/Scripts/update-liblzma.bash              |   30 +
 Utilities/Scripts/update-libuv.bash                |   26 +
 Utilities/Scripts/update-third-party.bash          |    8 +-
 Utilities/Scripts/update-vim-syntax.bash           |   24 +
 Utilities/Sphinx/CMakeLists.txt                    |   35 +-
 Utilities/Sphinx/cmake.py                          |   14 +-
 Utilities/Sphinx/conf.py.in                        |   14 +-
 Utilities/cmThirdParty.h.in                        |   14 +-
 Utilities/cm_bzlib.h                               |   13 +-
 Utilities/cm_curl.h                                |   13 +-
 Utilities/cm_expat.h                               |   13 +-
 Utilities/cm_jsoncpp_reader.h                      |   13 +-
 Utilities/cm_jsoncpp_value.h                       |   13 +-
 Utilities/cm_jsoncpp_writer.h                      |   13 +-
 Utilities/cm_kwiml.h                               |   13 +-
 Utilities/cm_libarchive.h                          |   13 +-
 Utilities/cm_lzma.h                                |   13 +-
 Utilities/cm_uv.h                                  |   14 +
 Utilities/cm_xmlrpc.h                              |   13 +-
 Utilities/cm_zlib.h                                |   13 +-
 Utilities/cmlibarchive/libarchive/xxhash.c         |    5 +-
 Utilities/cmliblzma/CMakeLists.txt                 |    6 +-
 Utilities/cmliblzma/README-CMake.txt               |   66 -
 Utilities/cmliblzma/liblzma/api/lzma/block.h       |    3 +
 Utilities/cmliblzma/liblzma/api/lzma/version.h     |    2 +-
 Utilities/cmliblzma/liblzma/check/crc32_fast.c     |    2 +-
 Utilities/cmliblzma/liblzma/check/sha256.c         |    2 +-
 .../cmliblzma/liblzma/lzma/lzma_encoder_presets.c  |    9 +-
 Utilities/cmlibuv/.gitattributes                   |    1 +
 Utilities/cmlibuv/CMakeLists.txt                   |  236 +
 Utilities/cmlibuv/LICENSE                          |   70 +
 Utilities/cmlibuv/include/android-ifaddrs.h        |   54 +
 Utilities/cmlibuv/include/pthread-barrier.h        |   66 +
 Utilities/cmlibuv/include/stdint-msvc2008.h        |  247 +
 Utilities/cmlibuv/include/tree.h                   |  768 ++++
 Utilities/cmlibuv/include/uv-aix.h                 |   32 +
 Utilities/cmlibuv/include/uv-bsd.h                 |   34 +
 Utilities/cmlibuv/include/uv-darwin.h              |   61 +
 Utilities/cmlibuv/include/uv-errno.h               |  419 ++
 Utilities/cmlibuv/include/uv-linux.h               |   34 +
 Utilities/cmlibuv/include/uv-os390.h               |   27 +
 Utilities/cmlibuv/include/uv-sunos.h               |   44 +
 Utilities/cmlibuv/include/uv-threadpool.h          |   37 +
 Utilities/cmlibuv/include/uv-unix.h                |  371 ++
 Utilities/cmlibuv/include/uv-version.h             |   43 +
 Utilities/cmlibuv/include/uv-win.h                 |  660 +++
 Utilities/cmlibuv/include/uv.h                     | 1499 ++++++
 Utilities/cmlibuv/src/fs-poll.c                    |  256 ++
 Utilities/cmlibuv/src/heap-inl.h                   |  245 +
 Utilities/cmlibuv/src/inet.c                       |  309 ++
 Utilities/cmlibuv/src/queue.h                      |  108 +
 Utilities/cmlibuv/src/threadpool.c                 |  303 ++
 Utilities/cmlibuv/src/unix/aix.c                   | 1154 +++++
 Utilities/cmlibuv/src/unix/android-ifaddrs.c       |  703 +++
 Utilities/cmlibuv/src/unix/async.c                 |  290 ++
 Utilities/cmlibuv/src/unix/atomic-ops.h            |   88 +
 Utilities/cmlibuv/src/unix/core.c                  | 1238 +++++
 Utilities/cmlibuv/src/unix/darwin-proctitle.c      |  206 +
 Utilities/cmlibuv/src/unix/darwin.c                |  335 ++
 Utilities/cmlibuv/src/unix/dl.c                    |   80 +
 Utilities/cmlibuv/src/unix/freebsd.c               |  460 ++
 Utilities/cmlibuv/src/unix/fs.c                    | 1364 ++++++
 Utilities/cmlibuv/src/unix/fsevents.c              |  904 ++++
 Utilities/cmlibuv/src/unix/getaddrinfo.c           |  202 +
 Utilities/cmlibuv/src/unix/getnameinfo.c           |  120 +
 Utilities/cmlibuv/src/unix/internal.h              |  322 ++
 Utilities/cmlibuv/src/unix/kqueue.c                |  463 ++
 Utilities/cmlibuv/src/unix/linux-core.c            |  985 ++++
 Utilities/cmlibuv/src/unix/linux-inotify.c         |  285 ++
 Utilities/cmlibuv/src/unix/linux-syscalls.c        |  471 ++
 Utilities/cmlibuv/src/unix/linux-syscalls.h        |  151 +
 Utilities/cmlibuv/src/unix/loop-watcher.c          |   68 +
 Utilities/cmlibuv/src/unix/loop.c                  |  159 +
 Utilities/cmlibuv/src/unix/netbsd.c                |  380 ++
 Utilities/cmlibuv/src/unix/openbsd.c               |  396 ++
 Utilities/cmlibuv/src/unix/os390.c                 |   42 +
 Utilities/cmlibuv/src/unix/pipe.c                  |  295 ++
 Utilities/cmlibuv/src/unix/poll.c                  |  130 +
 Utilities/cmlibuv/src/unix/process.c               |  563 +++
 Utilities/cmlibuv/src/unix/proctitle.c             |  105 +
 Utilities/cmlibuv/src/unix/pthread-barrier.c       |  120 +
 Utilities/cmlibuv/src/unix/pthread-fixes.c         |   56 +
 Utilities/cmlibuv/src/unix/signal.c                |  467 ++
 Utilities/cmlibuv/src/unix/spinlock.h              |   53 +
 Utilities/cmlibuv/src/unix/stream.c                | 1638 +++++++
 Utilities/cmlibuv/src/unix/sunos.c                 |  821 ++++
 Utilities/cmlibuv/src/unix/tcp.c                   |  395 ++
 Utilities/cmlibuv/src/unix/thread.c                |  605 +++
 Utilities/cmlibuv/src/unix/timer.c                 |  172 +
 Utilities/cmlibuv/src/unix/tty.c                   |  333 ++
 Utilities/cmlibuv/src/unix/udp.c                   |  895 ++++
 Utilities/cmlibuv/src/uv-common.c                  |  654 +++
 Utilities/cmlibuv/src/uv-common.h                  |  227 +
 Utilities/cmlibuv/src/version.c                    |   45 +
 Utilities/cmlibuv/src/win/async.c                  |   99 +
 Utilities/cmlibuv/src/win/atomicops-inl.h          |   56 +
 Utilities/cmlibuv/src/win/core.c                   |  602 +++
 Utilities/cmlibuv/src/win/detect-wakeup.c          |   35 +
 Utilities/cmlibuv/src/win/dl.c                     |  118 +
 Utilities/cmlibuv/src/win/error.c                  |  170 +
 Utilities/cmlibuv/src/win/fs-event.c               |  545 +++
 Utilities/cmlibuv/src/win/fs.c                     | 2496 ++++++++++
 Utilities/cmlibuv/src/win/getaddrinfo.c            |  385 ++
 Utilities/cmlibuv/src/win/getnameinfo.c            |  150 +
 Utilities/cmlibuv/src/win/handle-inl.h             |  179 +
 Utilities/cmlibuv/src/win/handle.c                 |  154 +
 Utilities/cmlibuv/src/win/internal.h               |  398 ++
 Utilities/cmlibuv/src/win/loop-watcher.c           |  122 +
 Utilities/cmlibuv/src/win/pipe.c                   | 2130 +++++++++
 Utilities/cmlibuv/src/win/poll.c                   |  646 +++
 Utilities/cmlibuv/src/win/process-stdio.c          |  510 +++
 Utilities/cmlibuv/src/win/process.c                | 1247 +++++
 Utilities/cmlibuv/src/win/req-inl.h                |  224 +
 Utilities/cmlibuv/src/win/req.c                    |   25 +
 Utilities/cmlibuv/src/win/signal.c                 |  356 ++
 Utilities/cmlibuv/src/win/snprintf.c               |   42 +
 Utilities/cmlibuv/src/win/stream-inl.h             |   56 +
 Utilities/cmlibuv/src/win/stream.c                 |  249 +
 Utilities/cmlibuv/src/win/tcp.c                    | 1510 +++++++
 Utilities/cmlibuv/src/win/thread.c                 |  697 +++
 Utilities/cmlibuv/src/win/timer.c                  |  195 +
 Utilities/cmlibuv/src/win/tty.c                    | 2257 ++++++++++
 Utilities/cmlibuv/src/win/udp.c                    |  928 ++++
 Utilities/cmlibuv/src/win/util.c                   | 1389 ++++++
 Utilities/cmlibuv/src/win/winapi.c                 |  159 +
 Utilities/cmlibuv/src/win/winapi.h                 | 4757 ++++++++++++++++++++
 Utilities/cmlibuv/src/win/winsock.c                |  561 +++
 Utilities/cmlibuv/src/win/winsock.h                |  191 +
 bootstrap                                          |   49 +-
 2237 files changed, 89112 insertions(+), 29704 deletions(-)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5d1732d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+# Exclude MacOS Finder files.
+.DS_Store
+
+*.user*
+
+*.pyc
+Testing
diff --git a/.hooks-config.bash b/.hooks-config.bash
index 97152f6..ea9342a 100644
--- a/.hooks-config.bash
+++ b/.hooks-config.bash
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 # Loaded by .git/hooks/(pre-commit|commit-msg|prepare-commit-msg)
 # during git commit after local hooks have been installed.
diff --git a/Auxiliary/CMakeLists.txt b/Auxiliary/CMakeLists.txt
index c003b28..8eb74b7 100644
--- a/Auxiliary/CMakeLists.txt
+++ b/Auxiliary/CMakeLists.txt
@@ -1,4 +1,4 @@
-install(FILES cmake-help.vim cmake-indent.vim cmake-syntax.vim DESTINATION ${CMAKE_DATA_DIR}/editors/vim)
+install(DIRECTORY vim/indent vim/syntax DESTINATION ${CMAKE_DATA_DIR}/editors/vim)
 install(FILES cmake-mode.el DESTINATION ${CMAKE_DATA_DIR}/editors/emacs)
 install(FILES cmake.m4 DESTINATION share/aclocal)
 add_subdirectory (bash-completion)
diff --git a/Auxiliary/bash-completion/cmake b/Auxiliary/bash-completion/cmake
index 6061129..0a862fa 100644
--- a/Auxiliary/bash-completion/cmake
+++ b/Auxiliary/bash-completion/cmake
@@ -102,7 +102,7 @@ _cmake()
             ;;
         -E)
             COMPREPLY=( $( compgen -W "$( cmake -E help |& sed -n \
-                '/^  /{s|^  \([^ ]\{1,\}\) .*$|\1|;p}' 2>/dev/null )" \
+                '/^  [^ ]/{s|^  \([^ ]\{1,\}\) .*$|\1|;p}' 2>/dev/null )" \
                 -- "$cur" ) )
             return
             ;;
diff --git a/Auxiliary/cmake-help.vim b/Auxiliary/cmake-help.vim
deleted file mode 100644
index 17cfa83..0000000
--- a/Auxiliary/cmake-help.vim
+++ /dev/null
@@ -1,21 +0,0 @@
-nmap ,hc :call OpenCmakeHelp()<CR>
-
-function! OpenCmakeHelp()
-    let s = getline( '.' )
-    let i = col( '.' ) - 1
-    while i > 0 && strpart( s, i, 1 ) =~ '[A-Za-z0-9_]'
-        let i = i - 1
-    endwhile
-    while i < col('$') && strpart( s, i, 1 ) !~ '[A-Za-z0-9_]'
-        let i = i + 1
-    endwhile
-    let start = match( s, '[A-Za-z0-9_]\+', i )
-    let end = matchend( s, '[A-Za-z0-9_]\+', i )
-    let ident = strpart( s, start, end - start )
-    execute "vertical new"
-    execute "%!cmake --help-command ".ident
-    set nomodified
-    set readonly
-endfunction
-
-autocmd BufRead,BufNewFile *.cmake,CMakeLists.txt,*.cmake.in nmap <F1> :call OpenCmakeHelp()<CR>
diff --git a/Auxiliary/cmake-indent.vim b/Auxiliary/cmake-indent.vim
deleted file mode 100644
index fa088e4..0000000
--- a/Auxiliary/cmake-indent.vim
+++ /dev/null
@@ -1,93 +0,0 @@
-" =============================================================================
-"
-"   Program:   CMake - Cross-Platform Makefile Generator
-"   Module:    $RCSfile$
-"   Language:  VIM
-"   Date:      $Date$
-"   Version:   $Revision$
-"
-" =============================================================================
-
-" Vim indent file
-" Language:     CMake (ft=cmake)
-" Author:       Andy Cedilnik <andy.cedilnik at kitware.com>
-" Maintainer:   Karthik Krishnan <karthik.krishnan at kitware.com>
-" Last Change:  $Date$
-" Version:      $Revision$
-"
-" Licence:      The CMake license applies to this file. See
-"               https://cmake.org/licensing
-"               This implies that distribution with Vim is allowed
-
-if exists("b:did_indent")
-  finish
-endif
-let b:did_indent = 1
-
-setlocal indentexpr=CMakeGetIndent(v:lnum)
-setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE(
-
-" Only define the function once.
-if exists("*CMakeGetIndent")
-  finish
-endif
-
-fun! CMakeGetIndent(lnum)
-  let this_line = getline(a:lnum)
-
-  " Find a non-blank line above the current line.
-  let lnum = a:lnum
-  let lnum = prevnonblank(lnum - 1)
-  let previous_line = getline(lnum)
-
-  " Hit the start of the file, use zero indent.
-  if lnum == 0
-    return 0
-  endif
-
-  let ind = indent(lnum)
-
-  let or = '\|'
-  " Regular expressions used by line indentation function.
-  let cmake_regex_comment = '#.*'
-  let cmake_regex_identifier = '[A-Za-z][A-Za-z0-9_]*'
-  let cmake_regex_quoted = '"\([^"\\]\|\\.\)*"'
-  let cmake_regex_arguments = '\(' . cmake_regex_quoted .
-                    \       or . '\$(' . cmake_regex_identifier . ')' .
-                    \       or . '[^()\\#"]' . or . '\\.' . '\)*'
-
-  let cmake_indent_comment_line = '^\s*' . cmake_regex_comment
-  let cmake_indent_blank_regex = '^\s*$'
-  let cmake_indent_open_regex = '^\s*' . cmake_regex_identifier .
-                    \           '\s*(' . cmake_regex_arguments .
-                    \           '\(' . cmake_regex_comment . '\)\?$'
-
-  let cmake_indent_close_regex = '^' . cmake_regex_arguments .
-                    \            ')\s*' .
-                    \            '\(' . cmake_regex_comment . '\)\?$'
-
-  let cmake_indent_begin_regex = '^\s*\(IF\|MACRO\|FOREACH\|ELSE\|ELSEIF\|WHILE\|FUNCTION\)\s*('
-  let cmake_indent_end_regex = '^\s*\(ENDIF\|ENDFOREACH\|ENDMACRO\|ELSE\|ELSEIF\|ENDWHILE\|ENDFUNCTION\)\s*('
-
-  " Add
-  if previous_line =~? cmake_indent_comment_line " Handle comments
-    let ind = ind
-  else
-    if previous_line =~? cmake_indent_begin_regex
-      let ind = ind + &sw
-    endif
-    if previous_line =~? cmake_indent_open_regex
-      let ind = ind + &sw
-    endif
-  endif
-
-  " Subtract
-  if this_line =~? cmake_indent_end_regex
-    let ind = ind - &sw
-  endif
-  if previous_line =~? cmake_indent_close_regex
-    let ind = ind - &sw
-  endif
-
-  return ind
-endfun
diff --git a/Auxiliary/cmake-mode.el b/Auxiliary/cmake-mode.el
index 20def8b..a1b43c5 100644
--- a/Auxiliary/cmake-mode.el
+++ b/Auxiliary/cmake-mode.el
@@ -1,16 +1,7 @@
 ;;; cmake-mode.el --- major-mode for editing CMake sources
 
-;=============================================================================
-; CMake - Cross Platform Makefile Generator
-; Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-;
-; Distributed under the OSI-approved BSD License (the "License");
-; see accompanying file Copyright.txt for details.
-;
-; This software is distributed WITHOUT ANY WARRANTY; without even the
-; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-; See the License for more information.
-;=============================================================================
+; Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+; file Copyright.txt or https://cmake.org/licensing for details.
 
 ;------------------------------------------------------------------------------
 
@@ -114,6 +105,14 @@ set the path with these commands:
 ;------------------------------------------------------------------------------
 
 ;;
+;; Indentation increment.
+;;
+(defcustom cmake-tab-width 2
+  "Number of columns to indent cmake blocks"
+  :type 'integer
+  :group 'cmake)
+
+;;
 ;; Line indentation function.
 ;;
 (defun cmake-indent ()
@@ -225,13 +224,6 @@ the indentation.  Otherwise it retains the same position on the line"
 ;;
 (defvar cmake-mode-hook nil)
 
-;;
-;; Indentation increment.
-;;
-(defcustom cmake-tab-width 2
-  "Number of columns to indent cmake blocks"
-  :type 'integer)
-
 ;------------------------------------------------------------------------------
 
 ;; For compatibility with Emacs < 24
@@ -270,7 +262,7 @@ optional argument topic will be appended to the argument list."
     (save-selected-window
       (select-window (display-buffer buffer 'not-this-window))
       (cmake-mode)
-      (toggle-read-only t))
+      (read-only-mode 1))
     )
   )
 
diff --git a/Auxiliary/cmake-syntax.vim b/Auxiliary/cmake-syntax.vim
deleted file mode 100644
index 624a8c4..0000000
--- a/Auxiliary/cmake-syntax.vim
+++ /dev/null
@@ -1,89 +0,0 @@
-" =============================================================================
-"
-"   Program:   CMake - Cross-Platform Makefile Generator
-"   Module:    $RCSfile$
-"   Language:  VIM
-"   Date:      $Date$
-"   Version:   $Revision$
-"
-" =============================================================================
-
-" Vim syntax file
-" Language:     CMake
-" Author:       Andy Cedilnik <andy.cedilnik at kitware.com>
-" Maintainer:   Karthik Krishnan <karthik.krishnan at kitware.com>
-" Last Change:  $Date$
-" Version:      $Revision$
-"
-" Licence:      The CMake license applies to this file. See
-"               https://cmake.org/licensing
-"               This implies that distribution with Vim is allowed
-
-" For version 5.x: Clear all syntax items
-" For version 6.x: Quit when a syntax file was already loaded
-if version < 600
-  syntax clear
-elseif exists("b:current_syntax")
-  finish
-endif
-
-syn case ignore
-syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained
-syn region cmakeComment start="#" end="$" contains=cmakeTodo
-syn region cmakeRegistry start=/\[/ end=/]/
-            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeEscaped
-syn region cmakeVariableValue start=/\${/ end=/}/
-            \ contained oneline contains=CONTAINED,cmakeTodo
-syn region cmakeEnvironment start=/\$ENV{/ end=/}/
-            \ contained oneline contains=CONTAINED,cmakeTodo
-syn region cmakeString start=/"/ end=/"/
-            \ contains=CONTAINED,cmakeTodo,cmakeOperators
-syn region cmakeArguments start=/(/ end=/)/
-            \ contains=ALLBUT,cmakeArguments,cmakeTodo
-syn keyword cmakeSystemVariables
-            \ WIN32 UNIX APPLE CYGWIN BORLAND MINGW MSVC MSVC_IDE MSVC60 MSVC70 MSVC71 MSVC80 MSVC90
-syn keyword cmakeOperators
-            \ ABSOLUTE AND BOOL CACHE COMMAND DEFINED DOC EQUAL EXISTS EXT FALSE GREATER INTERNAL LESS MATCHES NAME NAMES NAME_WE NOT OFF ON OR PATH PATHS PROGRAM STREQUAL STRGREATER STRING STRLESS TRUE
-            \ contained
-syn keyword cmakeDeprecated ABSTRACT_FILES BUILD_NAME SOURCE_FILES SOURCE_FILES_REMOVE VTK_MAKE_INSTANTIATOR VTK_WRAP_JAVA VTK_WRAP_PYTHON VTK_WRAP_TCL WRAP_EXCLUDE_FILES
-           \ nextgroup=cmakeArguments
-
-" The keywords are generated as:  cmake --help-command-list | tr "\n" " " | tr "[:lower:]" "[:upper:]"
-syn keyword cmakeStatement
-            \ ADD_COMPILE_OPTIONS ADD_CUSTOM_COMMAND ADD_CUSTOM_TARGET ADD_DEFINITIONS ADD_DEPENDENCIES ADD_EXECUTABLE ADD_LIBRARY ADD_SUBDIRECTORY ADD_TEST AUX_SOURCE_DIRECTORY BREAK BUILD_COMMAND BUILD_NAME CMAKE_HOST_SYSTEM_INFORMATION CMAKE_MINIMUM_REQUIRED CMAKE_POLICY CONFIGURE_FILE CREATE_TEST_SOURCELIST CTEST_BUILD CTEST_CONFIGURE CTEST_COVERAGE CTEST_EMPTY_BINARY_DIRECTORY CTEST_MEMCHECK CTEST_READ_CUSTOM_FILES CTEST_RUN_SCRIPT CTEST_SLEEP CTEST_START CTEST_SUBMIT CTEST_TEST CTE [...]
-            \ nextgroup=cmakeArguments
-syn keyword cmakeTodo
-            \ TODO FIXME XXX
-            \ contained
-
-" Define the default highlighting.
-" For version 5.7 and earlier: only when not done already
-" For version 5.8 and later: only when an item doesn't have highlighting yet
-if version >= 508 || !exists("did_cmake_syntax_inits")
-  if version < 508
-    let did_cmake_syntax_inits = 1
-    command -nargs=+ HiLink hi link <args>
-  else
-    command -nargs=+ HiLink hi def link <args>
-  endif
-
-  HiLink cmakeStatement Statement
-  HiLink cmakeComment Comment
-  HiLink cmakeString String
-  HiLink cmakeVariableValue Type
-  HiLink cmakeRegistry Underlined
-  HiLink cmakeArguments Identifier
-  HiLink cmakeArgument Constant
-  HiLink cmakeEnvironment Special
-  HiLink cmakeOperators Operator
-  HiLink cmakeMacro PreProc
-  HiLink cmakeError Error
-  HiLink cmakeTodo TODO
-  HiLink cmakeEscaped Special
-
-  delcommand HiLink
-endif
-
-let b:current_syntax = "cmake"
-
-"EOF"
diff --git a/Auxiliary/cmake.m4 b/Auxiliary/cmake.m4
index a374a3b..3ef4c16 100644
--- a/Auxiliary/cmake.m4
+++ b/Auxiliary/cmake.m4
@@ -1,14 +1,5 @@
-dnl ============================================================================
-dnl   CMake - Cross Platform Makefile Generator
-dnl   Copyright 2011 Matthias Kretz, kretz at kde.org
-dnl
-dnl   Distributed under the OSI-approved BSD License (the "License");
-dnl   see accompanying file Copyright.txt for details.
-dnl
-dnl   This software is distributed WITHOUT ANY WARRANTY; without even the
-dnl   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-dnl   See the License for more information.
-dnl ============================================================================
+dnl Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+dnl file Copyright.txt or https://cmake.org/licensing for details.
 
 AC_DEFUN([CMAKE_FIND_BINARY],
 [AC_ARG_VAR([CMAKE_BINARY], [path to the cmake binary])dnl
diff --git a/Auxiliary/vim/cmake.vim.in b/Auxiliary/vim/cmake.vim.in
new file mode 100644
index 0000000..89ece66
--- /dev/null
+++ b/Auxiliary/vim/cmake.vim.in
@@ -0,0 +1,91 @@
+" vim: set nowrap:
+" Vim syntax file
+" Language:     CMake
+" Author:       Andy Cedilnik <andy.cedilnik at kitware.com>, Nicholas Hutchinson <nshutchinson at gmail.com>, Patrick Boettcher <patrick.boettcher at posteo.de>
+" Maintainer:   Karthik Krishnan <karthik.krishnan at kitware.com>
+" Last Change:  $Date$
+" Version:      $Revision$
+"
+" Licence:      The CMake license applies to this file. See
+"               https://cmake.org/licensing
+"               This implies that distribution with Vim is allowed
+
+if exists("b:current_syntax")
+  finish
+endif
+
+syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained
+syn region cmakeComment start="#" end="$" contains=cmakeTodo, at Spell
+syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo, at Spell
+syn region cmakeGeneratorExpression start=/$</ end=/>/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariable,cmakeProperty,cmakeGeneratorExpressions
+syn region cmakeRegistry start=/\[/ end=/]/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeEscaped
+syn region cmakeVariableValue start=/\${/ end=/}/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariable
+syn region cmakeEnvironment start=/\$ENV{/ end=/}/
+            \ contained oneline contains=CONTAINED,cmakeTodo
+syn region cmakeString start=/"/ end=/"/
+            \ contains=CONTAINED,cmakeTodo
+syn region cmakeArguments start=/(/ end=/)/
+            \ contains=ALLBUT,cmakeArguments,cmakeTodo
+
+syn case match
+syn keyword cmakeProperty
+            \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_ [...]
+            \ contained
+
+syn keyword cmakeVariable
+ at VARIABLE_LIST@
+            \ contained
+
+syn keyword cmakeModule
+ at MODULES@
+            \ contained
+
+ at KEYWORDS@
+
+syn keyword cmakeGeneratorExpressions
+ at GENERATOR_EXPRESSIONS@
+            \ contained
+
+syn case ignore
+syn keyword cmakeCommand
+ at COMMAND_LIST@
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandConditional
+ at CONDITIONALS@
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandRepeat
+ at LOOPS@
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandDeprecated
+ at DEPRECATED@
+            \ nextgroup=cmakeArguments
+syn case match
+
+syn keyword cmakeTodo
+            \ TODO FIXME XXX
+            \ contained
+
+hi def link cmakeCommand Function
+hi def link cmakeCommandConditional Conditional
+hi def link cmakeCommandDeprecated WarningMsg
+hi def link cmakeCommandRepeat Repeat
+hi def link cmakeComment Comment
+hi def link cmakeEnvironment Special
+hi def link cmakeEscaped Special
+hi def link cmakeGeneratorExpression WarningMsg
+hi def link cmakeGeneratorExpressions ModeMsg
+hi def link cmakeLuaComment Comment
+hi def link cmakeModule Include
+hi def link cmakeProperty Constant
+hi def link cmakeRegistry Underlined
+hi def link cmakeString String
+hi def link cmakeTodo TODO
+hi def link cmakeVariable Identifier
+hi def link cmakeVariableValue Type
+
+ at KEYWORDS_HIGHLIGHT@
+
+let b:current_syntax = "cmake"
diff --git a/Auxiliary/vim/extract-upper-case.pl b/Auxiliary/vim/extract-upper-case.pl
new file mode 100755
index 0000000..e945d52
--- /dev/null
+++ b/Auxiliary/vim/extract-upper-case.pl
@@ -0,0 +1,141 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+my @variables;
+my @commands;
+my @properties;
+my @modules;
+my %keywords; # command => keyword-list
+
+# unwanted upper-cases
+my %unwanted = map { $_ => 1 } qw(VS CXX IDE NOTFOUND NO_ DFOO DBAR);
+	# cannot remove ALL - exists for add_custom_command
+
+# control-statements
+my %conditional = map { $_ => 1 } qw(if else elseif endif);
+my %loop = map { $_ => 1 } qw(foreach while endforeach endwhile);
+
+# decrecated
+my %deprecated = map { $_ => 1 } qw(build_name exec_program export_library_dependencies install_files install_programs install_targets link_libraries make_directory output_required_files remove subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file);
+
+# add some (popular) modules
+push @modules, "ExternalProject";
+
+# variables
+open(CMAKE, "cmake --help-variable-list|") or die "could not run cmake";
+while (<CMAKE>) {
+	chomp;
+	push @variables, $_;
+}
+close(CMAKE);
+
+# transform all variables in a hash - to be able to use exists later on
+my %variables = map { $_ => 1 } @variables;
+
+# commands
+open(CMAKE, "cmake --help-command-list|");
+while (my $cmd = <CMAKE>) {
+	chomp $cmd;
+
+	push @commands, $cmd;
+}
+close(CMAKE);
+
+# now generate a keyword-list per command
+foreach my $cmd (@commands) {
+	my @word = extract_upper("cmake --help-command $cmd|");
+
+	next if scalar @word == 0;
+
+	$keywords{$cmd} = [ sort keys %{ { map { $_ => 1 } @word } } ];
+}
+
+# and now for modules
+foreach my $mod (@modules) {
+	my @word = extract_upper("cmake --help-module $mod|");
+
+	next if scalar @word == 0;
+
+	$keywords{$mod} = [ sort keys %{ { map { $_ => 1 } @word } } ];
+}
+
+# and now for generator-expressions
+my @generator_expr = extract_upper("cmake --help-manual cmake-generator-expressions |");
+
+# properties
+open(CMAKE, "cmake --help-property-list|");
+while (<CMAKE>) {
+	chomp;
+	push @properties, $_;
+}
+close(CMAKE);
+
+# generate cmake.vim
+open(IN,  "<cmake.vim.in") or die "could not read cmake.vim.in";
+open(OUT, ">syntax/cmake.vim") or die "could not write to syntax/cmake.vim";
+
+my @keyword_hi;
+
+while(<IN>)
+{
+	if (m/\@([A-Z0-9_]+)\@/) { # match for @SOMETHING@
+		if ($1 eq "COMMAND_LIST") {
+			# do not include "special" commands in this list
+			my @tmp = grep { ! exists $conditional{$_} and
+			                 ! exists $loop{$_} and
+			                 ! exists $deprecated{$_} } @commands;
+			print OUT " " x 12 , "\\ ", join(" ", @tmp), "\n";
+		} elsif ($1 eq "VARIABLE_LIST") {
+			print OUT " " x 12 , "\\ ", join(" ", @variables), "\n";
+		} elsif ($1 eq "MODULES") {
+			print OUT " " x 12 , "\\ ", join("\n", @modules), "\n";
+		} elsif ($1 eq "GENERATOR_EXPRESSIONS") {
+			print OUT " " x 12 , "\\ ", join(" ", @generator_expr), "\n";
+		} elsif ($1 eq "CONDITIONALS") {
+			print OUT " " x 12 , "\\ ", join(" ", sort keys %conditional), "\n";
+		} elsif ($1 eq "LOOPS") {
+			print OUT " " x 12 , "\\ ", join(" ", sort keys %loop), "\n";
+		} elsif ($1 eq "DEPRECATED") {
+			print OUT " " x 12 , "\\ ", join(" ", sort keys %deprecated), "\n";
+		} elsif ($1 eq "KEYWORDS") {
+			foreach my $k (sort keys %keywords) {
+				print OUT "syn keyword cmakeKW$k\n";
+				print OUT " " x 12, "\\ ", join(" ", @{$keywords{$k}}), "\n";
+				print OUT " " x 12, "\\ contained\n";
+				print OUT "\n";
+				push @keyword_hi, "hi def link cmakeKW$k ModeMsg";
+			}
+		} elsif ($1 eq "KEYWORDS_HIGHLIGHT") {
+			print OUT join("\n", @keyword_hi), "\n";
+		} else {
+			print "ERROR do not know how to replace $1\n";
+		}
+	} else {
+		print OUT $_;
+	}
+}
+close(IN);
+close(OUT);
+
+sub extract_upper
+{
+	my $input = shift;
+	my @word;
+
+	open(KW, $input);
+	while (<KW>) {
+
+		foreach my $w (m/\b([A-Z_]{2,})\b/g) {
+			next
+				if exists $variables{$w} or  # skip if it is a variable
+				   exists $unwanted{$w};     # skip if not wanted
+
+			push @word, $w;
+		}
+	}
+	close(KW);
+
+	return @word;
+}
diff --git a/Auxiliary/vim/indent/cmake.vim b/Auxiliary/vim/indent/cmake.vim
new file mode 100644
index 0000000..76aff64
--- /dev/null
+++ b/Auxiliary/vim/indent/cmake.vim
@@ -0,0 +1,83 @@
+" Vim indent file
+" Language:     CMake (ft=cmake)
+" Author:       Andy Cedilnik <andy.cedilnik at kitware.com>
+" Maintainer:   Karthik Krishnan <karthik.krishnan at kitware.com>
+" Last Change:  $Date$
+" Version:      $Revision$
+"
+" Licence:      The CMake license applies to this file. See
+"               https://cmake.org/licensing
+"               This implies that distribution with Vim is allowed
+
+if exists("b:did_indent")
+  finish
+endif
+let b:did_indent = 1
+
+setlocal indentexpr=CMakeGetIndent(v:lnum)
+setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE(
+
+" Only define the function once.
+if exists("*CMakeGetIndent")
+  finish
+endif
+
+fun! CMakeGetIndent(lnum)
+  let this_line = getline(a:lnum)
+
+  " Find a non-blank line above the current line.
+  let lnum = a:lnum
+  let lnum = prevnonblank(lnum - 1)
+  let previous_line = getline(lnum)
+
+  " Hit the start of the file, use zero indent.
+  if lnum == 0
+    return 0
+  endif
+
+  let ind = indent(lnum)
+
+  let or = '\|'
+  " Regular expressions used by line indentation function.
+  let cmake_regex_comment = '#.*'
+  let cmake_regex_identifier = '[A-Za-z][A-Za-z0-9_]*'
+  let cmake_regex_quoted = '"\([^"\\]\|\\.\)*"'
+  let cmake_regex_arguments = '\(' . cmake_regex_quoted .
+                    \       or . '\$(' . cmake_regex_identifier . ')' .
+                    \       or . '[^()\\#"]' . or . '\\.' . '\)*'
+
+  let cmake_indent_comment_line = '^\s*' . cmake_regex_comment
+  let cmake_indent_blank_regex = '^\s*$'
+  let cmake_indent_open_regex = '^\s*' . cmake_regex_identifier .
+                    \           '\s*(' . cmake_regex_arguments .
+                    \           '\(' . cmake_regex_comment . '\)\?$'
+
+  let cmake_indent_close_regex = '^' . cmake_regex_arguments .
+                    \            ')\s*' .
+                    \            '\(' . cmake_regex_comment . '\)\?$'
+
+  let cmake_indent_begin_regex = '^\s*\(IF\|MACRO\|FOREACH\|ELSE\|ELSEIF\|WHILE\|FUNCTION\)\s*('
+  let cmake_indent_end_regex = '^\s*\(ENDIF\|ENDFOREACH\|ENDMACRO\|ELSE\|ELSEIF\|ENDWHILE\|ENDFUNCTION\)\s*('
+
+  " Add
+  if previous_line =~? cmake_indent_comment_line " Handle comments
+    let ind = ind
+  else
+    if previous_line =~? cmake_indent_begin_regex
+      let ind = ind + &sw
+    endif
+    if previous_line =~? cmake_indent_open_regex
+      let ind = ind + &sw
+    endif
+  endif
+
+  " Subtract
+  if this_line =~? cmake_indent_end_regex
+    let ind = ind - &sw
+  endif
+  if previous_line =~? cmake_indent_close_regex
+    let ind = ind - &sw
+  endif
+
+  return ind
+endfun
diff --git a/Auxiliary/vim/syntax/cmake.vim b/Auxiliary/vim/syntax/cmake.vim
new file mode 100644
index 0000000..11b0fcb
--- /dev/null
+++ b/Auxiliary/vim/syntax/cmake.vim
@@ -0,0 +1,554 @@
+" vim: set nowrap:
+" Vim syntax file
+" Language:     CMake
+" Author:       Andy Cedilnik <andy.cedilnik at kitware.com>, Nicholas Hutchinson <nshutchinson at gmail.com>, Patrick Boettcher <patrick.boettcher at posteo.de>
+" Maintainer:   Karthik Krishnan <karthik.krishnan at kitware.com>
+" Last Change:  $Date$
+" Version:      $Revision$
+"
+" Licence:      The CMake license applies to this file. See
+"               https://cmake.org/licensing
+"               This implies that distribution with Vim is allowed
+
+if exists("b:current_syntax")
+  finish
+endif
+
+syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained
+syn region cmakeComment start="#" end="$" contains=cmakeTodo, at Spell
+syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo, at Spell
+syn region cmakeGeneratorExpression start=/$</ end=/>/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariable,cmakeProperty,cmakeGeneratorExpressions
+syn region cmakeRegistry start=/\[/ end=/]/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeEscaped
+syn region cmakeVariableValue start=/\${/ end=/}/
+            \ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariable
+syn region cmakeEnvironment start=/\$ENV{/ end=/}/
+            \ contained oneline contains=CONTAINED,cmakeTodo
+syn region cmakeString start=/"/ end=/"/
+            \ contains=CONTAINED,cmakeTodo
+syn region cmakeArguments start=/(/ end=/)/
+            \ contains=ALLBUT,cmakeArguments,cmakeTodo
+
+syn case match
+syn keyword cmakeProperty
+            \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_ [...]
+            \ contained
+
+syn keyword cmakeVariable
+            \ <PROJECT-NAME>_BINARY_DIR <PROJECT-NAME>_SOURCE_DIR <PROJECT-NAME>_VERSION <PROJECT-NAME>_VERSION_MAJOR <PROJECT-NAME>_VERSION_MINOR <PROJECT-NAME>_VERSION_PATCH <PROJECT-NAME>_VERSION_TWEAK APPLE BORLAND BUILD_SHARED_LIBS CMAKE_<CONFIG>_POSTFIX CMAKE_<LANG>_ARCHIVE_APPEND CMAKE_<LANG>_ARCHIVE_CREATE CMAKE_<LANG>_ARCHIVE_FINISH CMAKE_<LANG>_COMPILER CMAKE_<LANG>_COMPILER_ABI CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN CMAKE_<LANG>_COMPILER_ID CMAKE_<LANG>_COMPILER_LAUNCHER CMA [...]
+            \ contained
+
+syn keyword cmakeModule
+            \ ExternalProject
+            \ contained
+
+syn keyword cmakeKWExternalProject
+            \ ALGO ALWAYS BINARY_DIR BUILD_ALWAYS BUILD_BYPRODUCTS BUILD_COMMAND BUILD_IN_SOURCE BYPRODUCTS CMAKE_ARGS CMAKE_CACHE_ARGS CMAKE_CACHE_DEFAULT_ARGS COMMAND COMMENT CONFIGURE_COMMAND CVS CVSROOT CVS_ CVS_MODULE CVS_REPOSITORY CVS_TAG DEPENDEES DEPENDERS DEPENDS DIRECTORY DOWNLOAD_COMMAND DOWNLOAD_DIR DOWNLOAD_NAME DOWNLOAD_NO_PROGRESS EP_BASE EP_INDEPENDENT_STEP_TARGETS EP_PREFIX EP_STEP_TARGETS EP_UPDATE_DISCONNECTED EXCLUDE_FROM_ALL EXCLUDE_FROM_MAIN FORCE GIT_REMOTE_NAME G [...]
+            \ contained
+
+syn keyword cmakeKWadd_compile_options
+            \ COMPILE_OPTIONS
+            \ contained
+
+syn keyword cmakeKWadd_custom_command
+            \ APPEND ARGS BYPRODUCTS COMMAND COMMENT DEPENDS GENERATE GENERATED IMPLICIT_DEPENDS MAIN_DEPENDENCY NOT OUTPUT POST_BUILD PRE_BUILD PRE_LINK SYMBOLIC TARGET TARGET_FILE USES_TERMINAL VERBATIM WORKING_DIRECTORY
+            \ contained
+
+syn keyword cmakeKWadd_custom_target
+            \ ALL BYPRODUCTS COMMAND COMMENT DEPENDS GENERATE GENERATED SOURCES USES_TERMINAL VERBATIM WORKING_DIRECTORY
+            \ contained
+
+syn keyword cmakeKWadd_definitions
+            \ COMPILE_DEFINITIONS
+            \ contained
+
+syn keyword cmakeKWadd_dependencies
+            \ DEPENDS OBJECT_DEPENDS
+            \ contained
+
+syn keyword cmakeKWadd_executable
+            \ ALIAS CONFIG EXCLUDE_FROM_ALL GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ MACOSX_BUNDLE OUTPUT_NAME RUNTIME_OUTPUT_DIRECTORY TARGET
+            \ contained
+
+syn keyword cmakeKWadd_library
+            \ ALIAS ARCHIVE_OUTPUT_DIRECTORY CLI CONFIG DLL EXCLUDE_FROM_ALL FRAMEWORK GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ INTERFACE INTERFACE_ LIBRARY_OUTPUT_DIRECTORY MODULE OBJECT ON OS OUTPUT_NAME POSITION_INDEPENDENT_CODE POST_BUILD PRE_BUILD PRE_LINK RUNTIME_OUTPUT_DIRECTORY SHARED STATIC TARGET TARGET_OBJECTS UNKNOWN
+            \ contained
+
+syn keyword cmakeKWadd_subdirectory
+            \ ALL EXCLUDE_FROM_ALL
+            \ contained
+
+syn keyword cmakeKWadd_test
+            \ BUILD_TESTING COMMAND CONFIGURATION CONFIGURATIONS FAIL_REGULAR_EXPRESSION NAME ON PASS_REGULAR_EXPRESSION TARGET_FILE WILL_FAIL WORKING_DIRECTORY
+            \ contained
+
+syn keyword cmakeKWbuild_command
+            \ CONFIGURATION NEW TARGET
+            \ contained
+
+syn keyword cmakeKWbuild_name
+            \ CMAKE_CXX_COMPILER
+            \ contained
+
+syn keyword cmakeKWcmake_host_system_information
+            \ AVAILABLE_PHYSICAL_MEMORY AVAILABLE_VIRTUAL_MEMORY FQDN HOSTNAME NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES QUERY RESULT TOTAL_PHYSICAL_MEMORY TOTAL_VIRTUAL_MEMORY
+            \ contained
+
+syn keyword cmakeKWcmake_minimum_required
+            \ FATAL_ERROR VERSION
+            \ contained
+
+syn keyword cmakeKWcmake_parse_arguments
+            \ ARGN CONFIGURATIONS DESTINATION FALSE FAST FILES MY_INSTALL MY_INSTALL_CONFIGURATIONS MY_INSTALL_DESTINATION MY_INSTALL_FAST MY_INSTALL_OPTIONAL MY_INSTALL_RENAME MY_INSTALL_TARGETS MY_INSTALL_UNPARSED_ARGUMENTS OPTIONAL RENAME TARGETS TRUE _UNPARSED_ARGUMENTS
+            \ contained
+
+syn keyword cmakeKWcmake_policy
+            \ CMAKE_POLICY_DEFAULT_CMP CMP GET NEW NNNN NO_POLICY_SCOPE OLD POP PUSH SET VERSION
+            \ contained
+
+syn keyword cmakeKWconfigure_file
+            \ COPYONLY CRLF DOS ESCAPE_QUOTES FOO_ENABLE FOO_STRING LF NEWLINE_STYLE ON ONLY VAR
+            \ contained
+
+syn keyword cmakeKWcreate_test_sourcelist
+            \ CMAKE_TESTDRIVER_AFTER_TESTMAIN CMAKE_TESTDRIVER_BEFORE_TESTMAIN EXTRA_INCLUDE FUNCTION
+            \ contained
+
+syn keyword cmakeKWctest_build
+            \ ALL_BUILD APPEND BUILD CONFIGURATION CTEST_BUILD_CONFIGURATION CTEST_BUILD_FLAGS CTEST_BUILD_TARGET CTEST_PROJECT_NAME FLAGS NUMBER_ERRORS NUMBER_WARNINGS QUIET RETURN_VALUE TARGET
+            \ contained
+
+syn keyword cmakeKWctest_configure
+            \ APPEND BUILD OPTIONS QUIET RETURN_VALUE SOURCE
+            \ contained
+
+syn keyword cmakeKWctest_coverage
+            \ APPEND BUILD LABELS QUIET RETURN_VALUE
+            \ contained
+
+syn keyword cmakeKWctest_memcheck
+            \ APPEND BUILD END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+            \ contained
+
+syn keyword cmakeKWctest_run_script
+            \ NEW_PROCESS RETURN_VALUE
+            \ contained
+
+syn keyword cmakeKWctest_start
+            \ APPEND QUIET TAG TRACK
+            \ contained
+
+syn keyword cmakeKWctest_submit
+            \ API CDASH_UPLOAD CDASH_UPLOAD_TYPE CTEST_EXTRA_SUBMIT_FILES CTEST_NOTES_FILES FILES PARTS QUIET RETRY_COUNT RETRY_DELAY RETURN_VALUE
+            \ contained
+
+syn keyword cmakeKWctest_test
+            \ APPEND BUILD CPU END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+            \ contained
+
+syn keyword cmakeKWctest_update
+            \ QUIET RETURN_VALUE SOURCE
+            \ contained
+
+syn keyword cmakeKWctest_upload
+            \ FILES QUIET
+            \ contained
+
+syn keyword cmakeKWdefine_property
+            \ BRIEF_DOCS CACHED_VARIABLE DIRECTORY FULL_DOCS GLOBAL INHERITED PROPERTY SOURCE TARGET TEST VARIABLE
+            \ contained
+
+syn keyword cmakeKWenable_language
+            \ OPTIONAL
+            \ contained
+
+syn keyword cmakeKWexec_program
+            \ ARGS OUTPUT_VARIABLE RETURN_VALUE
+            \ contained
+
+syn keyword cmakeKWexecute_process
+            \ COMMAND ERROR_ ERROR_FILE ERROR_QUIET ERROR_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE INPUT_ INPUT_FILE OUTPUT_ OUTPUT_FILE OUTPUT_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE RESULT_VARIABLE TIMEOUT VERBATIM WORKING_DIRECTORY
+            \ contained
+
+syn keyword cmakeKWexport
+            \ APPEND CONFIG EXPORT EXPORT_LINK_INTERFACE_LIBRARIES FILE IMPORTED IMPORTED_ LINK_INTERFACE_LIBRARIES NAMESPACE NEW PACKAGE TARGETS
+            \ contained
+
+syn keyword cmakeKWexport_library_dependencies
+            \ APPEND EXPORT INCLUDE LINK_INTERFACE_LIBRARIES SET
+            \ contained
+
+syn keyword cmakeKWfile
+            \ ALGO APPEND ASCII CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY CONDITION CONFIG CONTENT COPY CR DESTINATION DIRECTORY DIRECTORY_PERMISSIONS DOWNLOAD ENCODING EXCLUDE EXPECTED_HASH FILE FILES_MATCHING FILE_PERMISSIONS FOLLOW_SYMLINKS FUNCTION GENERATE GLOB GLOB_RECURSE GUARD HEX INACTIVITY_TIMEOUT INPUT INSTALL LENGTH_MAXIMUM LENGTH_MINIMUM LF LIMIT LIMIT_COUNT LIMIT_INPUT LIMIT_OUTPUT LIST_DIRECTORIES LOCK LOG MAKE_DIRECTORY NEW NEWLINE_CONSUME NO_HEX_CONVERSION NO_SOURCE_PERMISSIONS  [...]
+            \ contained
+
+syn keyword cmakeKWfind_file
+            \ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS INCLUDE NAMES NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATH PATHS PATH_SUFFIXES VAR
+            \ contained
+
+syn keyword cmakeKWfind_library
+            \ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS LIB NAMES NAMES_PER_DIR NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATH PATHS PATH_SUFFIXES VAR
+            \ contained
+
+syn keyword cmakeKWfind_package
+            \ CMAKE_DISABLE_FIND_PACKAGE_ CMAKE_FIND_ROOT_PATH_BOTH COMPONENTS CONFIG CONFIGS DVAR EXACT HINTS MODULE NAMES NO_CMAKE_BUILDS_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PACKAGE_REGISTRY NO_CMAKE_PATH NO_CMAKE_SYSTEM_PACKAGE_REGISTRY NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_MODULE NO_POLICY_SCOPE NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OPTIONAL_COMPONENTS OS PACKAGE_FIND_NAME PACKAGE_FIND_VERSION PACKAGE_FIND_VERSION_COUNT PACKAGE_FIND_VERSIO [...]
+            \ contained
+
+syn keyword cmakeKWfind_path
+            \ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS INCLUDE NAMES NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATH PATHS PATH_SUFFIXES VAR
+            \ contained
+
+syn keyword cmakeKWfind_program
+            \ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS NAMES NAMES_PER_DIR NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATH PATHS PATH_SUFFIXES VAR
+            \ contained
+
+syn keyword cmakeKWfltk_wrap_ui
+            \ FLTK
+            \ contained
+
+syn keyword cmakeKWforeach
+            \ ARGS IN ITEMS LISTS RANGE
+            \ contained
+
+syn keyword cmakeKWfunction
+            \ ARGC ARGN ARGS ARGV PARENT_SCOPE
+            \ contained
+
+syn keyword cmakeKWget_cmake_property
+            \ VAR
+            \ contained
+
+syn keyword cmakeKWget_directory_property
+            \ DEFINITION DIRECTORY
+            \ contained
+
+syn keyword cmakeKWget_filename_component
+            \ ABSOLUTE ARG_VAR BASE_DIR CACHE COMP DIRECTORY EXT NAME NAME_WE PATH PROGRAM PROGRAM_ARGS REALPATH VAR
+            \ contained
+
+syn keyword cmakeKWget_property
+            \ BRIEF_DOCS CACHE DEFINED DIRECTORY FULL_DOCS GLOBAL INSTALL PROPERTY SET SOURCE TARGET TEST VARIABLE
+            \ contained
+
+syn keyword cmakeKWget_source_file_property
+            \ LOCATION VAR
+            \ contained
+
+syn keyword cmakeKWget_target_property
+            \ VAR
+            \ contained
+
+syn keyword cmakeKWget_test_property
+            \ VAR
+            \ contained
+
+syn keyword cmakeKWif
+            \ AND ARGS CMP COMMAND DEFINED EQUAL EXISTS FALSE GREATER IGNORE IN_LIST IS_ABSOLUTE IS_DIRECTORY IS_NEWER_THAN IS_SYMLINK LESS MATCHES NNNN NO NOT OFF ON OR POLICY STREQUAL STRGREATER STRLESS TARGET TEST THEN TRUE VERSION_EQUAL VERSION_GREATER VERSION_LESS YES
+            \ contained
+
+syn keyword cmakeKWinclude
+            \ NO_POLICY_SCOPE OPTIONAL RESULT_VARIABLE VAR
+            \ contained
+
+syn keyword cmakeKWinclude_directories
+            \ AFTER BEFORE INCLUDE_DIRECTORIES ON SYSTEM
+            \ contained
+
+syn keyword cmakeKWinclude_external_msproject
+            \ GUID PLATFORM TYPE WIX
+            \ contained
+
+syn keyword cmakeKWinstall
+            \ ARCHIVE BUNDLE CODE COMPONENT CONFIG CONFIGURATIONS CVS DESTDIR DESTINATION DIRECTORY DIRECTORY_PERMISSIONS DLL EXCLUDE EXCLUDE_FROM_ALL EXPORT EXPORT_LINK_INTERFACE_LIBRARIES FILE FILES FILES_MATCHING FILE_PERMISSIONS FRAMEWORK GROUP_EXECUTE GROUP_READ GROUP_WRITE IMPORTED_ INCLUDES INSTALL_PREFIX INTERFACE_INCLUDE_DIRECTORIES LIBRARY LINK_INTERFACE_LIBRARIES MACOSX_BUNDLE MESSAGE MESSAGE_NEVER NAMELINK_ONLY NAMELINK_SKIP NAMESPACE NEW OPTIONAL OS OWNER_EXECUTE OWNER_READ  [...]
+            \ contained
+
+syn keyword cmakeKWinstall_files
+            \ FILES GLOB
+            \ contained
+
+syn keyword cmakeKWinstall_programs
+            \ FILES GLOB PROGRAMS TARGETS
+            \ contained
+
+syn keyword cmakeKWinstall_targets
+            \ DLL RUNTIME_DIRECTORY TARGETS
+            \ contained
+
+syn keyword cmakeKWlist
+            \ APPEND CACHE FIND GET INSERT INTERNAL LENGTH LIST NOTES PARENT_SCOPE REMOVE_AT REMOVE_DUPLICATES REMOVE_ITEM REVERSE SORT
+            \ contained
+
+syn keyword cmakeKWload_cache
+            \ EXCLUDE INCLUDE_INTERNALS READ_WITH_PREFIX
+            \ contained
+
+syn keyword cmakeKWload_command
+            \ CMAKE_LOADED_COMMAND_ COMMAND_NAME
+            \ contained
+
+syn keyword cmakeKWmacro
+            \ ARGC ARGN ARGS ARGV DEFINED GREATER IN LISTS NOT _BAR _FOO
+            \ contained
+
+syn keyword cmakeKWmake_directory
+            \ MAKE_DIRECTORY
+            \ contained
+
+syn keyword cmakeKWmark_as_advanced
+            \ CLEAR FORCE VAR
+            \ contained
+
+syn keyword cmakeKWmath
+            \ EXPR
+            \ contained
+
+syn keyword cmakeKWmessage
+            \ AUTHOR_WARNING DEPRECATION FATAL_ERROR GUI SEND_ERROR STATUS WARNING
+            \ contained
+
+syn keyword cmakeKWoption
+            \ OFF ON
+            \ contained
+
+syn keyword cmakeKWproject
+            \ CMAKE_PROJECT_ LANGUAGES NAME NEW NONE PROJECT VERSION _BINARY_DIR _INCLUDE _SOURCE_DIR _VERSION _VERSION_MAJOR _VERSION_MINOR _VERSION_PATCH _VERSION_TWEAK
+            \ contained
+
+syn keyword cmakeKWremove
+            \ REMOVE_ITEM VALUE VAR
+            \ contained
+
+syn keyword cmakeKWseparate_arguments
+            \ MSDN UNIX_COMMAND VARIABLE WINDOWS WINDOWS_COMMAND _COMMAND
+            \ contained
+
+syn keyword cmakeKWset
+            \ BOOL CACHE FILEPATH FORCE INTERNAL OFF ON PARENT_SCOPE PATH STRING STRINGS
+            \ contained
+
+syn keyword cmakeKWset_directory_properties
+            \ PROPERTIES
+            \ contained
+
+syn keyword cmakeKWset_property
+            \ APPEND APPEND_STRING CACHE DIRECTORY GLOBAL INSTALL PROPERTY SOURCE TARGET TEST WIX
+            \ contained
+
+syn keyword cmakeKWset_source_files_properties
+            \ PROPERTIES
+            \ contained
+
+syn keyword cmakeKWset_target_properties
+            \ PROPERTIES
+            \ contained
+
+syn keyword cmakeKWset_tests_properties
+            \ PROPERTIES
+            \ contained
+
+syn keyword cmakeKWsource_group
+            \ FILES REGULAR_EXPRESSION
+            \ contained
+
+syn keyword cmakeKWstring
+            \ ALPHABET APPEND ASCII CMAKE_MATCH_ COMPARE CONCAT CONFIGURE EQUAL ESCAPE_QUOTES FIND GENEX_STRIP GREATER GUID LENGTH LESS MAKE_C_IDENTIFIER MATCH MATCHALL MATCHES NAME NAMESPACE NOTEQUAL ONLY RANDOM RANDOM_SEED REGEX REPLACE REVERSE STRIP SUBSTRING SZ TIMESTAMP TOLOWER TOUPPER TYPE UPPER UTC UUID
+            \ contained
+
+syn keyword cmakeKWsubdirs
+            \ EXCLUDE_FROM_ALL PREORDER
+            \ contained
+
+syn keyword cmakeKWtarget_compile_definitions
+            \ COMPILE_DEFINITIONS INTERFACE INTERFACE_COMPILE_DEFINITIONS PRIVATE PUBLIC
+            \ contained
+
+syn keyword cmakeKWtarget_compile_features
+            \ COMPILE_FEATURES IMPORTED INTERFACE INTERFACE_COMPILE_FEATURES PRIVATE PUBLIC
+            \ contained
+
+syn keyword cmakeKWtarget_compile_options
+            \ BEFORE COMPILE_OPTIONS IMPORTED INTERFACE INTERFACE_COMPILE_OPTIONS PRIVATE PUBLIC
+            \ contained
+
+syn keyword cmakeKWtarget_include_directories
+            \ BEFORE BUILD_INTERFACE IMPORTED INCLUDE_DIRECTORIES INSTALL_INTERFACE INTERFACE INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES PRIVATE PUBLIC SYSTEM
+            \ contained
+
+syn keyword cmakeKWtarget_link_libraries
+            \ ALIAS DAG DEBUG_CONFIGURATIONS IMPORTED IMPORTED_NO_SONAME INTERFACE INTERFACE_LINK_LIBRARIES LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_MULTIPLICITY LINK_PRIVATE LINK_PUBLIC NEW OLD OSX PRIVATE PUBLIC SONAME STATIC
+            \ contained
+
+syn keyword cmakeKWtarget_sources
+            \ IMPORTED INTERFACE INTERFACE_SOURCES PRIVATE PUBLIC SOURCES
+            \ contained
+
+syn keyword cmakeKWtry_compile
+            \ ALL_BUILD CMAKE_FLAGS COMPILE_DEFINITIONS COPY_FILE COPY_FILE_ERROR DEFINED DLINK_LIBRARIES DVAR FALSE INCLUDE_DIRECTORIES LINK_DIRECTORIES LINK_LIBRARIES NEW NOT OUTPUT_VARIABLE RESULT_VAR SOURCES TRUE TYPE VALUE
+            \ contained
+
+syn keyword cmakeKWtry_run
+            \ ARGS CMAKE_FLAGS COMPILE_DEFINITIONS COMPILE_OUTPUT_VARIABLE COMPILE_RESULT_VAR DLINK_LIBRARIES DVAR FAILED_TO_RUN FALSE INCLUDE_DIRECTORIES LINK_DIRECTORIES LINK_LIBRARIES OUTPUT_VARIABLE RUN_OUTPUT_VARIABLE RUN_RESULT_VAR TRUE TYPE VALUE __TRYRUN_OUTPUT
+            \ contained
+
+syn keyword cmakeKWunset
+            \ CACHE LD_LIBRARY_PATH PARENT_SCOPE
+            \ contained
+
+syn keyword cmakeKWuse_mangled_mesa
+            \ GL OUTPUT_DIRECTORY PATH_TO_MESA
+            \ contained
+
+syn keyword cmakeKWvariable_requires
+            \ RESULT_VARIABLE TEST_VARIABLE
+            \ contained
+
+syn keyword cmakeKWvariable_watch
+            \ COMMAND
+            \ contained
+
+syn keyword cmakeKWwhile
+            \ ARGS
+            \ contained
+
+syn keyword cmakeKWwrite_file
+            \ APPEND CONFIGURE_FILE NOTE WRITE
+            \ contained
+
+
+syn keyword cmakeGeneratorExpressions
+            \ LINK_LIBRARIES INCLUDE_DIRECTORIES COMPILE_DEFINITIONS CONFIG DEBUG_MODE DEBUG_MODE BOOL AND OR NOT STREQUAL STREQUAL EQUAL EQUAL CONFIG MAP_IMPORTED_CONFIG_ CONFIG IMPORTED PLATFORM_ID C_COMPILER_ID CXX_COMPILER_ID VERSION_GREATER VERSION_LESS VERSION_EQUAL C_COMPILER_VERSION CXX_COMPILER_VERSION TARGET_POLICY NEW COMPILE_FEATURES C_STANDARD CXX_STANDARD COMPILE_LANGUAGE PRIVATE COMPILE_LANGUAGE PUBLIC PRIVATE COMPILE_LANGUAGE COMPILING_CXX PRIVATE COMPILE_LANGUAGE CXX_COM [...]
+            \ contained
+
+syn case ignore
+syn keyword cmakeCommand
+            \ add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_subdirectory add_test aux_source_directory break build_command cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue create_test_sourcelist ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_s [...]
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandConditional
+            \ else elseif endif if
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandRepeat
+            \ endforeach endwhile foreach while
+            \ nextgroup=cmakeArguments
+syn keyword cmakeCommandDeprecated
+            \ build_name exec_program export_library_dependencies install_files install_programs install_targets link_libraries make_directory output_required_files remove subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file
+            \ nextgroup=cmakeArguments
+syn case match
+
+syn keyword cmakeTodo
+            \ TODO FIXME XXX
+            \ contained
+
+hi def link cmakeCommand Function
+hi def link cmakeCommandConditional Conditional
+hi def link cmakeCommandDeprecated WarningMsg
+hi def link cmakeCommandRepeat Repeat
+hi def link cmakeComment Comment
+hi def link cmakeEnvironment Special
+hi def link cmakeEscaped Special
+hi def link cmakeGeneratorExpression WarningMsg
+hi def link cmakeGeneratorExpressions ModeMsg
+hi def link cmakeLuaComment Comment
+hi def link cmakeModule Include
+hi def link cmakeProperty Constant
+hi def link cmakeRegistry Underlined
+hi def link cmakeString String
+hi def link cmakeTodo TODO
+hi def link cmakeVariable Identifier
+hi def link cmakeVariableValue Type
+
+hi def link cmakeKWExternalProject ModeMsg
+hi def link cmakeKWadd_compile_options ModeMsg
+hi def link cmakeKWadd_custom_command ModeMsg
+hi def link cmakeKWadd_custom_target ModeMsg
+hi def link cmakeKWadd_definitions ModeMsg
+hi def link cmakeKWadd_dependencies ModeMsg
+hi def link cmakeKWadd_executable ModeMsg
+hi def link cmakeKWadd_library ModeMsg
+hi def link cmakeKWadd_subdirectory ModeMsg
+hi def link cmakeKWadd_test ModeMsg
+hi def link cmakeKWbuild_command ModeMsg
+hi def link cmakeKWbuild_name ModeMsg
+hi def link cmakeKWcmake_host_system_information ModeMsg
+hi def link cmakeKWcmake_minimum_required ModeMsg
+hi def link cmakeKWcmake_parse_arguments ModeMsg
+hi def link cmakeKWcmake_policy ModeMsg
+hi def link cmakeKWconfigure_file ModeMsg
+hi def link cmakeKWcreate_test_sourcelist ModeMsg
+hi def link cmakeKWctest_build ModeMsg
+hi def link cmakeKWctest_configure ModeMsg
+hi def link cmakeKWctest_coverage ModeMsg
+hi def link cmakeKWctest_memcheck ModeMsg
+hi def link cmakeKWctest_run_script ModeMsg
+hi def link cmakeKWctest_start ModeMsg
+hi def link cmakeKWctest_submit ModeMsg
+hi def link cmakeKWctest_test ModeMsg
+hi def link cmakeKWctest_update ModeMsg
+hi def link cmakeKWctest_upload ModeMsg
+hi def link cmakeKWdefine_property ModeMsg
+hi def link cmakeKWenable_language ModeMsg
+hi def link cmakeKWexec_program ModeMsg
+hi def link cmakeKWexecute_process ModeMsg
+hi def link cmakeKWexport ModeMsg
+hi def link cmakeKWexport_library_dependencies ModeMsg
+hi def link cmakeKWfile ModeMsg
+hi def link cmakeKWfind_file ModeMsg
+hi def link cmakeKWfind_library ModeMsg
+hi def link cmakeKWfind_package ModeMsg
+hi def link cmakeKWfind_path ModeMsg
+hi def link cmakeKWfind_program ModeMsg
+hi def link cmakeKWfltk_wrap_ui ModeMsg
+hi def link cmakeKWforeach ModeMsg
+hi def link cmakeKWfunction ModeMsg
+hi def link cmakeKWget_cmake_property ModeMsg
+hi def link cmakeKWget_directory_property ModeMsg
+hi def link cmakeKWget_filename_component ModeMsg
+hi def link cmakeKWget_property ModeMsg
+hi def link cmakeKWget_source_file_property ModeMsg
+hi def link cmakeKWget_target_property ModeMsg
+hi def link cmakeKWget_test_property ModeMsg
+hi def link cmakeKWif ModeMsg
+hi def link cmakeKWinclude ModeMsg
+hi def link cmakeKWinclude_directories ModeMsg
+hi def link cmakeKWinclude_external_msproject ModeMsg
+hi def link cmakeKWinstall ModeMsg
+hi def link cmakeKWinstall_files ModeMsg
+hi def link cmakeKWinstall_programs ModeMsg
+hi def link cmakeKWinstall_targets ModeMsg
+hi def link cmakeKWlist ModeMsg
+hi def link cmakeKWload_cache ModeMsg
+hi def link cmakeKWload_command ModeMsg
+hi def link cmakeKWmacro ModeMsg
+hi def link cmakeKWmake_directory ModeMsg
+hi def link cmakeKWmark_as_advanced ModeMsg
+hi def link cmakeKWmath ModeMsg
+hi def link cmakeKWmessage ModeMsg
+hi def link cmakeKWoption ModeMsg
+hi def link cmakeKWproject ModeMsg
+hi def link cmakeKWremove ModeMsg
+hi def link cmakeKWseparate_arguments ModeMsg
+hi def link cmakeKWset ModeMsg
+hi def link cmakeKWset_directory_properties ModeMsg
+hi def link cmakeKWset_property ModeMsg
+hi def link cmakeKWset_source_files_properties ModeMsg
+hi def link cmakeKWset_target_properties ModeMsg
+hi def link cmakeKWset_tests_properties ModeMsg
+hi def link cmakeKWsource_group ModeMsg
+hi def link cmakeKWstring ModeMsg
+hi def link cmakeKWsubdirs ModeMsg
+hi def link cmakeKWtarget_compile_definitions ModeMsg
+hi def link cmakeKWtarget_compile_features ModeMsg
+hi def link cmakeKWtarget_compile_options ModeMsg
+hi def link cmakeKWtarget_include_directories ModeMsg
+hi def link cmakeKWtarget_link_libraries ModeMsg
+hi def link cmakeKWtarget_sources ModeMsg
+hi def link cmakeKWtry_compile ModeMsg
+hi def link cmakeKWtry_run ModeMsg
+hi def link cmakeKWunset ModeMsg
+hi def link cmakeKWuse_mangled_mesa ModeMsg
+hi def link cmakeKWvariable_requires ModeMsg
+hi def link cmakeKWvariable_watch ModeMsg
+hi def link cmakeKWwhile ModeMsg
+hi def link cmakeKWwrite_file ModeMsg
+
+let b:current_syntax = "cmake"
diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake
index 3203279..1889be2 100644
--- a/CMakeCPack.cmake
+++ b/CMakeCPack.cmake
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 # If the cmake version includes cpack, use it
 if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
@@ -70,6 +61,9 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
   # Components
   if(CMake_INSTALL_COMPONENTS)
     set(_CPACK_IFW_COMPONENTS_ALL cmake ctest cpack)
+    if(WIN32 AND NOT CYGWIN)
+        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmcldeps)
+    endif()
     if(APPLE)
       list(APPEND _CPACK_IFW_COMPONENTS_ALL cmakexbuild)
     endif()
@@ -87,8 +81,10 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
     endif()
     if(BUILD_QtDialog)
       list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-gui)
-      set(_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES "set(CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES
-    \"LGPLv2.1\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv2.1.txt\")")
+      if(USE_LGPL)
+        set(_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES "set(CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES
+    \"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\")")
+      endif()
     endif()
     if(SPHINX_MAN)
       list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-man)
@@ -102,22 +98,31 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
     if(SPHINX_QTHELP)
       list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-qthelp)
     endif()
+    if(CMake_BUILD_DEVELOPER_REFERENCE)
+      if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-html)
+      endif()
+      if(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
+        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-qthelp)
+      endif()
+    endif()
     set(_CPACK_IFW_COMPONENTS_CONFIGURATION "
   # Components
   set(CPACK_COMPONENTS_ALL \"${_CPACK_IFW_COMPONENTS_ALL}\")
   set(CPACK_COMPONENTS_GROUPING IGNORE)
 ")
   else()
-    if(BUILD_QtDialog AND CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL)
+    if(BUILD_QtDialog AND USE_LGPL)
       set(_CPACK_IFW_ADDITIONAL_LICENSES
-        "\"LGPLv2.1\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv2.1.txt\"")
+        "\"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\"")
     endif()
   endif()
 
   # Components scripts configuration
   foreach(_script
     CMake
-    CMake.Documentation.SphinxHTML)
+    CMake.Documentation.SphinxHTML
+    CMake.DeveloperReference.HTML)
     configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/${_script}.qs.in"
       "${CMake_BINARY_DIR}/${_script}.qs" @ONLY)
   endforeach()
@@ -131,6 +136,11 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
     if(SPHINX_HTML)
       set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/html/index.html\", \"@StartMenuDir@/CMake Documentation.lnk\");\n")
     endif()
+    if(CMake_BUILD_DEVELOPER_REFERENCE)
+      if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+      set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/developer-reference/html/index.html\", \"@StartMenuDir@/CMake Developer Reference.lnk\");\n")
+      endif()
+    endif()
     configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/installscript.qs.in"
       "${CMake_BINARY_DIR}/installscript.qs" @ONLY
     )
@@ -166,36 +176,11 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
   set(CPACK_PACKAGE_CONTACT "cmake at cmake.org")
 
   if(UNIX)
-    set(CPACK_STRIP_FILES "bin/ccmake;bin/cmake;bin/cpack;bin/ctest")
+    set(CPACK_STRIP_FILES "${CMAKE_BIN_DIR}/ccmake;${CMAKE_BIN_DIR}/cmake;${CMAKE_BIN_DIR}/cpack;${CMAKE_BIN_DIR}/ctest")
     set(CPACK_SOURCE_STRIP_FILES "")
     set(CPACK_PACKAGE_EXECUTABLES "ccmake" "CMake")
   endif()
 
-  # cygwin specific packaging stuff
-  if(CYGWIN)
-    # setup the cygwin package name
-    set(CPACK_PACKAGE_NAME cmake)
-    # setup the name of the package for cygwin cmake-2.4.3
-    set(CPACK_PACKAGE_FILE_NAME
-      "${CPACK_PACKAGE_NAME}-${CMake_VERSION}")
-    # the source has the same name as the binary
-    set(CPACK_SOURCE_PACKAGE_FILE_NAME ${CPACK_PACKAGE_FILE_NAME})
-    # Create a cygwin version number in case there are changes for cygwin
-    # that are not reflected upstream in CMake
-    set(CPACK_CYGWIN_PATCH_NUMBER 1 CACHE STRING "patch number for CMake cygwin packages")
-    mark_as_advanced(CPACK_CYGWIN_PATCH_NUMBER)
-    # These files are required by the cmCPackCygwinSourceGenerator and the files
-    # put into the release tar files.
-    set(CPACK_CYGWIN_BUILD_SCRIPT
-      "${CMake_BINARY_DIR}/${CPACK_PACKAGE_FILE_NAME}-${CPACK_CYGWIN_PATCH_NUMBER}.sh")
-    set(CPACK_CYGWIN_PATCH_FILE
-      "${CMake_BINARY_DIR}/${CPACK_PACKAGE_FILE_NAME}-${CPACK_CYGWIN_PATCH_NUMBER}.patch")
-    # include the sub directory cmake file for cygwin that
-    # configures some files and adds some install targets
-    # this file uses some of the package file name variables
-    include(Utilities/Release/Cygwin/CMakeLists.txt)
-  endif()
-
   set(CPACK_WIX_UPGRADE_GUID "8ffd1d72-b7f1-11e2-8ee5-00238bca4991")
 
   if(MSVC AND NOT "$ENV{WIX}" STREQUAL "")
diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in
index 59ae224..d7a33bc 100644
--- a/CMakeCPackOptions.cmake.in
+++ b/CMakeCPackOptions.cmake.in
@@ -102,13 +102,21 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_IFW_COMPONENT_CPACK_PRIORITY 87)
   set(CPACK_IFW_COMPONENT_CPACK_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
 
+  set(CPACK_COMPONENT_CMCLDEPS_DISPLAY_NAME "cmcldeps")
+  set(CPACK_COMPONENT_CMCLDEPS_DESCRIPTION
+    "The \"cmcldeps\" executable is wrapper around \"cl\" program")
+  set(CPACK_COMPONENT_CMCLDEPS_GROUP Tools)
+  set(CPACK_IFW_COMPONENT_CMCLDEPS_NAME "CMClDeps")
+  set(CPACK_IFW_COMPONENT_CMCLDEPS_PRIORITY 86)
+  set(CPACK_IFW_COMPONENT_CMCLDEPS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+
   set(CPACK_COMPONENT_CMAKEXBUILD_DISPLAY_NAME "cmakexbuild")
   set(CPACK_COMPONENT_CMAKEXBUILD_DESCRIPTION
     "The \"cmakexbuild\" executable is a wrapper program for \"xcodebuild\"")
   set(CPACK_COMPONENT_CMAKEXBUILD_REQUIRED TRUE)
   set(CPACK_COMPONENT_CMAKEXBUILD_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CMAKEXBUILD_NAME "CMakeXBuild")
-  set(CPACK_IFW_COMPONENT_CMAKEXBUILD_PRIORITY 86)
+  set(CPACK_IFW_COMPONENT_CMAKEXBUILD_PRIORITY 85)
   set(CPACK_IFW_COMPONENT_CMAKEXBUILD_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
 
   # Dialogs
@@ -167,6 +175,29 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_NAME "SphinxQtHelp")
   set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
 
+  # Developer Reference
+  set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_DISPLAY_NAME "Developer Reference")
+  set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_DESCRIPTION
+    "CMake Reference in different formats (html, qch)")
+  set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_PARENT_GROUP CMake)
+  set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_PRIORITY 50)
+  set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_VERSION
+    "@_CPACK_IFW_PACKAGE_VERSION@")
+
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_DISPLAY_NAME "HTML")
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_GROUP DeveloperReference)
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_DISABLED TRUE)
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_NAME "HTML")
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_SCRIPT
+    "@CMake_BINARY_DIR@/CMake.DeveloperReference.HTML.qs")
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISPLAY_NAME "Qt Compressed Help")
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_GROUP DeveloperReference)
+  set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISABLED TRUE)
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_NAME "QtHelp")
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+
 endif()
 
 if(CPACK_GENERATOR MATCHES "CygwinSource")
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 787f319..b4a577c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,15 +1,7 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-cmake_minimum_required(VERSION 2.8.4 FATAL_ERROR)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
 if(POLICY CMP0025)
   cmake_policy(SET CMP0025 NEW)
 endif()
@@ -18,6 +10,10 @@ if(POLICY CMP0053)
 endif()
 project(CMake)
 
+# Make sure we can find internal find_package modules only used for
+# building CMake and not for shipping externally
+list(INSERT CMAKE_MODULE_PATH 0 ${CMake_SOURCE_DIR}/Source/Modules)
+
 if(CMAKE_BOOTSTRAP)
   # Running from bootstrap script.  Set local variable and remove from cache.
   set(CMAKE_BOOTSTRAP 1)
@@ -28,6 +24,16 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
   set(CMake_BIN_DIR ${CMake_BINARY_DIR}/bin)
 endif()
 
+if(CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL)
+  if(CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL MATCHES "^3|2\\.1$")
+    set(USE_LGPL "${CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL}")
+  else()
+    set(USE_LGPL "2.1")
+  endif()
+else()
+  set(USE_LGPL "")
+endif()
+
 if("${CMake_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}")
   # Disallow architecture-specific try_run.  It may not run on the host.
   macro(TRY_RUN)
@@ -57,7 +63,7 @@ if(NOT DEFINED CMAKE_CXX_STANDARD AND NOT CMake_NO_CXX_STANDARD)
   endif()
 endif()
 if(NOT CMake_TEST_EXTERNAL_CMAKE)
-  include(${CMake_SOURCE_DIR}/Source/Checks/cm_cxx11_unordered_map.cmake)
+  include(${CMake_SOURCE_DIR}/Source/Checks/cm_cxx_features.cmake)
 endif()
 
 # option to set the internal encoding of CMake to UTF-8
@@ -83,6 +89,11 @@ option(CMake_INSTALL_DEPENDENCIES
   "Whether to install 3rd-party runtime dependencies" OFF)
 mark_as_advanced(CMake_INSTALL_DEPENDENCIES)
 
+# option to build reference for CMake developers
+option(CMake_BUILD_DEVELOPER_REFERENCE
+  "Build CMake Developer Reference" OFF)
+mark_as_advanced(CMake_BUILD_DEVELOPER_REFERENCE)
+
 #-----------------------------------------------------------------------
 # a macro to deal with system libraries, implemented as a macro
 # simply to improve readability of the main script
@@ -97,7 +108,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
 
   # Allow the user to enable/disable all system utility library options by
   # defining CMAKE_USE_SYSTEM_LIBRARIES or CMAKE_USE_SYSTEM_LIBRARY_${util}.
-  set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA ZLIB)
+  set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBUV ZLIB)
   foreach(util ${UTILITIES})
     if(NOT DEFINED CMAKE_USE_SYSTEM_LIBRARY_${util}
         AND DEFINED CMAKE_USE_SYSTEM_LIBRARIES)
@@ -137,6 +148,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
     "${CMAKE_USE_SYSTEM_LIBRARY_LIBLZMA}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
   option(CMAKE_USE_SYSTEM_FORM "Use system-installed libform" "${CMAKE_USE_SYSTEM_LIBRARY_FORM}")
   option(CMAKE_USE_SYSTEM_JSONCPP "Use system-installed jsoncpp" "${CMAKE_USE_SYSTEM_LIBRARY_JSONCPP}")
+  option(CMAKE_USE_SYSTEM_LIBUV "Use system-installed libuv" "${CMAKE_USE_SYSTEM_LIBRARY_LIBUV}")
 
   # For now use system KWIML only if explicitly requested rather
   # than activating via the general system libs options.
@@ -433,7 +445,7 @@ macro (CMAKE_BUILD_UTILITIES)
   # Build jsoncpp library.
   if(CMAKE_USE_SYSTEM_JSONCPP)
     if(NOT CMAKE_VERSION VERSION_LESS 3.0)
-      include(${CMake_SOURCE_DIR}/Source/Modules/FindJsonCpp.cmake)
+      find_package(JsonCpp)
     else()
       message(FATAL_ERROR "CMAKE_USE_SYSTEM_JSONCPP requires CMake >= 3.0")
     endif()
@@ -449,6 +461,55 @@ macro (CMAKE_BUILD_UTILITIES)
   endif()
 
   #---------------------------------------------------------------------
+  # Build libuv library.
+  if(NOT DEFINED CMAKE_USE_LIBUV)
+    set(CMAKE_USE_LIBUV 1)
+    if(APPLE)
+      include(CheckCSourceCompiles)
+      check_c_source_compiles("
+#include <CoreServices/CoreServices.h>
+#include <AvailabilityMacros.h>
+#ifndef MAC_OS_X_VERSION_10_5
+#error \"MAC_OS_X_VERSION_10_5 is not defined\"
+#endif
+int main(void) { return 0; }
+" HAVE_CoreServices_OS_X_10_5)
+      if(NOT HAVE_CoreServices_OS_X_10_5)
+        set(CMAKE_USE_LIBUV 0)
+      endif()
+    elseif(CYGWIN)
+      # libuv does not support Cygwin
+      set(CMAKE_USE_LIBUV 0)
+    elseif(CMAKE_SYSTEM_NAME STREQUAL "HP-UX")
+      # Disable until it can be ported.
+      set(CMAKE_USE_LIBUV 0)
+    elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "sparc")
+      # Disable until it can be ported.
+      set(CMAKE_USE_LIBUV 0)
+    endif()
+  endif()
+  if(CMAKE_USE_LIBUV)
+    if(CMAKE_USE_SYSTEM_LIBUV)
+      if(NOT CMAKE_VERSION VERSION_LESS 3.0)
+        find_package(LibUV 1.0.0)
+      else()
+        message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBUV requires CMake >= 3.0")
+      endif()
+      if(NOT LIBUV_FOUND)
+        message(FATAL_ERROR
+          "CMAKE_USE_SYSTEM_LIBUV is ON but a libuv is not found!")
+      endif()
+      set(CMAKE_LIBUV_LIBRARIES LibUV::LibUV)
+    else()
+      set(CMAKE_LIBUV_LIBRARIES cmlibuv)
+      add_subdirectory(Utilities/cmlibuv)
+      CMAKE_SET_TARGET_FOLDER(cmlibuv "Utilities/3rdParty")
+    endif()
+  else()
+    set(CMAKE_LIBUV_LIBRARIES)
+  endif()
+
+  #---------------------------------------------------------------------
   # Build XMLRPC library for CMake and CTest.
   if(CTEST_USE_XMLRPC)
     find_package(XMLRPC QUIET REQUIRED libwww-client)
@@ -637,6 +698,31 @@ endif()
 # setup some Testing support (a macro defined in this file)
 CMAKE_SETUP_TESTING()
 
+# Check whether to build server mode or not:
+if(NOT CMake_TEST_EXTERNAL_CMAKE)
+  if(NOT DEFINED CMake_ENABLE_SERVER_MODE)
+    list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_auto_type CMake_HAVE_CXX_AUTO_TYPE)
+    list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_range_for CMake_HAVE_CXX_RANGE_FOR)
+    if(CMAKE_USE_LIBUV
+        AND CMake_HAVE_CXX_AUTO_TYPE
+        AND CMake_HAVE_CXX_MAKE_UNIQUE
+        AND CMake_HAVE_CXX_RANGE_FOR
+        )
+      set(CMake_ENABLE_SERVER_MODE 1)
+    else()
+      set(CMake_ENABLE_SERVER_MODE 0)
+    endif()
+  endif()
+  if(CMake_ENABLE_SERVER_MODE AND NOT CMAKE_USE_LIBUV)
+    message(FATAL_ERROR "The server mode requires libuv!")
+  endif()
+else()
+  set(CMake_ENABLE_SERVER_MODE 0)
+endif()
+if(NOT DEFINED CMake_TEST_SERVER_MODE)
+  set(CMake_TEST_SERVER_MODE ${CMake_ENABLE_SERVER_MODE})
+endif()
+
 if(NOT CMake_TEST_EXTERNAL_CMAKE)
   if(NOT CMake_VERSION_IS_RELEASE)
     if(CMAKE_C_COMPILER_ID STREQUAL "GNU" AND
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index ddf8407..921ba7c 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -6,22 +6,26 @@ Community
 
 CMake is maintained and supported by `Kitware`_ and developed in
 collaboration with a productive community of contributors.
+Please subscribe and post to the `CMake Developers List`_ to raise
+discussion of development topics.
 
 .. _`Kitware`: http://www.kitware.com/cmake
-
-The preferred entry point for new contributors is the mailing list.
-Please subscribe and post to the `CMake Developers List`_ to offer
-contributions.  Regular and productive contributors may be invited
-to gain direct push access.
-
 .. _`CMake Developers List`: https://cmake.org/mailman/listinfo/cmake-developers
 
 Patches
 =======
 
-Please base all new work on the ``master`` branch.  Then use
-``git format-patch`` to produce patches suitable to post to
-the mailing list.
+CMake uses `Kitware's GitLab Instance`_ to manage development and code review.
+To contribute patches:
+
+#. Fork the upstream `CMake Repository`_ into a personal account.
+#. Base all new work on the upstream ``master`` branch.
+#. Create commits making incremental, distinct, logically complete changes.
+#. Push a topic branch to a personal repository fork on GitLab.
+#. Create a GitLab Merge Request targeting the upstream ``master`` branch.
+
+.. _`Kitware's GitLab Instance`: https://gitlab.kitware.com
+.. _`CMake Repository`: https://gitlab.kitware.com/cmake/cmake
 
 Code Style
 ==========
@@ -29,9 +33,11 @@ Code Style
 We use `clang-format`_ to define our style for C++ code in the CMake source
 tree.  See the `.clang-format`_ configuration file for our style settings.
 Use ``clang-format`` version 3.8 or higher to format source files.
+See also the `Utilities/Scripts/clang-format.bash`_ script.
 
 .. _`clang-format`: http://clang.llvm.org/docs/ClangFormat.html
 .. _`.clang-format`: .clang-format
+.. _`Utilities/Scripts/clang-format.bash`: Utilities/Scripts/clang-format.bash
 
 License
 =======
diff --git a/CTestConfig.cmake b/CTestConfig.cmake
index df2f94c..020582e 100644
--- a/CTestConfig.cmake
+++ b/CTestConfig.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 set(CTEST_PROJECT_NAME "CMake")
 set(CTEST_NIGHTLY_START_TIME "1:00:00 UTC")
 
diff --git a/CTestCustom.cmake.in b/CTestCustom.cmake.in
index a39049b..48dd3de 100644
--- a/CTestCustom.cmake.in
+++ b/CTestCustom.cmake.in
@@ -49,6 +49,7 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
   "stl_deque.h:1051"
   "(Lexer|Parser).*warning.*conversion.*may (alter its value|change the sign)"
   "(Lexer|Parser).*warning.*(statement is unreachable|will never be executed)"
+  "(Lexer|Parser).*warning.*variable.*was set but never used"
   "PGC-W-0095-Type cast required for this conversion.*ProcessUNIX.c"
   "[Qq]t([Cc]ore|[Gg]ui|[Ww]idgets).*warning.*conversion.*may alter its value"
   "warning:.*is.*very unsafe.*consider using.*"
@@ -62,13 +63,17 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
   "warning.*This version of Mac OS X is unsupported"
   "clang.*: warning: argument unused during compilation: .-g"
   "note: in expansion of macro" # diagnostic context note
+  "note: expanded from macro" # diagnostic context note
   "cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*rand.*may return deterministic values"
   "cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*rand.*isn.*t random" # we do not do crypto
   "cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*srand.*seed choices are.*poor" # we do not do crypto
+  "IPA warning: function.*multiply defined in"
 
   # Ignore clang's summary warning, assuming prior text has matched some
   # other warning expression:
   "[0-9,]+ warnings? generated."
+  # similarly for PGI
+  "compilation completed with warnings"
 
 # scanbuild exceptions
   "char_traits.h:.*: warning: Null pointer argument in call to string length function"
@@ -80,8 +85,11 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
   "index_encoder.c.241.2. warning: Value stored to .out_start. is never read"
   "index.c.*warning: Access to field.*results in a dereference of a null pointer.*loaded from variable.*"
   "cm_sha2.*warning: Value stored to.*is never read"
+  "cmFortranLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
   "testProcess.*warning: Dereference of null pointer .loaded from variable .invalidAddress.."
   "liblzma/simple/x86.c:[0-9]+:[0-9]+: warning: The result of the '<<' expression is undefined"
+  "libuv/src/.*:[0-9]+:[0-9]+: warning: Dereference of null pointer"
+  "libuv/src/.*:[0-9]+:[0-9]+: warning: The left operand of '==' is a garbage value"
   )
 
 if(NOT "@CMAKE_GENERATOR@" MATCHES "Xcode")
diff --git a/CompileFlags.cmake b/CompileFlags.cmake
index 3c053fa..c875e6f 100644
--- a/CompileFlags.cmake
+++ b/CompileFlags.cmake
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 #-----------------------------------------------------------------------------
 # set some special flags for different compilers
@@ -64,7 +55,7 @@ endif()
 
 # Workaround for short jump tables on PA-RISC
 if(CMAKE_SYSTEM_PROCESSOR MATCHES "^parisc")
-  if(CMAKE_COMPILER_IS_GNUC)
+  if(CMAKE_COMPILER_IS_GNUCC)
     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mlong-calls")
   endif()
   if(CMAKE_COMPILER_IS_GNUCXX)
@@ -80,6 +71,13 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL SunPro)
   endif()
 endif()
 
+foreach(lang C CXX)
+  # Suppress warnings from PGI compiler.
+  if (CMAKE_${lang}_COMPILER_ID STREQUAL "PGI")
+    set(CMAKE_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} -w")
+  endif()
+endforeach()
+
 # use the ansi CXX compile flag for building cmake
 if (CMAKE_ANSI_CXXFLAGS)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_ANSI_CXXFLAGS}")
diff --git a/Copyright.txt b/Copyright.txt
index f99998f..63d7bb8 100644
--- a/Copyright.txt
+++ b/Copyright.txt
@@ -1,6 +1,5 @@
 CMake - Cross Platform Makefile Generator
-Copyright 2000-2016 Kitware, Inc.
-Copyright 2000-2011 Insight Software Consortium
+Copyright 2000-2016 Kitware, Inc. and Contributors
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -14,10 +13,9 @@ are met:
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 
-* Neither the names of Kitware, Inc., the Insight Software Consortium,
-  nor the names of their contributors may be used to endorse or promote
-  products derived from this software without specific prior written
-  permission.
+* Neither the name of Kitware, Inc. nor the names of Contributors
+  may be used to endorse or promote products derived from this
+  software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -33,12 +31,77 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 ------------------------------------------------------------------------------
 
+The following individuals and institutions are among the Contributors:
+
+* Aaron C. Meadows <cmake at shadowguarddev.com>
+* Aleksey Avdeev <solo at altlinux.ru>
+* Alexander Neundorf <neundorf at kde.org>
+* Alexander Smorkalov <alexander.smorkalov at itseez.com>
+* Alex Turbov <i.zaufi at gmail.com>
+* Andreas Pakulat <apaku at gmx.de>
+* Andreas Schneider <asn at cryptomilk.org>
+* André Rigland Brodtkorb <Andre.Brodtkorb at ifi.uio.no>
+* Axel Huebl, Helmholtz-Zentrum Dresden - Rossendorf
+* Benjamin Eikel
+* Bjoern Ricks <bjoern.ricks at gmail.com>
+* Brad Hards <bradh at kde.org>
+* Christopher Harvey
+* Christoph Grüninger <foss at grueninger.de>
+* Clement Creusot <creusot at cs.york.ac.uk>
+* Daniel Blezek <blezek at gmail.com>
+* Daniel Pfeifer <daniel at pfeifer-mail.de>
+* Enrico Scholz <enrico.scholz at informatik.tu-chemnitz.de>
+* Eran Ifrah <eran.ifrah at gmail.com>
+* Esben Mose Hansen, Ange Optimization ApS
+* Geoffrey Viola <geoffrey.viola at asirobots.com>
+* Gregor Jasny
+* Helio Chissini de Castro <helio at kde.org>
+* Ilya Lavrenov <ilya.lavrenov at itseez.com>
+* Insight Software Consortium <insightsoftwareconsortium.org>
+* Jan Woetzel
+* Kelly Thompson <kgt at lanl.gov>
+* Konstantin Podsvirov <konstantin at podsvirov.pro>
+* Mario Bensi <mbensi at ipsquad.net>
+* Mathieu Malaterre <mathieu.malaterre at gmail.com>
+* Matthaeus G. Chajdas
+* Matthias Kretz <kretz at kde.org>
+* Matthias Maennich <matthias at maennich.net>
+* Miguel A. Figueroa-Villanueva
+* Mike Jackson
+* Mike McQuaid <mike at mikemcquaid.com>
+* Nicolas Bock <nicolasbock at gmail.com>
+* Nicolas Despres <nicolas.despres at gmail.com>
+* Nikita Krupen'ko <krnekit at gmail.com>
+* OpenGamma Ltd. <opengamma.com>
+* Per Øyvind Karlsen <peroyvind at mandriva.org>
+* Peter Collingbourne <peter at pcc.me.uk>
+* Petr Gotthard <gotthard at honeywell.com>
+* Philip Lowman <philip at yhbt.com>
+* Philippe Proulx <pproulx at efficios.com>
+* Raffi Enficiaud, Max Planck Society
+* Raumfeld <raumfeld.com>
+* Roger Leigh <rleigh at codelibre.net>
+* Rolf Eike Beer <eike at sf-mail.de>
+* Roman Donchenko <roman.donchenko at itseez.com>
+* Roman Kharitonov <roman.kharitonov at itseez.com>
+* Ruslan Baratov
+* Sebastian Holtermann <sebholt at xwmw.org>
+* Stephen Kelly <steveire at gmail.com>
+* Sylvain Joubert <joubert.sy at gmail.com>
+* Thomas Sondergaard <ts at medical-insight.com>
+* Tobias Hunger <tobias.hunger at qt.io>
+* Todd Gamblin <tgamblin at llnl.gov>
+* Tristan Carel
+* University of Dundee
+* Vadim Zhukov
+* Will Dicharry <wdicharry at stellarscience.com>
+
+See version control history for details of individual contributions.
+
 The above copyright and license notice applies to distributions of
-CMake in source and binary form.  Some source files contain additional
-notices of original copyright by their contributors; see each source
-for details.  Third-party software packages supplied with CMake under
-compatible licenses provide their own copyright notices documented in
-corresponding subdirectories.
+CMake in source and binary form.  Third-party software packages supplied
+with CMake under compatible licenses provide their own copyright notices
+documented in corresponding subdirectories or source files.
 
 ------------------------------------------------------------------------------
 
diff --git a/DartConfig.cmake b/DartConfig.cmake
index 92dffca..7d7c45b 100644
--- a/DartConfig.cmake
+++ b/DartConfig.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 set(CTEST_PROJECT_NAME "CMake")
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 
diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst
index d421364..4ab4298 100644
--- a/Help/command/add_custom_command.rst
+++ b/Help/command/add_custom_command.rst
@@ -20,6 +20,7 @@ The first signature is for adding a custom command to produce an output::
                                       [<lang2> depend2] ...]
                      [WORKING_DIRECTORY dir]
                      [COMMENT comment]
+                     [DEPFILE depfile]
                      [VERBATIM] [APPEND] [USES_TERMINAL])
 
 This defines a command to generate specified ``OUTPUT`` file(s).
@@ -170,6 +171,12 @@ The options are:
   If it is a relative path it will be interpreted relative to the
   build tree directory corresponding to the current source directory.
 
+``DEPFILE``
+  Specify a ``.d`` depfile for the :generator:`Ninja` generator.
+  A ``.d`` file holds dependencies usually emitted by the custom
+  command itself.
+  Using ``DEPFILE`` with other generators than Ninja is an error.
+
 Build Events
 ^^^^^^^^^^^^
 
diff --git a/Help/command/cmake_parse_arguments.rst b/Help/command/cmake_parse_arguments.rst
index 6206611..ec4ffed 100644
--- a/Help/command/cmake_parse_arguments.rst
+++ b/Help/command/cmake_parse_arguments.rst
@@ -11,6 +11,17 @@ respective options.
   cmake_parse_arguments(<prefix> <options> <one_value_keywords>
                         <multi_value_keywords> args...)
 
+  cmake_parse_arguments(PARSE_ARGV N <prefix> <options> <one_value_keywords>
+                        <multi_value_keywords>)
+
+The first signature reads processes arguments passed in the ``args...``.
+This may be used in either a :command:`macro` or a :command:`function`.
+
+The ``PARSE_ARGV`` signature is only for use in a :command:`function`
+body.  In this case the arguments that are parsed come from the
+``ARGV#`` variables of the calling function.  The parsing starts with
+the Nth argument, where ``N`` is an unsigned integer.  This allows for
+the values to have special characters like ``;`` in them.
 
 The ``<options>`` argument contains all options for the respective macro,
 i.e.  keywords which can be used when calling the macro without any value
diff --git a/Help/command/ctest_build.rst b/Help/command/ctest_build.rst
index e1b7793..55bb4a3 100644
--- a/Help/command/ctest_build.rst
+++ b/Help/command/ctest_build.rst
@@ -13,6 +13,7 @@ Perform the :ref:`CTest Build Step` as a :ref:`Dashboard Client`.
               [NUMBER_ERRORS <num-err-var>]
               [NUMBER_WARNINGS <num-warn-var>]
               [RETURN_VALUE <result-var>]
+              [CAPTURE_CMAKE_ERROR <result-var>]
               )
 
 Build the project and store results in ``Build.xml``
@@ -29,9 +30,11 @@ The options are:
   :variable:`CTEST_BINARY_DIRECTORY` variable is used.
 
 ``APPEND``
-  Mark results for append to those previously submitted to a
+  Mark ``Build.xml`` for append to results previously submitted to a
   dashboard server since the last :command:`ctest_start` call.
   Append semantics are defined by the dashboard server in use.
+  This does *not* cause results to be appended to a ``.xml`` file
+  produced by a previous call to this command.
 
 ``CONFIGURATION <config>``
   Specify the build configuration (e.g. ``Debug``).  If not
@@ -66,6 +69,10 @@ The options are:
 ``RETURN_VALUE <result-var>``
   Store the return value of the native build tool in the given variable.
 
+``CAPTURE_CMAKE_ERROR <result-var>``
+  Store in the ``<result-var>`` variable -1 if there are any errors running
+  the command and prevent ctest from returning non-zero if an error occurs.
+
 ``QUIET``
   Suppress any CTest-specific non-error output that would have been
   printed to the console otherwise.  The summary of warnings / errors,
diff --git a/Help/command/ctest_configure.rst b/Help/command/ctest_configure.rst
index 851c292..2dea07b 100644
--- a/Help/command/ctest_configure.rst
+++ b/Help/command/ctest_configure.rst
@@ -6,7 +6,8 @@ Perform the :ref:`CTest Configure Step` as a :ref:`Dashboard Client`.
 ::
 
   ctest_configure([BUILD <build-dir>] [SOURCE <source-dir>] [APPEND]
-                  [OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET])
+                  [OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET]
+                  [CAPTURE_CMAKE_ERROR <result-var>])
 
 Configure the project build tree and record results in ``Configure.xml``
 for submission with the :command:`ctest_submit` command.
@@ -22,9 +23,11 @@ The options are:
   :variable:`CTEST_SOURCE_DIRECTORY` variable is used.
 
 ``APPEND``
-  Mark results for append to those previously submitted to a
+  Mark ``Configure.xml`` for append to results previously submitted to a
   dashboard server since the last :command:`ctest_start` call.
   Append semantics are defined by the dashboard server in use.
+  This does *not* cause results to be appended to a ``.xml`` file
+  produced by a previous call to this command.
 
 ``OPTIONS <options>``
   Specify command-line arguments to pass to the configuration tool.
@@ -33,6 +36,10 @@ The options are:
   Store in the ``<result-var>`` variable the return value of the native
   configuration tool.
 
+``CAPTURE_CMAKE_ERROR <result-var>``
+  Store in the ``<result-var>`` variable -1 if there are any errors running
+  the command and prevent ctest from returning non-zero if an error occurs.
+
 ``QUIET``
   Suppress any CTest-specific non-error messages that would have
   otherwise been printed to the console.  Output from the underlying
diff --git a/Help/command/ctest_coverage.rst b/Help/command/ctest_coverage.rst
index 12429b9..8d27b9c 100644
--- a/Help/command/ctest_coverage.rst
+++ b/Help/command/ctest_coverage.rst
@@ -8,6 +8,7 @@ Perform the :ref:`CTest Coverage Step` as a :ref:`Dashboard Client`.
   ctest_coverage([BUILD <build-dir>] [APPEND]
                  [LABELS <label>...]
                  [RETURN_VALUE <result-var>]
+                 [CAPTURE_CMAKE_ERROR <result-var]
                  [QUIET]
                  )
 
@@ -21,9 +22,11 @@ The options are:
   :variable:`CTEST_BINARY_DIRECTORY` variable is used.
 
 ``APPEND``
-  Mark results for append to those previously submitted to a
+  Mark ``Coverage.xml`` for append to results previously submitted to a
   dashboard server since the last :command:`ctest_start` call.
   Append semantics are defined by the dashboard server in use.
+  This does *not* cause results to be appended to a ``.xml`` file
+  produced by a previous call to this command.
 
 ``LABELS``
   Filter the coverage report to include only source files labeled
@@ -33,6 +36,10 @@ The options are:
   Store in the ``<result-var>`` variable ``0`` if coverage tools
   ran without error and non-zero otherwise.
 
+``CAPTURE_CMAKE_ERROR <result-var>``
+  Store in the ``<result-var>`` variable -1 if there are any errors running
+  the command and prevent ctest from returning non-zero if an error occurs.
+
 ``QUIET``
   Suppress any CTest-specific non-error output that would have been
   printed to the console otherwise.  The summary indicating how many
diff --git a/Help/command/ctest_test.rst b/Help/command/ctest_test.rst
index 412e323..ce50d42 100644
--- a/Help/command/ctest_test.rst
+++ b/Help/command/ctest_test.rst
@@ -18,6 +18,7 @@ Perform the :ref:`CTest Test Step` as a :ref:`Dashboard Client`.
              [SCHEDULE_RANDOM <ON|OFF>]
              [STOP_TIME <time-of-day>]
              [RETURN_VALUE <result-var>]
+             [CAPTURE_CMAKE_ERROR <result-var>]
              [QUIET]
              )
 
@@ -31,9 +32,11 @@ The options are:
   :variable:`CTEST_BINARY_DIRECTORY` variable is used.
 
 ``APPEND``
-  Mark results for append to those previously submitted to a
+  Mark ``Test.xml`` for append to results previously submitted to a
   dashboard server since the last :command:`ctest_start` call.
   Append semantics are defined by the dashboard server in use.
+  This does *not* cause results to be appended to a ``.xml`` file
+  produced by a previous call to this command.
 
 ``START <start-number>``
   Specify the beginning of a range of test numbers.
@@ -80,6 +83,10 @@ The options are:
   Store in the ``<result-var>`` variable ``0`` if all tests passed.
   Store non-zero if anything went wrong.
 
+``CAPTURE_CMAKE_ERROR <result-var>``
+  Store in the ``<result-var>`` variable -1 if there are any errors running
+  the command and prevent ctest from returning non-zero if an error occurs.
+
 ``QUIET``
   Suppress any CTest-specific non-error messages that would have otherwise
   been printed to the console.  Output from the underlying test command is not
diff --git a/Help/command/ctest_upload.rst b/Help/command/ctest_upload.rst
index d9630d2..39d9de1 100644
--- a/Help/command/ctest_upload.rst
+++ b/Help/command/ctest_upload.rst
@@ -5,7 +5,7 @@ Upload files to a dashboard server as a :ref:`Dashboard Client`.
 
 ::
 
-  ctest_upload(FILES <file>... [QUIET])
+  ctest_upload(FILES <file>... [QUIET] [CAPTURE_CMAKE_ERROR <result-var>])
 
 The options are:
 
@@ -16,3 +16,7 @@ The options are:
 ``QUIET``
   Suppress any CTest-specific non-error output that would have been
   printed to the console otherwise.
+
+``CAPTURE_CMAKE_ERROR <result-var>``
+  Store in the ``<result-var>`` variable -1 if there are any errors running
+  the command and prevent ctest from returning non-zero if an error occurs.
diff --git a/Help/command/export.rst b/Help/command/export.rst
index 4419dc1..53675a7 100644
--- a/Help/command/export.rst
+++ b/Help/command/export.rst
@@ -55,3 +55,18 @@ build tree. In some cases, for example for packaging and for system
 wide installations, it is not desirable to write the user package
 registry. If the :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable
 is enabled, the ``export(PACKAGE)`` command will do nothing.
+
+::
+
+  export(TARGETS [target1 [target2 [...]]]  [ANDROID_MK <filename>])
+
+This signature exports cmake built targets to the android ndk build system
+by creating an Android.mk file that references the prebuilt targets. The
+Android NDK supports the use of prebuilt libraries, both static and shared.
+This allows cmake to build the libraries of a project and make them available
+to an ndk build system complete with transitive dependencies, include flags
+and defines required to use the libraries. The signature takes a list of
+targets and puts them in the Android.mk file specified by the ``<filename>``
+given. This signature can only be used if policy CMP0022 is NEW for all
+targets given. A error will be issued if that policy is set to OLD for one
+of the targets.
diff --git a/Help/command/file.rst b/Help/command/file.rst
index 256d16d..77e9f62 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -222,6 +222,12 @@ Options to both ``DOWNLOAD`` and ``UPLOAD`` are:
 ``TIMEOUT <seconds>``
   Terminate the operation after a given total time has elapsed.
 
+``USERPWD <username>:<password>``
+  Set username and password for operation.
+
+``HTTPHEADER <HTTP-header>``
+  HTTP header for operation. Suboption can be repeated several times.
+
 Additional options to ``DOWNLOAD`` are:
 
 ``EXPECTED_HASH ALGO=<value>``
diff --git a/Help/command/find_library.rst b/Help/command/find_library.rst
index 31e6ec0..1eb50f7 100644
--- a/Help/command/find_library.rst
+++ b/Help/command/find_library.rst
@@ -49,6 +49,13 @@ path to the framework ``<fullPath>/A.framework``.  When a full path to a
 framework is used as a library, CMake will use a ``-framework A``, and a
 ``-F<fullPath>`` to link the framework to the target.
 
+If the :prop_gbl:`FIND_LIBRARY_USE_LIB32_PATHS` global property is set
+all search paths will be tested as normal, with ``32/`` appended, and
+with all matches of ``lib/`` replaced with ``lib32/``.  This property is
+automatically set for the platforms that are known to need it if at
+least one of the languages supported by the :command:`project` command
+is enabled.
+
 If the :prop_gbl:`FIND_LIBRARY_USE_LIB64_PATHS` global property is set
 all search paths will be tested as normal, with ``64/`` appended, and
 with all matches of ``lib/`` replaced with ``lib64/``.  This property is
diff --git a/Help/command/find_package.rst b/Help/command/find_package.rst
index 58dff9d..2cb1e5f 100644
--- a/Help/command/find_package.rst
+++ b/Help/command/find_package.rst
@@ -170,11 +170,21 @@ is acceptable the following variables are set:
 ``<package>_VERSION_COUNT``
   number of version components, 0 to 4
 
-and the corresponding package configuration file is loaded.  When
-multiple package configuration files are available whose version files
+and the corresponding package configuration file is loaded.
+When multiple package configuration files are available whose version files
 claim compatibility with the version requested it is unspecified which
-one is chosen.  No attempt is made to choose a highest or closest
-version number.
+one is chosen: unless the variable :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER`
+is set no attempt is made to choose a highest or closest version number.
+
+To control the order in which ``find_package`` checks for compatibiliy use
+the two variables :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER` and
+:variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION`.
+For instance in order to select the highest version one can set::
+
+  SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
+  SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
+
+before calling ``find_package``.
 
 Config mode provides an elaborate interface and search procedure.
 Much of the interface is provided for completeness and for use
@@ -194,13 +204,16 @@ configuration file.  The tables below show the directories searched.
 Each entry is meant for installation trees following Windows (W), UNIX
 (U), or Apple (A) conventions::
 
-  <prefix>/                                               (W)
-  <prefix>/(cmake|CMake)/                                 (W)
-  <prefix>/<name>*/                                       (W)
-  <prefix>/<name>*/(cmake|CMake)/                         (W)
-  <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/          (U)
-  <prefix>/(lib/<arch>|lib|share)/<name>*/                (U)
-  <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (U)
+  <prefix>/                                                       (W)
+  <prefix>/(cmake|CMake)/                                         (W)
+  <prefix>/<name>*/                                               (W)
+  <prefix>/<name>*/(cmake|CMake)/                                 (W)
+  <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/                  (U)
+  <prefix>/(lib/<arch>|lib|share)/<name>*/                        (U)
+  <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/          (U)
+  <prefix>/<name>*/(lib/<arch>|lib|share)/cmake/<name>*/          (W/U)
+  <prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/                (W/U)
+  <prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (W/U)
 
 On systems supporting OS X Frameworks and Application Bundles the
 following directories are searched for frameworks or bundles
diff --git a/Help/command/get_cmake_property.rst b/Help/command/get_cmake_property.rst
index 3a6fb41..497ab4e 100644
--- a/Help/command/get_cmake_property.rst
+++ b/Help/command/get_cmake_property.rst
@@ -1,15 +1,20 @@
 get_cmake_property
 ------------------
 
-Get a property of the CMake instance.
+Get a global property of the CMake instance.
 
 ::
 
   get_cmake_property(VAR property)
 
-Get a property from the CMake instance.  The value of the property is
+Get a global property from the CMake instance.  The value of the property is
 stored in the variable ``VAR``.  If the property is not found, ``VAR``
 will be  set to "NOTFOUND".  See the :manual:`cmake-properties(7)` manual
 for available properties.
 
-See also the more general :command:`get_property` command.
+See also the :command:`get_property` command ``GLOBAL`` option.
+
+In addition to global properties, this command (for historical reasons)
+also supports the :prop_dir:`VARIABLES` and :prop_dir:`MACROS` directory
+properties.  It also supports a special ``COMPONENTS`` global property that
+lists the components given to the :command:`install` command.
diff --git a/Help/command/if.rst b/Help/command/if.rst
index 56e618c..0941029 100644
--- a/Help/command/if.rst
+++ b/Help/command/if.rst
@@ -30,10 +30,12 @@ else and endif clause is optional.  Long expressions can be used and
 there is a traditional order of precedence.  Parenthetical expressions
 are evaluated first followed by unary tests such as ``EXISTS``,
 ``COMMAND``, and ``DEFINED``.  Then any binary tests such as
-``EQUAL``, ``LESS``, ``GREATER``, ``STRLESS``, ``STRGREATER``,
-``STREQUAL``, and ``MATCHES`` will be evaluated.  Then boolean ``NOT``
-operators and finally boolean ``AND`` and then ``OR`` operators will
-be evaluated.
+``EQUAL``, ``LESS``, ``LESS_EQUAL, ``GREATER``, ``GREATER_EQUAL``,
+``STREQUAL``, ``STRLESS``, ``STRLESS_EQUAL``, ``STRGREATER``,
+``STRGREATER_EQUAL``, ``VERSION_EQUAL``, ``VERSION_LESS``,
+``VERSION_LESS_EQUAL``, ``VERSION_GREATER``, ``VERSION_GREATER_EQUAL``,
+and ``MATCHES`` will be evaluated.  Then boolean ``NOT`` operators and
+finally boolean ``AND`` and then ``OR`` operators will be evaluated.
 
 Possible expressions are:
 
@@ -115,6 +117,14 @@ Possible expressions are:
  True if the given string or variable's value is a valid number and equal
  to that on the right.
 
+``if(<variable|string> LESS_EQUAL <variable|string>)``
+ True if the given string or variable's value is a valid number and less
+ than or equal to that on the right.
+
+``if(<variable|string> GREATER_EQUAL <variable|string>)``
+ True if the given string or variable's value is a valid number and greater
+ than or equal to that on the right.
+
 ``if(<variable|string> STRLESS <variable|string>)``
  True if the given string or variable's value is lexicographically less
  than the string or variable on the right.
@@ -127,15 +137,31 @@ Possible expressions are:
  True if the given string or variable's value is lexicographically equal
  to the string or variable on the right.
 
+``if(<variable|string> STRLESS_EQUAL <variable|string>)``
+ True if the given string or variable's value is lexicographically less
+ than or equal to the string or variable on the right.
+
+``if(<variable|string> STRGREATER_EQUAL <variable|string>)``
+ True if the given string or variable's value is lexicographically greater
+ than or equal to the string or variable on the right.
+
 ``if(<variable|string> VERSION_LESS <variable|string>)``
  Component-wise integer version number comparison (version format is
  ``major[.minor[.patch[.tweak]]]``).
 
+``if(<variable|string> VERSION_GREATER <variable|string>)``
+ Component-wise integer version number comparison (version format is
+ ``major[.minor[.patch[.tweak]]]``).
+
 ``if(<variable|string> VERSION_EQUAL <variable|string>)``
  Component-wise integer version number comparison (version format is
  ``major[.minor[.patch[.tweak]]]``).
 
-``if(<variable|string> VERSION_GREATER <variable|string>)``
+``if(<variable|string> VERSION_LESS_EQUAL <variable|string>)``
+ Component-wise integer version number comparison (version format is
+ ``major[.minor[.patch[.tweak]]]``).
+
+``if(<variable|string> VERSION_GREATER_EQUAL <variable|string>)``
  Component-wise integer version number comparison (version format is
  ``major[.minor[.patch[.tweak]]]``).
 
@@ -186,20 +212,21 @@ above-documented signature accepts ``<variable|string>``:
 * If the left hand argument to ``MATCHES`` is missing it returns false
   without error
 
-* Both left and right hand arguments to ``LESS``, ``GREATER``, and
-  ``EQUAL`` are independently tested to see if they are defined
-  variables, if so their defined values are used otherwise the original
-  value is used.
+* Both left and right hand arguments to ``LESS``, ``GREATER``, ``EQUAL``,
+  ``LESS_EQUAL``, and ``GREATER_EQUAL``, are independently tested to see if
+  they are defined variables, if so their defined values are used otherwise
+  the original value is used.
 
-* Both left and right hand arguments to ``STRLESS``, ``STREQUAL``, and
-  ``STRGREATER`` are independently tested to see if they are defined
-  variables, if so their defined values are used otherwise the original
-  value is used.
+* Both left and right hand arguments to ``STRLESS``, ``STRGREATER``,
+  ``STREQUAL``, ``STRLESS_EQUAL``, and ``STRGREATER_EQUAL`` are independently
+  tested to see if they are defined variables, if so their defined values are
+  used otherwise the original value is used.
 
 * Both left and right hand arguments to ``VERSION_LESS``,
-  ``VERSION_EQUAL``, and ``VERSION_GREATER`` are independently tested
-  to see if they are defined variables, if so their defined values are
-  used otherwise the original value is used.
+  ``VERSION_GREATER``, ``VERSION_EQUAL``, ``VERSION_LESS_EQUAL``, and
+  ``VERSION_GREATER_EQUAL`` are independently tested to see if they are defined
+  variables, if so their defined values are used otherwise the original value
+  is used.
 
 * The right hand argument to ``NOT`` is tested to see if it is a boolean
   constant, if so the value is used, otherwise it is assumed to be a
diff --git a/Help/command/include.rst b/Help/command/include.rst
index c391561..eeca4c6 100644
--- a/Help/command/include.rst
+++ b/Help/command/include.rst
@@ -15,10 +15,10 @@ is present, then no error is raised if the file does not exist.  If
 which has been included or NOTFOUND if it failed.
 
 If a module is specified instead of a file, the file with name
-<modulename>.cmake is searched first in :variable:`CMAKE_MODULE_PATH`,
+``<modulename>.cmake`` is searched first in :variable:`CMAKE_MODULE_PATH`,
 then in the CMake module directory.  There is one exception to this: if
-the file which calls ``include()`` is located itself in the CMake module
-directory, then first the CMake module directory is searched and
+the file which calls ``include()`` is located itself in the CMake builtin
+module directory, then first the CMake builtin module directory is searched and
 :variable:`CMAKE_MODULE_PATH` afterwards.  See also policy :policy:`CMP0017`.
 
 See the :command:`cmake_policy` command documentation for discussion of the
diff --git a/Help/command/install.rst b/Help/command/install.rst
index aaf12cc..d57dd75 100644
--- a/Help/command/install.rst
+++ b/Help/command/install.rst
@@ -314,7 +314,8 @@ Installing Exports
 ::
 
   install(EXPORT <export-name> DESTINATION <dir>
-          [NAMESPACE <namespace>] [FILE <name>.cmake]
+          [NAMESPACE <namespace>] [[FILE <name>.cmake]|
+          [EXPORT_ANDROID_MK <name>.mk]]
           [PERMISSIONS permissions...]
           [CONFIGURATIONS [Debug|Release|...]]
           [EXPORT_LINK_INTERFACE_LIBRARIES]
@@ -342,6 +343,13 @@ specified that does not match that given to the targets associated with
 included in the export but a target to which it links is not included
 the behavior is unspecified.
 
+In additon to cmake language files, the ``EXPORT_ANDROID_MK`` option maybe
+used to specifiy an export to the android ndk build system.  The Android
+NDK supports the use of prebuilt libraries, both static and shared. This
+allows cmake to build the libraries of a project and make them available
+to an ndk build system complete with transitive dependencies, include flags
+and defines required to use the libraries.
+
 The ``EXPORT`` form is useful to help outside projects use targets built
 and installed by the current project.  For example, the code
 
@@ -349,9 +357,11 @@ and installed by the current project.  For example, the code
 
   install(TARGETS myexe EXPORT myproj DESTINATION bin)
   install(EXPORT myproj NAMESPACE mp_ DESTINATION lib/myproj)
+  install(EXPORT_ANDROID_MK myexp DESTINATION share/ndk-modules)
 
 will install the executable myexe to ``<prefix>/bin`` and code to import
-it in the file ``<prefix>/lib/myproj/myproj.cmake``.  An outside project
+it in the file ``<prefix>/lib/myproj/myproj.cmake`` and
+``<prefix>/lib/share/ndk-modules/Android.mk``.  An outside project
 may load this file with the include command and reference the ``myexe``
 executable from the installation tree using the imported target name
 ``mp_myexe`` as if the target were built in its own tree.
diff --git a/Help/command/math.rst b/Help/command/math.rst
index d4deb16..f99dc3d 100644
--- a/Help/command/math.rst
+++ b/Help/command/math.rst
@@ -5,9 +5,10 @@ Mathematical expressions.
 
 ::
 
-  math(EXPR <output variable> <math expression>)
+  math(EXPR <output-variable> <math-expression>)
 
 ``EXPR`` evaluates mathematical expression and returns result in the
-output variable.  Example mathematical expression is '5 * ( 10 + 13
-)'.  Supported operators are + - * / % | & ^ ~ << >> * / %.  They have
-the same meaning as they do in C code.
+output variable.  Example mathematical expression is ``5 * (10 + 13)``.
+Supported operators are ``+``, ``-``, ``*``, ``/``, ``%``, ``|``, ``&``,
+``^``, ``~``, ``<<``, ``>>``, and ``(...)``.  They have the same meaning
+as they do in C code.
diff --git a/Help/command/separate_arguments.rst b/Help/command/separate_arguments.rst
index 0e3e5a5..1fd3cd1 100644
--- a/Help/command/separate_arguments.rst
+++ b/Help/command/separate_arguments.rst
@@ -13,19 +13,21 @@ entire command line must be given in one "<args>" argument.
 
 The ``UNIX_COMMAND`` mode separates arguments by unquoted whitespace.  It
 recognizes both single-quote and double-quote pairs.  A backslash
-escapes the next literal character (\" is "); there are no special
-escapes (\n is just n).
+escapes the next literal character (``\"`` is ``"``); there are no special
+escapes (``\n`` is just ``n``).
 
 The ``WINDOWS_COMMAND`` mode parses a windows command-line using the same
 syntax the runtime library uses to construct argv at startup.  It
 separates arguments by whitespace that is not double-quoted.
 Backslashes are literal unless they precede double-quotes.  See the
-MSDN article "Parsing C Command-Line Arguments" for details.
+MSDN article `Parsing C Command-Line Arguments`_ for details.
+
+.. _`Parsing C Command-Line Arguments`: https://msdn.microsoft.com/library/a1y7w461.aspx
 
 ::
 
-  separate_arguments(VARIABLE)
+  separate_arguments(<var>)
 
-Convert the value of ``VARIABLE`` to a semi-colon separated list.  All
+Convert the value of ``<var>`` to a semi-colon separated list.  All
 spaces are replaced with ';'.  This helps with generating command
 lines.
diff --git a/Help/command/set.rst b/Help/command/set.rst
index d04b880..b24ebef 100644
--- a/Help/command/set.rst
+++ b/Help/command/set.rst
@@ -25,7 +25,9 @@ If the ``PARENT_SCOPE`` option is given the variable will be set in
 the scope above the current scope.  Each new directory or function
 creates a new scope.  This command will set the value of a variable
 into the parent directory or calling function (whichever is applicable
-to the case at hand).
+to the case at hand). The previous state of the variable's value stays the
+same in the current scope (e.g., if it was undefined before, it is still
+undefined and if it had a value, it is still that value).
 
 Set Cache Entry
 ^^^^^^^^^^^^^^^
diff --git a/Help/command/string.rst b/Help/command/string.rst
index 3f4050e..8028333 100644
--- a/Help/command/string.rst
+++ b/Help/command/string.rst
@@ -197,10 +197,12 @@ Comparison
 
 ::
 
-  string(COMPARE EQUAL <string1> <string2> <output variable>)
-  string(COMPARE NOTEQUAL <string1> <string2> <output variable>)
   string(COMPARE LESS <string1> <string2> <output variable>)
   string(COMPARE GREATER <string1> <string2> <output variable>)
+  string(COMPARE EQUAL <string1> <string2> <output variable>)
+  string(COMPARE NOTEQUAL <string1> <string2> <output variable>)
+  string(COMPARE LESS_EQUAL <string1> <string2> <output variable>)
+  string(COMPARE GREATER_EQUAL <string1> <string2> <output variable>)
 
 Compare the strings and store true or false in the output variable.
 
@@ -276,12 +278,14 @@ specifiers:
    %I        The hour on a 12-hour clock (01-12).
    %j        The day of the current year (001-366).
    %m        The month of the current year (01-12).
+   %b        Abbreviated month name (e.g. Oct).
    %M        The minute of the current hour (00-59).
    %s        Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
    %S        The second of the current minute.
              60 represents a leap second. (00-60)
    %U        The week number of the current year (00-53).
    %w        The day of the current week. 0 is Sunday. (0-6)
+   %a        Abbreviated weekday name (e.g. Fri).
    %y        The last two digits of the current year (00-99)
    %Y        The current year.
 
diff --git a/Help/command/target_link_libraries.rst b/Help/command/target_link_libraries.rst
index d903d05..90b6575 100644
--- a/Help/command/target_link_libraries.rst
+++ b/Help/command/target_link_libraries.rst
@@ -62,6 +62,12 @@ Each ``<item>`` may be:
   dependencies, so they are generally safe to specify only as private link
   items that will not propagate to dependents.
 
+  Link flags specified here are inserted into the link command in the same
+  place as the link libraries. This might not be correct, depending on
+  the linker. Use the :prop_tgt:`LINK_FLAGS` target property to add link
+  flags explicitly. The flags will then be placed at the toolchain-defined
+  flag position in the link command.
+
 * A ``debug``, ``optimized``, or ``general`` keyword immediately followed
   by another ``<item>``.  The item following such a keyword will be used
   only for the corresponding build configuration.  The ``debug`` keyword
diff --git a/Help/generator/CodeLite.rst b/Help/generator/CodeLite.rst
index dbc46d7..3e60aa6 100644
--- a/Help/generator/CodeLite.rst
+++ b/Help/generator/CodeLite.rst
@@ -5,7 +5,11 @@ Generates CodeLite project files.
 
 Project files for CodeLite will be created in the top directory and
 in every subdirectory which features a CMakeLists.txt file containing
-a PROJECT() call. The appropriate make program can build the
+a :command:`project` call.
+The :variable:`CMAKE_CODELITE_USE_TARGETS` variable may be set to ``ON``
+to change the default behaviour from projects to targets as the basis
+for project files.
+The appropriate make program can build the
 project through the default make target.  A "make install" target is
 also provided.
 
diff --git a/Help/generator/Ninja.rst b/Help/generator/Ninja.rst
index d94e5f6..3bbd9dc 100644
--- a/Help/generator/Ninja.rst
+++ b/Help/generator/Ninja.rst
@@ -7,6 +7,27 @@ A build.ninja file is generated into the build tree.  Recent versions
 of the ninja program can build the project through the "all" target.
 An "install" target is also provided.
 
-For each subdirectory ``sub/dir`` of the project an additional target
-named ``sub/dir/all`` is generated that depends on all targets required
-by that subdirectory.
+For each subdirectory ``sub/dir`` of the project, additional targets
+are generated:
+
+``sub/dir/all``
+  Depends on all targets required by the subdirectory.
+
+``sub/dir/install``
+  Runs the install step in the subdirectory, if any.
+
+``sub/dir/test``
+  Runs the test step in the subdirectory, if any.
+
+``sub/dir/package``
+  Runs the package step in the subdirectory, if any.
+
+Fortran Support
+^^^^^^^^^^^^^^^
+
+The ``Ninja`` generator conditionally supports Fortran when the ``ninja``
+tool has the required features.  As of this version of CMake the needed
+features have not been integrated into upstream Ninja.  Kitware maintains
+a branch of Ninja with the required features on `github.com/Kitware/ninja`_.
+
+.. _`github.com/Kitware/ninja`: https://github.com/Kitware/ninja/tree/features-for-fortran#readme
diff --git a/Help/generator/Visual Studio 10 2010.rst b/Help/generator/Visual Studio 10 2010.rst
index 77ea9df..c694443 100644
--- a/Help/generator/Visual Studio 10 2010.rst	
+++ b/Help/generator/Visual Studio 10 2010.rst	
@@ -4,7 +4,7 @@ Visual Studio 10 2010
 Generates Visual Studio 10 (VS 2010) project files.
 
 The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
-to specify a target platform name.
+to specify a target platform name (architecture).
 
 For compatibility with CMake versions prior to 3.1, one may specify
 a target platform name optionally at the end of this generator name:
diff --git a/Help/generator/Visual Studio 11 2012.rst b/Help/generator/Visual Studio 11 2012.rst
index 5fa7f2c..2f1e729 100644
--- a/Help/generator/Visual Studio 11 2012.rst	
+++ b/Help/generator/Visual Studio 11 2012.rst	
@@ -4,7 +4,7 @@ Visual Studio 11 2012
 Generates Visual Studio 11 (VS 2012) project files.
 
 The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
-to specify a target platform name.
+to specify a target platform name (architecture).
 
 For compatibility with CMake versions prior to 3.1, one may specify
 a target platform name optionally at the end of this generator name:
diff --git a/Help/generator/Visual Studio 12 2013.rst b/Help/generator/Visual Studio 12 2013.rst
index 2c3b119..6e8545b 100644
--- a/Help/generator/Visual Studio 12 2013.rst	
+++ b/Help/generator/Visual Studio 12 2013.rst	
@@ -4,7 +4,7 @@ Visual Studio 12 2013
 Generates Visual Studio 12 (VS 2013) project files.
 
 The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
-to specify a target platform name.
+to specify a target platform name (architecture).
 
 For compatibility with CMake versions prior to 3.1, one may specify
 a target platform name optionally at the end of this generator name:
diff --git a/Help/generator/Visual Studio 14 2015.rst b/Help/generator/Visual Studio 14 2015.rst
index b35997a..707caf9 100644
--- a/Help/generator/Visual Studio 14 2015.rst	
+++ b/Help/generator/Visual Studio 14 2015.rst	
@@ -4,7 +4,7 @@ Visual Studio 14 2015
 Generates Visual Studio 14 (VS 2015) project files.
 
 The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
-to specify a target platform name.
+to specify a target platform name (architecture).
 
 For compatibility with CMake versions prior to 3.1, one may specify
 a target platform name optionally at the end of this generator name:
diff --git a/Help/generator/Visual Studio 15.rst b/Help/generator/Visual Studio 15.rst
new file mode 100644
index 0000000..ae456eb
--- /dev/null
+++ b/Help/generator/Visual Studio 15.rst	
@@ -0,0 +1,16 @@
+Visual Studio 15
+----------------
+
+Generates Visual Studio 15 project files.
+
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name (architecture).
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 15 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 15 ARM``
+  Specify target platform ``ARM``.
diff --git a/Help/index.rst b/Help/index.rst
index 2d3f156..97cd107 100644
--- a/Help/index.rst
+++ b/Help/index.rst
@@ -32,6 +32,7 @@ Reference Manuals
    /manual/cmake-generator-expressions.7
    /manual/cmake-generators.7
    /manual/cmake-language.7
+   /manual/cmake-server.7
    /manual/cmake-modules.7
    /manual/cmake-packages.7
    /manual/cmake-policies.7
diff --git a/Help/manual/OPTIONS_BUILD.txt b/Help/manual/OPTIONS_BUILD.txt
index b428a74..fa0e4c1 100644
--- a/Help/manual/OPTIONS_BUILD.txt
+++ b/Help/manual/OPTIONS_BUILD.txt
@@ -66,10 +66,12 @@
  Specify platform name if supported by generator.
 
  Some CMake generators support a platform name to be given to the
- native build system to choose a compiler or SDK.  This is supported only on
- specific generators::
+ native build system to choose a compiler or SDK.  See the
+ :variable:`CMAKE_GENERATOR_PLATFORM` variable.
+ This is supported only on specific generators:
 
-   Visual Studio >= 8
+ * For :ref:`Visual Studio Generators` with VS 2005 and above this
+   specifies the target architecture.
 
  See native build system documentation for allowed platform names.
 
diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst
index 07bf33f..4950fee 100644
--- a/Help/manual/cmake-buildsystem.7.rst
+++ b/Help/manual/cmake-buildsystem.7.rst
@@ -860,7 +860,7 @@ with :prop_tgt:`IMPORTED` targets.
 Alias Targets
 -------------
 
-An ``ALIAS`` target is a name which may be used interchangably with
+An ``ALIAS`` target is a name which may be used interchangeably with
 a binary target name in read-only contexts.  A primary use-case for ``ALIAS``
 targets is for example or unit test executables accompanying a library, which
 may be part of the same buildsystem or built separately based on user
diff --git a/Help/manual/cmake-developer.7.rst b/Help/manual/cmake-developer.7.rst
index 7bfdcad..6557686 100644
--- a/Help/manual/cmake-developer.7.rst
+++ b/Help/manual/cmake-developer.7.rst
@@ -24,9 +24,10 @@ to build with such toolchains.
 std::auto_ptr
 -------------
 
-Some implementations have a ``std::auto_ptr`` which can not be used as a
-return value from a function. ``std::auto_ptr`` may not be used. Use
-``cmsys::auto_ptr`` instead.
+The ``std::auto_ptr`` template is deprecated in C++11.  We want to use it
+so we can build on C++98 compilers but we do not want to turn off compiler
+warnings about deprecated interfaces in general.  Use the ``CM_AUTO_PTR``
+macro instead.
 
 size_t
 ------
@@ -518,8 +519,16 @@ containing just the line::
 
 The ``cmake-module`` directive will scan the module file to extract
 reStructuredText markup from comment blocks that start in ``.rst:``.
-Add to the top of ``Modules/<module-name>.cmake`` a
-:ref:`Line Comment` block of the form:
+At the top of ``Modules/<module-name>.cmake``, begin with the following
+license notice:
+
+.. code-block:: cmake
+
+ # 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 :ref:`Line Comment` block of the form:
 
 .. code-block:: cmake
 
@@ -551,6 +560,9 @@ For example, a ``Modules/Findxxx.cmake`` module may contain:
 
 .. code-block:: cmake
 
+ # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+ # file Copyright.txt or https://cmake.org/licensing for details.
+
  #.rst:
  # FindXxx
  # -------
@@ -578,25 +590,6 @@ For example, a ``Modules/Findxxx.cmake`` module may contain:
    <code>
  endmacro()
 
-After the top documentation block, leave a *BLANK* line, and then add a
-copyright and licence notice block like this one (change only the year
-range and name)
-
-.. code-block:: cmake
-
-  #=============================================================================
-  # Copyright 2009-2011 Your Name
-  #
-  # Distributed under the OSI-approved BSD License (the "License");
-  # see accompanying file Copyright.txt for details.
-  #
-  # This software is distributed WITHOUT ANY WARRANTY; without even the
-  # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  # See the License for more information.
-  #=============================================================================
-  # (To distribute this file outside of CMake, substitute the full
-  #  License text for the above reference.)
-
 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.
@@ -790,10 +783,17 @@ A Sample Find Module
 We will describe how to create a simple find module for a library
 ``Foo``.
 
-The first thing that is needed is documentation.  CMake's documentation
-system requires you to start the file with a documentation marker and
-the name of the module.  You should follow this with a simple statement
-of what the module does.
+The first thing that is needed is a license notice.
+
+.. code-block:: cmake
+
+ # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+ # file Copyright.txt or https://cmake.org/licensing for details.
+
+Next we need module documentation.  CMake's documentation system requires you
+to follow the license notice with a blank line and then with a documentation
+marker and the name of the module.  You should follow this with a simple
+statement of what the module does.
 
 .. code-block:: cmake
 
@@ -824,24 +824,6 @@ If the package provides any macros, they should be listed here, but can
 be documented where they are defined.  See the `Module
 Documentation`_ section above for more details.
 
-After the documentation, leave a blank line, and then add a copyright and
-licence notice block
-
-.. code-block:: cmake
-
-  #=============================================================================
-  # Copyright 2009-2011 Your Name
-  #
-  # Distributed under the OSI-approved BSD License (the "License");
-  # see accompanying file Copyright.txt for details.
-  #
-  # This software is distributed WITHOUT ANY WARRANTY; without even the
-  # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  # See the License for more information.
-  #=============================================================================
-  # (To distribute this file outside of CMake, substitute the full
-  #  License text for the above reference.)
-
 Now the actual libraries and so on have to be found.  The code here will
 obviously vary from module to module (dealing with that, after all, is the
 point of find modules), but there tends to be a common pattern for libraries.
diff --git a/Help/manual/cmake-generator-expressions.7.rst b/Help/manual/cmake-generator-expressions.7.rst
index d4f47dd..64d15a9 100644
--- a/Help/manual/cmake-generator-expressions.7.rst
+++ b/Help/manual/cmake-generator-expressions.7.rst
@@ -66,12 +66,16 @@ Available logical expressions are:
   ``1`` if the CMake-id of the C compiler matches ``comp``, otherwise ``0``.
 ``$<CXX_COMPILER_ID:comp>``
   ``1`` if the CMake-id of the CXX compiler matches ``comp``, otherwise ``0``.
-``$<VERSION_GREATER:v1,v2>``
-  ``1`` if ``v1`` is a version greater than ``v2``, else ``0``.
 ``$<VERSION_LESS:v1,v2>``
   ``1`` if ``v1`` is a version less than ``v2``, else ``0``.
+``$<VERSION_GREATER:v1,v2>``
+  ``1`` if ``v1`` is a version greater than ``v2``, else ``0``.
 ``$<VERSION_EQUAL:v1,v2>``
   ``1`` if ``v1`` is the same version as ``v2``, else ``0``.
+``$<VERSION_LESS_EQUAL:v1,v2>``
+  ``1`` if ``v1`` is a version less than or equal to ``v2``, else ``0``.
+``$<VERSION_GREATER_EQUAL:v1,v2>``
+  ``1`` if ``v1`` is a version greater than or equal to ``v2``, else ``0``.
 ``$<C_COMPILER_VERSION:ver>``
   ``1`` if the version of the C compiler matches ``ver``, otherwise ``0``.
 ``$<CXX_COMPILER_VERSION:ver>``
diff --git a/Help/manual/cmake-generators.7.rst b/Help/manual/cmake-generators.7.rst
index cde8de8..3df3a81 100644
--- a/Help/manual/cmake-generators.7.rst
+++ b/Help/manual/cmake-generators.7.rst
@@ -82,6 +82,7 @@ Visual Studio Generators
    /generator/Visual Studio 11 2012
    /generator/Visual Studio 12 2013
    /generator/Visual Studio 14 2015
+   /generator/Visual Studio 15
 
 Other Generators
 ^^^^^^^^^^^^^^^^
diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst
index 62910cf..015e36e 100644
--- a/Help/manual/cmake-modules.7.rst
+++ b/Help/manual/cmake-modules.7.rst
@@ -14,6 +14,7 @@ All Modules
    :maxdepth: 1
 
    /module/AddFileDependencies
+   /module/AndroidTestUtilities
    /module/BundleUtilities
    /module/CheckCCompilerFlag
    /module/CheckCSourceCompiles
@@ -60,6 +61,7 @@ All Modules
    /module/CPackIFW
    /module/CPackNSIS
    /module/CPackPackageMaker
+   /module/CPackProductBuild
    /module/CPackRPM
    /module/CPack
    /module/CPackWIX
@@ -120,6 +122,7 @@ All Modules
    /module/FindHTMLHelp
    /module/FindIce
    /module/FindIcotool
+   /module/FindICU
    /module/FindImageMagick
    /module/FindIntl
    /module/FindITK
@@ -209,6 +212,7 @@ All Modules
    /module/FindTIFF
    /module/FindUnixCommands
    /module/FindVTK
+   /module/FindVulkan
    /module/FindWget
    /module/FindWish
    /module/FindwxWidgets
diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst
index 43f4637..0cfe983 100644
--- a/Help/manual/cmake-policies.7.rst
+++ b/Help/manual/cmake-policies.7.rst
@@ -51,6 +51,14 @@ The :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable may also be used
 to determine whether to report an error on use of deprecated macros or
 functions.
 
+Policies Introduced by CMake 3.7
+================================
+
+.. toctree::
+   :maxdepth: 1
+
+   CMP0066: Honor per-config flags in try_compile() source-file signature. </policy/CMP0066>
+
 Policies Introduced by CMake 3.4
 ================================
 
diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst
index 3403dcd..271f497 100644
--- a/Help/manual/cmake-properties.7.rst
+++ b/Help/manual/cmake-properties.7.rst
@@ -24,6 +24,7 @@ Properties of Global Scope
    /prop_gbl/DISABLED_FEATURES
    /prop_gbl/ENABLED_FEATURES
    /prop_gbl/ENABLED_LANGUAGES
+   /prop_gbl/FIND_LIBRARY_USE_LIB32_PATHS
    /prop_gbl/FIND_LIBRARY_USE_LIB64_PATHS
    /prop_gbl/FIND_LIBRARY_USE_OPENBSD_VERSIONING
    /prop_gbl/GLOBAL_DEPENDS_DEBUG_MODE
@@ -53,6 +54,8 @@ Properties on Directories
    :maxdepth: 1
 
    /prop_dir/ADDITIONAL_MAKE_CLEAN_FILES
+   /prop_dir/BINARY_DIR
+   /prop_dir/BUILDSYSTEM_TARGETS
    /prop_dir/CACHE_VARIABLES
    /prop_dir/CLEAN_NO_CUSTOM
    /prop_dir/CMAKE_CONFIGURE_DEPENDS
@@ -72,6 +75,8 @@ Properties on Directories
    /prop_dir/RULE_LAUNCH_COMPILE
    /prop_dir/RULE_LAUNCH_CUSTOM
    /prop_dir/RULE_LAUNCH_LINK
+   /prop_dir/SOURCE_DIR
+   /prop_dir/SUBDIRECTORIES
    /prop_dir/TEST_INCLUDE_FILE
    /prop_dir/VARIABLES
    /prop_dir/VS_GLOBAL_SECTION_POST_section
@@ -217,6 +222,7 @@ Properties on Targets
    /prop_tgt/LINK_LIBRARIES
    /prop_tgt/LINK_SEARCH_END_STATIC
    /prop_tgt/LINK_SEARCH_START_STATIC
+   /prop_tgt/LINK_WHAT_YOU_USE
    /prop_tgt/LOCATION_CONFIG
    /prop_tgt/LOCATION
    /prop_tgt/MACOSX_BUNDLE_INFO_PLIST
@@ -274,6 +280,7 @@ Properties on Targets
    /prop_tgt/VS_SCC_LOCALPATH
    /prop_tgt/VS_SCC_PROJECTNAME
    /prop_tgt/VS_SCC_PROVIDER
+   /prop_tgt/VS_SDK_REFERENCES
    /prop_tgt/VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION
    /prop_tgt/VS_WINRT_COMPONENT
    /prop_tgt/VS_WINRT_EXTENSIONS
@@ -297,6 +304,9 @@ Properties on Tests
    /prop_test/DEPENDS
    /prop_test/ENVIRONMENT
    /prop_test/FAIL_REGULAR_EXPRESSION
+   /prop_test/FIXTURES_CLEANUP
+   /prop_test/FIXTURES_REQUIRED
+   /prop_test/FIXTURES_SETUP
    /prop_test/LABELS
    /prop_test/MEASUREMENT
    /prop_test/PASS_REGULAR_EXPRESSION
@@ -341,9 +351,11 @@ Properties on Source Files
    /prop_sf/VS_SHADER_FLAGS
    /prop_sf/VS_SHADER_MODEL
    /prop_sf/VS_SHADER_TYPE
+   /prop_sf/VS_TOOL_OVERRIDE.rst
    /prop_sf/VS_XAML_TYPE
    /prop_sf/WRAP_EXCLUDE
    /prop_sf/XCODE_EXPLICIT_FILE_TYPE
+   /prop_sf/XCODE_FILE_ATTRIBUTES
    /prop_sf/XCODE_LAST_KNOWN_FILE_TYPE
 
 .. _`Cache Entry Properties`:
diff --git a/Help/manual/cmake-server.7.rst b/Help/manual/cmake-server.7.rst
new file mode 100644
index 0000000..afd4e2b
--- /dev/null
+++ b/Help/manual/cmake-server.7.rst
@@ -0,0 +1,703 @@
+.. cmake-manual-description: CMake Server
+
+cmake-server(7)
+***************
+
+.. only:: html
+
+   .. contents::
+
+Introduction
+============
+
+:manual:`cmake(1)` is capable of providing semantic information about
+CMake code it executes to generate a buildsystem.  If executed with
+the ``-E server`` command line options, it starts in a long running mode
+and allows a client to request the available information via a JSON protocol.
+
+The protocol is designed to be useful to IDEs, refactoring tools, and
+other tools which have a need to understand the buildsystem in entirety.
+
+A single :manual:`cmake-buildsystem(7)` may describe buildsystem contents
+and build properties which differ based on
+:manual:`generation-time context <cmake-generator-expressions(7)>`
+including:
+
+* The Platform (eg, Windows, APPLE, Linux).
+* The build configuration (eg, Debug, Release, Coverage).
+* The Compiler (eg, MSVC, GCC, Clang) and compiler version.
+* The language of the source files compiled.
+* Available compile features (eg CXX variadic templates).
+* CMake policies.
+
+The protocol aims to provide information to tooling to satisfy several
+needs:
+
+#. Provide a complete and easily parsed source of all information relevant
+   to the tooling as it relates to the source code.  There should be no need
+   for tooling to parse generated buildsystems to access include directories
+   or compile definitions for example.
+#. Semantic information about the CMake buildsystem itself.
+#. Provide a stable interface for reading the information in the CMake cache.
+#. Information for determining when cmake needs to be re-run as a result of
+   file changes.
+
+
+Operation
+=========
+
+Start :manual:`cmake(1)` in the server command mode, supplying the path to
+the build directory to process::
+
+  cmake -E server (--debug|--pipe <NAMED_PIPE>)
+
+The server will communicate using stdin/stdout (with the ``--debug`` parameter)
+or using a named pipe (with the ``--pipe <NAMED_PIPE>`` parameter).
+
+When connecting to the server (via named pipe or by starting it in ``--debug``
+mode), the server will reply with a hello message::
+
+  [== CMake Server ==[
+  {"supportedProtocolVersions":[{"major":1,"minor":0}],"type":"hello"}
+  ]== CMake Server ==]
+
+Messages sent to and from the process are wrapped in magic strings::
+
+  [== CMake Server ==[
+  {
+    ... some JSON message ...
+  }
+  ]== CMake Server ==]
+
+The server is now ready to accept further requests via the named pipe
+or stdin.
+
+
+Debugging
+=========
+
+CMake server mode can be asked to provide statistics on execution times, etc.
+or to dump a copy of the response into a file. This is done passing a "debug"
+JSON object as a child of the request.
+
+The debug object supports the "showStats" key, which takes a boolean and makes
+the server mode return a "zzzDebug" object with stats as part of its response.
+"dumpToFile" takes a string value and will cause the cmake server to copy
+the response into the given filename.
+
+This is a response from the cmake server with "showStats" set to true::
+
+  [== CMake Server ==[
+  {
+    "cookie":"",
+    "errorMessage":"Waiting for type \"handshake\".",
+    "inReplyTo":"unknown",
+   "type":"error",
+    "zzzDebug": {
+      "dumpFile":"/tmp/error.txt",
+      "jsonSerialization":0.011016,
+      "size":111,
+      "totalTime":0.025995
+    }
+  }
+  ]== CMake Server ==]
+
+The server has made a copy of this response into the file /tmp/error.txt and
+took 0.011 seconds to turn the JSON response into a string, and it took 0.025
+seconds to process the request in total. The reply has a size of 111 bytes.
+
+
+Protocol API
+============
+
+
+General Message Layout
+----------------------
+
+All messages need to have a "type" value, which identifies the type of
+message that is passed back or forth. E.g. the initial message sent by the
+server is of type "hello". Messages without a type will generate an response
+of type "error".
+
+All requests sent to the server may contain a "cookie" value. This value
+will he handed back unchanged in all responses triggered by the request.
+
+All responses will contain a value "inReplyTo", which may be empty in
+case of parse errors, but will contain the type of the request message
+in all other cases.
+
+
+Type "reply"
+^^^^^^^^^^^^
+
+This type is used by the server to reply to requests.
+
+The message may -- depending on the type of the original request --
+contain values.
+
+Example::
+
+  [== CMake Server ==[
+  {"cookie":"zimtstern","inReplyTo":"handshake","type":"reply"}
+  ]== CMake Server ==]
+
+
+Type "error"
+^^^^^^^^^^^^
+
+This type is used to return an error condition to the client. It will
+contain an "errorMessage".
+
+Example::
+
+  [== CMake Server ==[
+  {"cookie":"","errorMessage":"Protocol version not supported.","inReplyTo":"handshake","type":"error"}
+  ]== CMake Server ==]
+
+
+Type "progress"
+^^^^^^^^^^^^^^^
+
+When the server is busy for a long time, it is polite to send back replies of
+type "progress" to the client. These will contain a "progressMessage" with a
+string describing the action currently taking place as well as
+"progressMinimum", "progressMaximum" and "progressCurrent" with integer values
+describing the range of progess.
+
+Messages of type "progress" will be followed by more "progress" messages or with
+a message of type "reply" or "error" that complete the request.
+
+"progress" messages may not be emitted after the "reply" or "error" message for
+the request that triggered the responses was delivered.
+
+
+Type "message"
+^^^^^^^^^^^^^^
+
+A message is triggered when the server processes a request and produces some
+form of output that should be displayed to the user. A Message has a "message"
+with the actual text to display as well as a "title" with a suggested dialog
+box title.
+
+Example::
+
+  [== CMake Server ==[
+  {"cookie":"","message":"Something happened.","title":"Title Text","inReplyTo":"handshake","type":"message"}
+  ]== CMake Server ==]
+
+
+Type "signal"
+^^^^^^^^^^^^^
+
+The server can send signals when it detects changes in the system state. Signals
+are of type "signal", have an empty "cookie" and "inReplyTo" field and always
+have a "name" set to show which signal was sent.
+
+
+Specific Signals
+----------------
+
+The cmake server may sent signals with the following names:
+
+"dirty" Signal
+^^^^^^^^^^^^^^
+
+The "dirty" signal is sent whenever the server determines that the configuration
+of the project is no longer up-to-date. This happens when any of the files that have
+an influence on the build system is changed.
+
+The "dirty" signal may look like this::
+
+  [== CMake Server ==[
+  {
+    "cookie":"",
+    "inReplyTo":"",
+    "name":"dirty",
+    "type":"signal"}
+  ]== CMake Server ==]
+
+
+"fileChange" Signal
+^^^^^^^^^^^^^^^^^^^
+
+The "fileChange" signal is sent whenever a watched file is changed. It contains
+the "path" that has changed and a list of "properties" with the kind of change
+that was detected. Possible changes are "change" and "rename".
+
+The "fileChange" signal looks like this::
+
+  [== CMake Server ==[
+  {
+    "cookie":"",
+    "inReplyTo":"",
+    "name":"fileChange",
+    "path":"/absolute/CMakeLists.txt",
+    "properties":["change"],
+    "type":"signal"}
+  ]== CMake Server ==]
+
+
+Specific Message Types
+----------------------
+
+
+Type "hello"
+^^^^^^^^^^^^
+
+The initial message send by the cmake server on startup is of type "hello".
+This is the only message ever sent by the server that is not of type "reply",
+"progress" or "error".
+
+It will contain "supportedProtocolVersions" with an array of server protocol
+versions supported by the cmake server. These are JSON objects with "major" and
+"minor" keys containing non-negative integer values.
+
+Example::
+
+  [== CMake Server ==[
+  {"supportedProtocolVersions":[{"major":0,"minor":1}],"type":"hello"}
+  ]== CMake Server ==]
+
+
+Type "handshake"
+^^^^^^^^^^^^^^^^
+
+The first request that the client may send to the server is of type "handshake".
+
+This request needs to pass one of the "supportedProtocolVersions" of the "hello"
+type response received earlier back to the server in the "protocolVersion" field.
+
+Each protocol version may request additional attributes to be present.
+
+Protocol version 1.0 requires the following attributes to be set:
+
+  * "sourceDirectory" with a path to the sources
+  * "buildDirectory" with a path to the build directory
+  * "generator" with the generator name
+  * "extraGenerator" (optional!) with the extra generator to be used.
+
+Example::
+
+  [== CMake Server ==[
+  {"cookie":"zimtstern","type":"handshake","protocolVersion":{"major":0},
+   "sourceDirectory":"/home/code/cmake", "buildDirectory":"/tmp/testbuild",
+   "generator":"Ninja"}
+  ]== CMake Server ==]
+
+which will result in a response type "reply"::
+
+  [== CMake Server ==[
+  {"cookie":"zimtstern","inReplyTo":"handshake","type":"reply"}
+  ]== CMake Server ==]
+
+indicating that the server is ready for action.
+
+
+Type "globalSettings"
+^^^^^^^^^^^^^^^^^^^^^
+
+This request can be sent after the initial handshake. It will return a
+JSON structure with information on cmake state.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"globalSettings"}
+  ]== CMake Server ==]
+
+which will result in a response type "reply"::
+
+  [== CMake Server ==[
+  {
+    "buildDirectory": "/tmp/test-build",
+    "capabilities": {
+      "generators": [
+        {
+          "extraGenerators": [],
+          "name": "Watcom WMake",
+          "platformSupport": false,
+          "toolsetSupport": false
+        },
+        <...>
+      ],
+      "serverMode": false,
+      "version": {
+        "isDirty": false,
+        "major": 3,
+        "minor": 6,
+        "patch": 20160830,
+        "string": "3.6.20160830-gd6abad",
+        "suffix": "gd6abad"
+      }
+    },
+    "checkSystemVars": false,
+    "cookie": "",
+    "extraGenerator": "",
+    "generator": "Ninja",
+    "debugOutput": false,
+    "inReplyTo": "globalSettings",
+    "sourceDirectory": "/home/code/cmake",
+    "trace": false,
+    "traceExpand": false,
+    "type": "reply",
+    "warnUninitialized": false,
+    "warnUnused": false,
+    "warnUnusedCli": true
+  }
+  ]== CMake Server ==]
+
+
+Type "setGlobalSettings"
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+This request can be sent to change the global settings attributes. Unknown
+attributes are going to be ignored. Read-only attributes reported by
+"globalSettings" are all capabilities, buildDirectory, generator,
+extraGenerator and sourceDirectory. Any attempt to set these will be ignored,
+too.
+
+All other settings will be changed.
+
+The server will respond with an empty reply message or an error.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"setGlobalSettings","debugOutput":true}
+  ]== CMake Server ==]
+
+CMake will reply to this with::
+
+  [== CMake Server ==[
+  {"inReplyTo":"setGlobalSettings","type":"reply"}
+  ]== CMake Server ==]
+
+
+Type "configure"
+^^^^^^^^^^^^^^^^
+
+This request will configure a project for build.
+
+To configure a build directory already containing cmake files, it is enough to
+set "buildDirectory" via "setGlobalSettings". To create a fresh build directory
+you also need to set "currentGenerator" and "sourceDirectory" via "setGlobalSettings"
+in addition to "buildDirectory".
+
+You may a list of strings to "configure" via the "cacheArguments" key. These
+strings will be interpreted similar to command line arguments related to
+cache handling that are passed to the cmake command line client.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"configure", "cacheArguments":["-Dsomething=else"]}
+  ]== CMake Server ==]
+
+CMake will reply like this (after reporting progress for some time)::
+
+  [== CMake Server ==[
+  {"cookie":"","inReplyTo":"configure","type":"reply"}
+  ]== CMake Server ==]
+
+
+Type "compute"
+^^^^^^^^^^^^^^
+
+This requist will generate build system files in the build directory and
+is only available after a project was successfully "configure"d.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"compute"}
+  ]== CMake Server ==]
+
+CMake will reply (after reporting progress information)::
+
+  [== CMake Server ==[
+  {"cookie":"","inReplyTo":"compute","type":"reply"}
+  ]== CMake Server ==]
+
+
+Type "codemodel"
+^^^^^^^^^^^^^^^^
+
+The "codemodel" request can be used after a project was "compute"d successfully.
+
+It will list the complete project structure as it is known to cmake.
+
+The reply will contain a key "projects", which will contain a list of
+project objects, one for each (sub-)project defined in the cmake build system.
+
+Each project object can have the following keys:
+
+"name"
+  contains the (sub-)projects name.
+"sourceDirectory"
+  contains the current source directory
+"buildDirectory"
+  contains the current build directory.
+"configurations"
+  contains a list of configuration objects.
+
+Configuration objects are used to destinquish between different
+configurations the build directory might have enabled. While most generators
+only support one configuration, others support several.
+
+Each configuration object can have the following keys:
+
+"name"
+  contains the name of the configuration. The name may be empty.
+"targets"
+  contains a list of target objects, one for each build target.
+
+Target objects define individual build targets for a certain configuration.
+
+Each target object can have the following keys:
+
+"name"
+  contains the name of the target.
+"type"
+  defines the type of build of the target. Possible values are
+  "STATIC_LIBRARY", "MODULE_LIBRARY", "SHARED_LIBRARY", "OBJECT_LIBRARY",
+  "EXECUTABLE", "UTILITY" and "INTERFACE_LIBRARY".
+"fullName"
+  contains the full name of the build result (incl. extensions, etc.).
+"sourceDirectory"
+  contains the current source directory.
+"buildDirectory"
+  contains the current build directory.
+"artifacts"
+  with a list of build artifacts. The list is sorted with the most
+  important artifacts first (e.g. a .DLL file is listed before a
+  .PDB file on windows).
+"linkerLanguage"
+  contains the language of the linker used to produce the artifact.
+"linkLibraries"
+  with a list of libraries to link to. This value is encoded in the
+  system's native shell format.
+"linkFlags"
+  with a list of flags to pass to the linker. This value is encoded in
+  the system's native shell format.
+"linkLanguageFlags"
+  with the flags for a compiler using the linkerLanguage. This value is
+  encoded in the system's native shell format.
+"frameworkPath"
+  with the framework path (on Apple computers). This value is encoded
+  in the system's native shell format.
+"linkPath"
+  with the link path. This value is encoded in the system's native shell
+  format.
+"sysroot"
+  with the sysroot path.
+"fileGroups"
+  contains the source files making up the target.
+
+FileGroups are used to group sources using similar settings together.
+
+Each fileGroup object may contain the following keys:
+
+"language"
+  contains the programming language used by all files in the group.
+"compileFlags"
+  with a string containing all the flags passed to the compiler
+  when building any of the files in this group. This value is encoded in
+  the system's native shell format.
+"includePath"
+  with a list of include paths. Each include path is an object
+  containing a "path" with the actual include path and "isSystem" with a bool
+  value informing whether this is a normal include or a system include. This
+  value is encoded in the system's native shell format.
+"defines"
+  with a list of defines in the form "SOMEVALUE" or "SOMEVALUE=42". This
+  value is encoded in the system's native shell format.
+"sources"
+  with a list of source files.
+
+All file paths in the fileGroup are either absolute or relative to the
+sourceDirectory of the target.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"project"}
+  ]== CMake Server ==]
+
+CMake will reply::
+
+  [== CMake Server ==[
+  {
+    "cookie":"",
+    "type":"reply",
+    "inReplyTo":"project",
+
+    "projects":
+    [
+      {
+        "name":"CMAKE_FORM",
+        "sourceDirectory":"/home/code/src/cmake/Source/CursesDialog/form"
+        "buildDirectory":"/tmp/cmake-build-test/Source/CursesDialog/form",
+        "configurations":
+        [
+          {
+            "name":"",
+            "targets":
+            [
+              {
+                "artifactDirectory":"/tmp/cmake/Source/CursesDialog/form",
+                "fileGroups":
+                [
+                  {
+                    "compileFlags":"  -std=gnu11",
+                    "defines":
+                    [
+                      "SOMETHING=1",
+                      "LIBARCHIVE_STATIC"
+                    ],
+                    "includePath":
+                    [
+                      { "path":"/tmp/cmake-build-test/Utilities" },
+                      { "isSystem": true, "path":"/usr/include/something" },
+                      ...
+                    ]
+                    "language":"C",
+                    "sources":
+                    [
+                      "fld_arg.c",
+                      ...
+                      "fty_regex.c"
+                    ]
+                  }
+                ],
+                "fullName":"libcmForm.a",
+                "linkerLanguage":"C",
+                "name":"cmForm",
+                "type":"STATIC_LIBRARY"
+              }
+            ]
+          }
+        ],
+      },
+      ...
+    ]
+  }
+  ]== CMake Server ==]
+
+The output can be tailored to the specific needs via parameter passed when
+requesting "project" information.
+
+You can have a "depth" key, which accepts "project", "configuration" and
+"target" as string values. These cause the output to be trimmed at the
+appropriate depth of the output tree.
+
+You can also set "configurations" to an array of strings with configuration
+names to list. This will cause any configuration that is not listed to be
+trimmed from the output.
+
+Generated files can be included in the listing by setting "includeGeneratedFiles"
+to "true". This setting defaults to "false", so generated files are not
+listed by default.
+
+Finally you can limit the target types that are going to be listed. This is
+done by providing a list of target types as an array of strings to the
+"targetTypes" key.
+
+
+Type "cmakeInputs"
+^^^^^^^^^^^^^^^^^^
+
+The "cmakeInputs" requests will report files used by CMake as part
+of the build system itself.
+
+This request is only available after a project was successfully
+"configure"d.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"cmakeInputs"}
+  ]== CMake Server ==]
+
+CMake will reply with the following information::
+
+  [== CMake Server ==[
+  {"buildFiles":
+    [
+      {"isCMake":true,"isTemporary":false,"sources":["/usr/lib/cmake/...", ... ]},
+      {"isCMake":false,"isTemporary":false,"sources":["CMakeLists.txt", ...]},
+      {"isCMake":false,"isTemporary":true,"sources":["/tmp/build/CMakeFiles/...", ...]}
+    ],
+    "cmakeRootDirectory":"/usr/lib/cmake",
+    "sourceDirectory":"/home/code/src/cmake",
+    "cookie":"",
+    "inReplyTo":"cmakeInputs",
+    "type":"reply"
+  }
+  ]== CMake Server ==]
+
+All file names are either relative to the top level source directory or
+absolute.
+
+The list of files which "isCMake" set to true are part of the cmake installation.
+
+The list of files witch "isTemporary" set to true are part of the build directory
+and will not survive the build directory getting cleaned out.
+
+
+Type "cache"
+^^^^^^^^^^^^
+
+The "cache" request can be used once a project is configured and will
+list the cached configuration values.
+
+Example::
+
+  [== CMake Server ==[
+  {"type":"cache"}
+  ]== CMake Server ==]
+
+CMake will respond with the following output::
+
+  [== CMake Server ==[
+  {
+    "cookie":"","inReplyTo":"cache","type":"reply",
+    "cache":
+    [
+      {
+        "key":"SOMEVALUE",
+        "properties":
+        {
+          "ADVANCED":"1",
+          "HELPSTRING":"This is not helpful"
+        }
+        "type":"STRING",
+        "value":"TEST"}
+    ]
+  }
+  ]== CMake Server ==]
+
+The output can be limited to a list of keys by passing an array of key names
+to the "keys" optional field of the "cache" request.
+
+
+Type "fileSystemWatchers"
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The server can watch the filesystem for changes. The "fileSystemWatchers"
+command will report on the files and directories watched.
+
+Example::
+
+  [== CMake Server ==]
+  {"type":"fileSystemWatchers"}
+  [== CMake Server ==]
+
+CMake will respond with the following output::
+
+  [== CMake Server ==]
+  {
+    "cookie":"","inReplyTo":"fileSystemWatchers","type":"reply",
+    "watchedFiles": [ "/absolute/path" ],
+    "watchedDirectories": [ "/absolute" ]
+  }
+  [== CMake Server ==]
diff --git a/Help/manual/cmake-toolchains.7.rst b/Help/manual/cmake-toolchains.7.rst
index 390220c..74eab2d 100644
--- a/Help/manual/cmake-toolchains.7.rst
+++ b/Help/manual/cmake-toolchains.7.rst
@@ -290,12 +290,206 @@ Windows Store may look like this:
   set(CMAKE_SYSTEM_NAME WindowsStore)
   set(CMAKE_SYSTEM_VERSION 8.1)
 
-Cross Compiling using NVIDIA Nsight Tegra
------------------------------------------
+.. _`Cross Compiling for Android`:
 
-A toolchain file to configure a Visual Studio generator to
-build using NVIDIA Nsight Tegra targeting Android may look
-like this:
+Cross Compiling for Android
+---------------------------
+
+A toolchain file may configure cross-compiling for Android by setting the
+:variable:`CMAKE_SYSTEM_NAME` variable to ``Android``.  Further configuration
+is specific to the Android development environment to be used.
+
+For :ref:`Visual Studio Generators`, CMake expects :ref:`NVIDIA Nsight Tegra
+Visual Studio Edition <Cross Compiling for Android with NVIDIA Nsight Tegra
+Visual Studio Edition>` to be installed.  See that section for further
+configuration details.
+
+For :ref:`Makefile Generators` and the :generator:`Ninja` generator,
+CMake expects one of these environments:
+
+* :ref:`NDK <Cross Compiling for Android with the NDK>`
+* :ref:`Standalone Toolchain <Cross Compiling for Android with a Standalone Toolchain>`
+
+CMake uses the following steps to select one of the environments:
+
+* If the :variable:`CMAKE_ANDROID_NDK` variable is set, the NDK at the
+  specified location will be used.
+
+* Else, if the :variable:`CMAKE_ANDROID_STANDALONE_TOOLCHAIN` variable
+  is set, the Standalone Toolchain at the specified location will be used.
+
+* Else, if the :variable:`CMAKE_SYSROOT` variable is set to a directory
+  of the form ``<ndk>/platforms/android-<api>/arch-<arch>``, the ``<ndk>``
+  part will be used as the value of :variable:`CMAKE_ANDROID_NDK` and the
+  NDK will be used.
+
+* Else, if the :variable:`CMAKE_SYSROOT` variable is set to a directory of the
+  form ``<standalone-toolchain>/sysroot``, the ``<standalone-toolchain>`` part
+  will be used as the value of :variable:`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`
+  and the Standalone Toolchain will be used.
+
+* Else, if a cmake variable ``ANDROID_NDK`` is set it will be used
+  as the value of :variable:`CMAKE_ANDROID_NDK`, and the NDK will be used.
+
+* Else, if a cmake variable ``ANDROID_STANDALONE_TOOLCHAIN`` is set, it will be
+  used as the value of :variable:`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`, and the
+  Standalone Toolchain will be used.
+
+* Else, if an environment variable ``ANDROID_NDK_ROOT`` or
+  ``ANDROID_NDK`` is set, it will be used as the value of
+  :variable:`CMAKE_ANDROID_NDK`, and the NDK will be used.
+
+* Else, if an environment variable ``ANDROID_STANDALONE_TOOLCHAIN`` is
+  set then it will be used as the value of
+  :variable:`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`, and the Standalone
+  Toolchain will be used.
+
+* Else, an error diagnostic will be issued that neither the NDK or
+  Standalone Toolchain can be found.
+
+.. _`Cross Compiling for Android with the NDK`:
+
+Cross Compiling for Android with the NDK
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A toolchain file may configure :ref:`Makefile Generators` or the
+:generator:`Ninja` generator to target Android for cross-compiling.
+
+Configure use of an Android NDK with the following variables:
+
+:variable:`CMAKE_SYSTEM_NAME`
+  Set to ``Android``.  Must be specified to enable cross compiling
+  for Android.
+
+:variable:`CMAKE_SYSTEM_VERSION`
+  Set to the Android API level.  If not specified, the value is
+  determined as follows:
+
+  * If the :variable:`CMAKE_ANDROID_API` variable is set, its value
+    is used as the API level.
+  * If the :variable:`CMAKE_SYSROOT` variable is set, the API level is
+    detected from the NDK directory structure containing the sysroot.
+  * Otherwise, the latest API level available in the NDK is used.
+
+:variable:`CMAKE_ANDROID_ARCH_ABI`
+  Set to the Android ABI (architecture).  If not specified, this
+  variable will default to ``armeabi``.
+  The :variable:`CMAKE_ANDROID_ARCH` variable will be computed
+  from ``CMAKE_ANDROID_ARCH_ABI`` automatically.
+  Also see the :variable:`CMAKE_ANDROID_ARM_MODE` and
+  :variable:`CMAKE_ANDROID_ARM_NEON` variables.
+
+:variable:`CMAKE_ANDROID_NDK`
+  Set to the absolute path to the Android NDK root directory.
+  A ``${CMAKE_ANDROID_NDK}/platforms`` directory must exist.
+  If not specified, a default for this variable will be chosen
+  as specified :ref:`above <Cross Compiling for Android>`.
+
+:variable:`CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION`
+  Set to the version of the NDK toolchain to be selected as the compiler.
+  If not specified, the latest available GCC toolchain will be used.
+
+:variable:`CMAKE_ANDROID_STL_TYPE`
+  Set to specify which C++ standard library to use.  If not specified,
+  a default will be selected as described in the variable documentation.
+
+The following variables will be computed and provided automatically:
+
+:variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`
+  The absolute path prefix to the binutils in the NDK toolchain.
+
+:variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`
+  The host platform suffix of the binutils in the NDK toolchain.
+
+
+For example, a toolchain file might contain:
+
+.. code-block:: cmake
+
+  set(CMAKE_SYSTEM_NAME Android)
+  set(CMAKE_SYSTEM_VERSION 21) # API level
+  set(CMAKE_ANDROID_ARCH_ABI arm64-v8a)
+  set(CMAKE_ANDROID_NDK /path/to/android-ndk)
+  set(CMAKE_ANDROID_STL_TYPE gnustl_static)
+
+Alternatively one may specify the values without a toolchain file:
+
+.. code-block:: console
+
+  $ cmake ../src \
+    -DCMAKE_SYSTEM_NAME=Android \
+    -DCMAKE_SYSTEM_VERSION=21 \
+    -DCMAKE_ANDROID_ARCH_ABI=arm64-v8a \
+    -DCMAKE_ANDROID_NDK=/path/to/android-ndk \
+    -DCMAKE_ANDROID_STL_TYPE=gnustl_static
+
+.. _`Cross Compiling for Android with a Standalone Toolchain`:
+
+Cross Compiling for Android with a Standalone Toolchain
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A toolchain file may configure :ref:`Makefile Generators` or the
+:generator:`Ninja` generator to target Android for cross-compiling
+using a standalone toolchain.
+
+Configure use of an Android standalone toolchain with the following variables:
+
+:variable:`CMAKE_SYSTEM_NAME`
+  Set to ``Android``.  Must be specified to enable cross compiling
+  for Android.
+
+:variable:`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`
+  Set to the absolute path to the standalone toolchain root directory.
+  A ``${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot`` directory
+  must exist.
+  If not specified, a default for this variable will be chosen
+  as specified :ref:`above <Cross Compiling for Android>`.
+
+:variable:`CMAKE_ANDROID_ARM_MODE`
+  When the standalone toolchain targets ARM, optionally set this to ``ON``
+  to target 32-bit ARM instead of 16-bit Thumb.
+  See variable documentation for details.
+
+:variable:`CMAKE_ANDROID_ARM_NEON`
+  When the standalone toolchain targets ARM v7, optionally set thisto ``ON``
+  to target ARM NEON devices.  See variable documentation for details.
+
+The following variables will be computed and provided automatically:
+
+:variable:`CMAKE_SYSTEM_VERSION`
+  The Android API level detected from the standalone toolchain.
+
+:variable:`CMAKE_ANDROID_ARCH_ABI`
+  The Android ABI detected from the standalone toolchain.
+
+:variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`
+  The absolute path prefix to the binutils in the standalone toolchain.
+
+:variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`
+  The host platform suffix of the binutils in the standalone toolchain.
+
+For example, a toolchain file might contain:
+
+.. code-block:: cmake
+
+  set(CMAKE_SYSTEM_NAME Android)
+  set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN /path/to/android-toolchain)
+
+Alternatively one may specify the values without a toolchain file:
+
+.. code-block:: console
+
+  $ cmake ../src \
+    -DCMAKE_SYSTEM_NAME=Android \
+    -DCMAKE_ANDROID_STANDALONE_TOOLCHAIN=/path/to/android-toolchain
+
+.. _`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition`:
+
+Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio Edition
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A toolchain file to configure one of the :ref:`Visual Studio Generators`
+to build using NVIDIA Nsight Tegra targeting Android may look like this:
 
 .. code-block:: cmake
 
diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst
index 85b8eae..b74f867 100644
--- a/Help/manual/cmake-variables.7.rst
+++ b/Help/manual/cmake-variables.7.rst
@@ -38,6 +38,8 @@ Variables that Provide Information
    /variable/CMAKE_EXTRA_GENERATOR
    /variable/CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES
    /variable/CMAKE_FIND_PACKAGE_NAME
+   /variable/CMAKE_FIND_PACKAGE_SORT_DIRECTION
+   /variable/CMAKE_FIND_PACKAGE_SORT_ORDER
    /variable/CMAKE_GENERATOR
    /variable/CMAKE_GENERATOR_PLATFORM
    /variable/CMAKE_GENERATOR_TOOLSET
@@ -110,6 +112,7 @@ Variables that Change Behavior
    /variable/CMAKE_AUTOMOC_RELAXED_MODE
    /variable/CMAKE_BACKWARDS_COMPATIBILITY
    /variable/CMAKE_BUILD_TYPE
+   /variable/CMAKE_CODELITE_USE_TARGETS
    /variable/CMAKE_COLOR_MAKEFILE
    /variable/CMAKE_CONFIGURATION_TYPES
    /variable/CMAKE_DEBUG_TARGET_PROPERTIES
@@ -173,6 +176,7 @@ Variables that Describe the System
 .. toctree::
    :maxdepth: 1
 
+   /variable/ANDROID
    /variable/APPLE
    /variable/BORLAND
    /variable/CMAKE_CL_64
@@ -213,6 +217,7 @@ Variables that Describe the System
    /variable/WINCE
    /variable/WINDOWS_PHONE
    /variable/WINDOWS_STORE
+   /variable/XCODE
    /variable/XCODE_VERSION
 
 Variables that Control the Build
@@ -225,6 +230,9 @@ Variables that Control the Build
    /variable/CMAKE_ANDROID_API
    /variable/CMAKE_ANDROID_API_MIN
    /variable/CMAKE_ANDROID_ARCH
+   /variable/CMAKE_ANDROID_ARCH_ABI
+   /variable/CMAKE_ANDROID_ARM_MODE
+   /variable/CMAKE_ANDROID_ARM_NEON
    /variable/CMAKE_ANDROID_ASSETS_DIRECTORIES
    /variable/CMAKE_ANDROID_GUI
    /variable/CMAKE_ANDROID_JAR_DEPENDENCIES
@@ -232,11 +240,14 @@ Variables that Control the Build
    /variable/CMAKE_ANDROID_JAVA_SOURCE_DIR
    /variable/CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES
    /variable/CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES
+   /variable/CMAKE_ANDROID_NDK
+   /variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION
    /variable/CMAKE_ANDROID_PROCESS_MAX
    /variable/CMAKE_ANDROID_PROGUARD
    /variable/CMAKE_ANDROID_PROGUARD_CONFIG_PATH
    /variable/CMAKE_ANDROID_SECURE_PROPS_PATH
    /variable/CMAKE_ANDROID_SKIP_ANT_STEP
+   /variable/CMAKE_ANDROID_STANDALONE_TOOLCHAIN
    /variable/CMAKE_ANDROID_STL_TYPE
    /variable/CMAKE_ARCHIVE_OUTPUT_DIRECTORY
    /variable/CMAKE_ARCHIVE_OUTPUT_DIRECTORY_CONFIG
@@ -253,7 +264,9 @@ Variables that Control the Build
    /variable/CMAKE_DEBUG_POSTFIX
    /variable/CMAKE_ENABLE_EXPORTS
    /variable/CMAKE_EXE_LINKER_FLAGS_CONFIG
+   /variable/CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT
    /variable/CMAKE_EXE_LINKER_FLAGS
+   /variable/CMAKE_EXE_LINKER_FLAGS_INIT
    /variable/CMAKE_Fortran_FORMAT
    /variable/CMAKE_Fortran_MODULE_DIRECTORY
    /variable/CMAKE_GNUtoMS
@@ -275,11 +288,14 @@ Variables that Control the Build
    /variable/CMAKE_LINK_INTERFACE_LIBRARIES
    /variable/CMAKE_LINK_LIBRARY_FILE_FLAG
    /variable/CMAKE_LINK_LIBRARY_FLAG
+   /variable/CMAKE_LINK_WHAT_YOU_USE
    /variable/CMAKE_MACOSX_BUNDLE
    /variable/CMAKE_MACOSX_RPATH
    /variable/CMAKE_MAP_IMPORTED_CONFIG_CONFIG
    /variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG
+   /variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT
    /variable/CMAKE_MODULE_LINKER_FLAGS
+   /variable/CMAKE_MODULE_LINKER_FLAGS_INIT
    /variable/CMAKE_NINJA_OUTPUT_PATH_PREFIX
    /variable/CMAKE_NO_BUILTIN_CHRPATH
    /variable/CMAKE_NO_SYSTEM_FROM_IMPORTED
@@ -292,11 +308,15 @@ Variables that Control the Build
    /variable/CMAKE_RUNTIME_OUTPUT_DIRECTORY
    /variable/CMAKE_RUNTIME_OUTPUT_DIRECTORY_CONFIG
    /variable/CMAKE_SHARED_LINKER_FLAGS_CONFIG
+   /variable/CMAKE_SHARED_LINKER_FLAGS_CONFIG_INIT
    /variable/CMAKE_SHARED_LINKER_FLAGS
+   /variable/CMAKE_SHARED_LINKER_FLAGS_INIT
    /variable/CMAKE_SKIP_BUILD_RPATH
    /variable/CMAKE_SKIP_INSTALL_RPATH
    /variable/CMAKE_STATIC_LINKER_FLAGS_CONFIG
+   /variable/CMAKE_STATIC_LINKER_FLAGS_CONFIG_INIT
    /variable/CMAKE_STATIC_LINKER_FLAGS
+   /variable/CMAKE_STATIC_LINKER_FLAGS_INIT
    /variable/CMAKE_TRY_COMPILE_CONFIGURATION
    /variable/CMAKE_TRY_COMPILE_PLATFORM_VARIABLES
    /variable/CMAKE_TRY_COMPILE_TARGET_TYPE
@@ -315,7 +335,9 @@ Variables for Languages
 .. toctree::
    :maxdepth: 1
 
-   /variable/CMAKE_COMPILER_IS_GNULANG
+   /variable/CMAKE_COMPILER_IS_GNUCC
+   /variable/CMAKE_COMPILER_IS_GNUCXX
+   /variable/CMAKE_COMPILER_IS_GNUG77
    /variable/CMAKE_C_COMPILE_FEATURES
    /variable/CMAKE_C_EXTENSIONS
    /variable/CMAKE_C_STANDARD
@@ -328,6 +350,8 @@ Variables for Languages
    /variable/CMAKE_Fortran_MODDIR_FLAG
    /variable/CMAKE_Fortran_MODOUT_FLAG
    /variable/CMAKE_INTERNAL_PLATFORM_ABI
+   /variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX
+   /variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX
    /variable/CMAKE_LANG_ARCHIVE_APPEND
    /variable/CMAKE_LANG_ARCHIVE_CREATE
    /variable/CMAKE_LANG_ARCHIVE_FINISH
@@ -343,10 +367,15 @@ Variables for Languages
    /variable/CMAKE_LANG_CREATE_SHARED_MODULE
    /variable/CMAKE_LANG_CREATE_STATIC_LIBRARY
    /variable/CMAKE_LANG_FLAGS_DEBUG
+   /variable/CMAKE_LANG_FLAGS_DEBUG_INIT
    /variable/CMAKE_LANG_FLAGS_MINSIZEREL
+   /variable/CMAKE_LANG_FLAGS_MINSIZEREL_INIT
    /variable/CMAKE_LANG_FLAGS_RELEASE
+   /variable/CMAKE_LANG_FLAGS_RELEASE_INIT
    /variable/CMAKE_LANG_FLAGS_RELWITHDEBINFO
+   /variable/CMAKE_LANG_FLAGS_RELWITHDEBINFO_INIT
    /variable/CMAKE_LANG_FLAGS
+   /variable/CMAKE_LANG_FLAGS_INIT
    /variable/CMAKE_LANG_GHS_KERNEL_FLAGS_DEBUG
    /variable/CMAKE_LANG_GHS_KERNEL_FLAGS_MINSIZEREL
    /variable/CMAKE_LANG_GHS_KERNEL_FLAGS_RELEASE
@@ -368,6 +397,7 @@ Variables for Languages
    /variable/CMAKE_LANG_SOURCE_FILE_EXTENSIONS
    /variable/CMAKE_LANG_STANDARD_INCLUDE_DIRECTORIES
    /variable/CMAKE_LANG_STANDARD_LIBRARIES
+   /variable/CMAKE_Swift_LANGUAGE_VERSION
    /variable/CMAKE_USER_MAKE_RULES_OVERRIDE_LANG
 
 Variables for CTest
diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst
index 65153af..063aea1 100644
--- a/Help/manual/cmake.1.rst
+++ b/Help/manual/cmake.1.rst
@@ -108,6 +108,11 @@ Options
 
  Like ``--trace``, but with variables expanded.
 
+``--trace-source=<file>``
+ Put cmake in trace mode, but output only lines of a specified file.
+
+ Multiple options are allowed.
+
 ``--warn-uninitialized``
  Warn about uninitialized values.
 
@@ -175,6 +180,43 @@ CMake provides builtin command-line tools through the signature::
 Run ``cmake -E`` or ``cmake -E help`` for a summary of commands.
 Available commands are:
 
+``capabilities``
+  Report cmake capabilities in JSON format. The output is a JSON object
+  with the following keys:
+
+  ``version``
+    A JSON object with version information. Keys are:
+
+    ``string``
+      The full version string as displayed by cmake ``--version``.
+    ``major``
+      The major version number in integer form.
+    ``minor``
+      The minor version number in integer form.
+    ``patch``
+      The patch level in integer form.
+    ``suffix``
+      The cmake version suffix string.
+    ``isDirty``
+      A bool that is set if the cmake build is from a dirty tree.
+
+  ``generators``
+    A list available generators. Each generator is a JSON object with the
+    following keys:
+
+    ``name``
+      A string containing the name of the generator.
+    ``toolsetSupport``
+      ``true`` if the generator supports toolsets and ``false`` otherwise.
+    ``platformSupport``
+      ``true`` if the generator supports platforms and ``false`` otherwise.
+    ``extraGenerators``
+      A list of strings with all the extra generators compatible with
+      the generator.
+
+  ``serverMode``
+    ``true`` if cmake supports server-mode and ``false`` otherwise.
+
 ``chdir <dir> <cmd> [<arg>...]``
   Change the current working directory and run a command.
 
@@ -231,6 +273,9 @@ Available commands are:
 ``rename <oldname> <newname>``
   Rename a file or directory (on one volume).
 
+``server``
+  Launch :manual:`cmake-server(7)` mode.
+
 ``sleep <number>...``
   Sleep for given number of seconds.
 
diff --git a/Help/manual/ctest.1.rst b/Help/manual/ctest.1.rst
index e797333..ce81578 100644
--- a/Help/manual/ctest.1.rst
+++ b/Help/manual/ctest.1.rst
@@ -56,7 +56,7 @@ Options
  Enable failover.
 
  This option allows ctest to resume a test set execution that was
- previously interrupted.  If no interruption occurred, the -F option
+ previously interrupted.  If no interruption occurred, the ``-F`` option
  will have no effect.
 
 ``-j <jobs>, --parallel <jobs>``
@@ -77,12 +77,12 @@ Options
  Make ctest quiet.
 
  This option will suppress all the output.  The output log file will
- still be generated if the --output-log is specified.  Options such
- as --verbose, --extra-verbose, and --debug are ignored if --quiet is
- specified.
+ still be generated if the ``--output-log`` is specified.  Options such
+ as ``--verbose``, ``--extra-verbose``, and ``--debug`` are ignored
+ if ``--quiet`` is specified.
 
 ``-O <file>, --output-log <file>``
- Output to log file
+ Output to log file.
 
  This option tells ctest to write all its output to a log file.
 
@@ -90,7 +90,7 @@ Options
  Disable actual execution of tests.
 
  This option tells ctest to list the tests that would be run but not
- actually run them.  Useful in conjunction with the -R and -E
+ actually run them.  Useful in conjunction with the ``-R`` and ``-E``
  options.
 
 ``-L <regex>, --label-regex <regex>``
@@ -118,7 +118,7 @@ Options
  given regular expression.
 
 ``-D <dashboard>, --dashboard <dashboard>``
- Execute dashboard test
+ Execute dashboard test.
 
  This option tells ctest to act as a CDash client and perform a
  dashboard test.  All tests are <Mode><Test>, where Mode can be
@@ -126,26 +126,27 @@ Options
  Update, Configure, Build, Test, Coverage, and Submit.
 
 ``-D <var>:<type>=<value>``
- Define a variable for script mode
+ Define a variable for script mode.
 
  Pass in variable values on the command line.  Use in conjunction
- with -S to pass variable values to a dashboard script.  Parsing -D
+ with ``-S`` to pass variable values to a dashboard script.  Parsing ``-D``
  arguments as variable values is only attempted if the value
- following -D does not match any of the known dashboard types.
+ following ``-D`` does not match any of the known dashboard types.
 
 ``-M <model>, --test-model <model>``
- Sets the model for a dashboard
+ Sets the model for a dashboard.
 
- This option tells ctest to act as a CDash client where the TestModel
- can be Experimental, Nightly, and Continuous.  Combining -M and -T
- is similar to -D
+ This option tells ctest to act as a CDash client where the ``<model>``
+ can be ``Experimental``, ``Nightly``, and ``Continuous``.
+ Combining ``-M`` and ``-T`` is similar to ``-D``.
 
 ``-T <action>, --test-action <action>``
- Sets the dashboard action to perform
+ Sets the dashboard action to perform.
 
  This option tells ctest to act as a CDash client and perform some
- action such as start, build, test etc.  Combining -M and -T is
- similar to -D
+ action such as ``start``, ``build``, ``test`` etc. See
+ `Dashboard Client Steps`_ for the full list of actions.
+ Combining ``-M`` and ``-T`` is similar to ``-D``.
 
 ``--track <track>``
  Specify the track to submit dashboard to
@@ -156,24 +157,24 @@ Options
  arbitrary.
 
 ``-S <script>, --script <script>``
- Execute a dashboard for a configuration
+ Execute a dashboard for a configuration.
 
  This option tells ctest to load in a configuration script which sets
  a number of parameters such as the binary and source directories.
  Then ctest will do what is required to create and run a dashboard.
- This option basically sets up a dashboard and then runs ctest -D
+ This option basically sets up a dashboard and then runs ``ctest -D``
  with the appropriate options.
 
 ``-SP <script>, --script-new-process <script>``
- Execute a dashboard for a configuration
+ Execute a dashboard for a configuration.
 
- This option does the same operations as -S but it will do them in a
+ This option does the same operations as ``-S`` but it will do them in a
  separate process.  This is primarily useful in cases where the
  script may modify the environment and you do not want the modified
- environment to impact other -S scripts.
+ environment to impact other ``-S`` scripts.
 
 ``-A <file>, --add-notes <file>``
- Add a notes file with submission
+ Add a notes file with submission.
 
  This option tells ctest to include a notes file when submitting
  dashboard.
@@ -188,19 +189,19 @@ Options
  contains the same syntax as the command line.
 
 ``-U, --union``
- Take the Union of -I and -R
+ Take the Union of ``-I`` and ``-R``.
 
- When both -R and -I are specified by default the intersection of
- tests are run.  By specifying -U the union of tests is run instead.
+ When both ``-R`` and ``-I`` are specified by default the intersection of
+ tests are run.  By specifying ``-U`` the union of tests is run instead.
 
 ``--rerun-failed``
- Run only the tests that failed previously
+ Run only the tests that failed previously.
 
  This option tells ctest to perform only the tests that failed during
  its previous run.  When this option is specified, ctest ignores all
- other options intended to modify the list of tests to run (-L, -R,
- -E, -LE, -I, etc).  In the event that CTest runs and no tests fail,
- subsequent calls to ctest with the --rerun-failed option will run
+ other options intended to modify the list of tests to run (``-L``, ``-R``,
+ ``-E``, ``-LE``, ``-I``, etc).  In the event that CTest runs and no tests
+ fail, subsequent calls to ctest with the ``--rerun-failed`` option will run
  the set of tests that most recently failed (if any).
 
 ``--repeat-until-fail <n>``
@@ -209,7 +210,7 @@ Options
  This is useful in finding sporadic failures in test cases.
 
 ``--max-width <width>``
- Set the max width for a test name to output
+ Set the max width for a test name to output.
 
  Set the maximum width for each test name to show in the output.
  This allows the user to widen the output to avoid clipping the test
@@ -232,26 +233,25 @@ Options
  label associated with the tests run.  If there are no labels on the
  tests, nothing extra is printed.
 
-``--build-and-test``
+``--build-and-test <path-to-source> <path-to-build>``
  Configure, build and run a test.
 
  This option tells ctest to configure (i.e.  run cmake on), build,
  and or execute a test.  The configure and test steps are optional.
  The arguments to this command line are the source and binary
- directories.  By default this will run CMake on the Source/Bin
- directories specified unless --build-nocmake is specified.
- The --build-generator option *must* be provided to use
- --build-and-test.  If --test-command is specified then that will be
+ directories.
+ The ``--build-generator`` option *must* be provided to use
+ ``--build-and-test``.  If ``--test-command`` is specified then that will be
  run after the build is complete.  Other options that affect this
- mode are --build-target --build-nocmake, --build-run-dir,
- --build-two-config, --build-exe-dir,
- --build-project,--build-noclean, --build-options
+ mode are ``--build-target``, ``--build-nocmake``, ``--build-run-dir``,
+ ``--build-two-config``, ``--build-exe-dir``,
+ ``--build-project``, ``--build-noclean`` and ``--build-options``.
 
 ``--build-target``
  Specify a specific target to build.
 
- This option goes with the --build-and-test option, if left out the
- all target is built.
+ This option goes with the ``--build-and-test`` option, if left out the
+ ``all`` target is built.
 
 ``--build-nocmake``
  Run the build without running cmake first.
@@ -264,13 +264,13 @@ Options
  Directory where programs will be after it has been compiled.
 
 ``--build-two-config``
- Run CMake twice
+ Run CMake twice.
 
 ``--build-exe-dir``
  Specify the directory for the executable.
 
 ``--build-generator``
- Specify the generator to use.
+ Specify the generator to use. See the :manual:`cmake-generators(7)` manual.
 
 ``--build-generator-platform``
  Specify the generator-specific platform.
@@ -288,25 +288,23 @@ Options
  Skip the make clean step.
 
 ``--build-config-sample``
- A sample executable to use to determine the configuration
-
  A sample executable to use to determine the configuration that
- should be used.  e.g.  Debug/Release/etc
+ should be used.  e.g.  Debug/Release/etc.
 
 ``--build-options``
  Add extra options to the build step.
 
  This option must be the last option with the exception of
- --test-command
+ ``--test-command``
 
 ``--test-command``
- The test to run with the --build-and-test option.
+ The test to run with the ``--build-and-test`` option.
 
 ``--test-output-size-passed <size>``
- Limit the output for passed tests to <size> bytes.
+ Limit the output for passed tests to ``<size>`` bytes.
 
 ``--test-output-size-failed <size>``
- Limit the output for failed tests to <size> bytes.
+ Limit the output for failed tests to ``<size>`` bytes.
 
 ``--test-timeout``
  The time limit in seconds, internal use only.
@@ -335,14 +333,14 @@ Options
  This option will submit extra files to the dashboard.
 
 ``--force-new-ctest-process``
- Run child CTest instances as new processes
+ Run child CTest instances as new processes.
 
  By default CTest will run child CTest instances within the same
  process.  If this behavior is not desired, this argument will
  enforce new processes for child CTest processes.
 
 ``--schedule-random``
- Use a random order for scheduling tests
+ Use a random order for scheduling tests.
 
  This option will run the tests in a random order.  It is commonly
  used to detect implicit dependencies in a test suite.
@@ -361,7 +359,7 @@ Options
  Set a time at which all tests should stop running.
 
  Set a real time of day at which all tests should timeout.  Example:
- 7:00:00 -0400.  Any time format understood by the curl date parser
+ ``7:00:00 -0400``.  Any time format understood by the curl date parser
  is accepted.  Local time is assumed if no timezone is specified.
 
 ``--http1.0``
diff --git a/Help/module/AndroidTestUtilities.rst b/Help/module/AndroidTestUtilities.rst
new file mode 100644
index 0000000..e7ec864
--- /dev/null
+++ b/Help/module/AndroidTestUtilities.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/AndroidTestUtilities.cmake
diff --git a/Help/module/CPackProductBuild.rst b/Help/module/CPackProductBuild.rst
new file mode 100644
index 0000000..6081fe4
--- /dev/null
+++ b/Help/module/CPackProductBuild.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CPackProductBuild.cmake
diff --git a/Help/module/FindICU.rst b/Help/module/FindICU.rst
new file mode 100644
index 0000000..ee3f4a9
--- /dev/null
+++ b/Help/module/FindICU.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindICU.cmake
diff --git a/Help/module/FindVulkan.rst b/Help/module/FindVulkan.rst
new file mode 100644
index 0000000..adf824e
--- /dev/null
+++ b/Help/module/FindVulkan.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindVulkan.cmake
diff --git a/Help/policy/CMP0066.rst b/Help/policy/CMP0066.rst
new file mode 100644
index 0000000..d1dcb0e
--- /dev/null
+++ b/Help/policy/CMP0066.rst
@@ -0,0 +1,27 @@
+CMP0066
+-------
+
+Honor per-config flags in :command:`try_compile` source-file signature.
+
+The source file signature of the :command:`try_compile` command uses the value
+of the :variable:`CMAKE_<LANG>_FLAGS` variable in the test project so that the
+test compilation works as it would in the main project.  However, CMake 3.6 and
+below do not also honor config-specific compiler flags such as those in the
+:variable:`CMAKE_<LANG>_FLAGS_DEBUG` variable.  CMake 3.7 and above prefer to
+honor config-specific compiler flags too.  This policy provides compatibility
+for projects that do not expect config-specific compiler flags to be used.
+
+The ``OLD`` behavior of this policy is to ignore config-specific flag
+variables like :variable:`CMAKE_<LANG>_FLAGS_DEBUG` and only use CMake's
+built-in defaults for the current compiler and platform.
+
+The ``NEW`` behavior of this policy is to honor config-specific flag
+variabldes like :variable:`CMAKE_<LANG>_FLAGS_DEBUG`.
+
+This policy was introduced in CMake version 3.7.  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_CMP0066 <CMAKE_POLICY_WARNING_CMP<NNNN>>`
+variable to control the warning.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/prop_dir/BINARY_DIR.rst b/Help/prop_dir/BINARY_DIR.rst
new file mode 100644
index 0000000..597c79a
--- /dev/null
+++ b/Help/prop_dir/BINARY_DIR.rst
@@ -0,0 +1,5 @@
+BINARY_DIR
+----------
+
+This read-only directory property reports absolute path to the binary
+directory corresponding to the source on which it is read.
diff --git a/Help/prop_dir/BUILDSYSTEM_TARGETS.rst b/Help/prop_dir/BUILDSYSTEM_TARGETS.rst
new file mode 100644
index 0000000..da907cb
--- /dev/null
+++ b/Help/prop_dir/BUILDSYSTEM_TARGETS.rst
@@ -0,0 +1,11 @@
+BUILDSYSTEM_TARGETS
+-------------------
+
+This read-only directory property contains a
+:ref:`;-list <CMake Language Lists>` of buildsystem targets added in the
+directory by calls to the :command:`add_library`, :command:`add_executable`,
+and :command:`add_custom_target` commands.  The list does not include any
+:ref:`Imported Targets` or :ref:`Alias Targets`, but does include
+:ref:`Interface Libraries`.  Each entry in the list is the logical name
+of a target, suitable to pass to the :command:`get_property` command
+``TARGET`` option.
diff --git a/Help/prop_dir/SOURCE_DIR.rst b/Help/prop_dir/SOURCE_DIR.rst
new file mode 100644
index 0000000..ac98c3b
--- /dev/null
+++ b/Help/prop_dir/SOURCE_DIR.rst
@@ -0,0 +1,5 @@
+SOURCE_DIR
+----------
+
+This read-only directory property reports absolute path to the source
+directory on which it is read.
diff --git a/Help/prop_dir/SUBDIRECTORIES.rst b/Help/prop_dir/SUBDIRECTORIES.rst
new file mode 100644
index 0000000..2c2ea77
--- /dev/null
+++ b/Help/prop_dir/SUBDIRECTORIES.rst
@@ -0,0 +1,15 @@
+SUBDIRECTORIES
+--------------
+
+This read-only directory property contains a
+:ref:`;-list <CMake Language Lists>` of subdirectories processed so far by
+the :command:`add_subdirectory` or :command:`subdirs` commands.  Each entry is
+the absolute path to the source directory (containing the ``CMakeLists.txt``
+file).  This is suitable to pass to the :command:`get_property` command
+``DIRECTORY`` option.
+
+.. note::
+
+  The :command:`subdirs` command does not process its arguments until
+  after the calling directory is fully processed.  Therefore looking
+  up this property in the current directory will not see them.
diff --git a/Help/prop_gbl/FIND_LIBRARY_USE_LIB32_PATHS.rst b/Help/prop_gbl/FIND_LIBRARY_USE_LIB32_PATHS.rst
new file mode 100644
index 0000000..ce18b65
--- /dev/null
+++ b/Help/prop_gbl/FIND_LIBRARY_USE_LIB32_PATHS.rst
@@ -0,0 +1,10 @@
+FIND_LIBRARY_USE_LIB32_PATHS
+----------------------------
+
+Whether the :command:`find_library` command should automatically search
+``lib32`` directories.
+
+``FIND_LIBRARY_USE_LIB32_PATHS`` is a boolean specifying whether the
+:command:`find_library` command should automatically search the ``lib32``
+variant of directories called ``lib`` in the search path when building 32-bit
+binaries.
diff --git a/Help/prop_sf/VS_TOOL_OVERRIDE.rst b/Help/prop_sf/VS_TOOL_OVERRIDE.rst
new file mode 100644
index 0000000..8bdc5ca
--- /dev/null
+++ b/Help/prop_sf/VS_TOOL_OVERRIDE.rst
@@ -0,0 +1,5 @@
+VS_TOOL_OVERRIDE
+----------------
+
+Override the default Visual Studio tool that will be applied to the source file
+with a new tool not based on the extension of the file.
diff --git a/Help/prop_sf/XCODE_FILE_ATTRIBUTES.rst b/Help/prop_sf/XCODE_FILE_ATTRIBUTES.rst
new file mode 100644
index 0000000..39e6966
--- /dev/null
+++ b/Help/prop_sf/XCODE_FILE_ATTRIBUTES.rst
@@ -0,0 +1,11 @@
+XCODE_FILE_ATTRIBUTES
+---------------------
+
+Add values to the Xcode ``ATTRIBUTES`` setting on its reference to a
+source file.  Among other things, this can be used to set the role on
+a mig file::
+
+  set_source_files_properties(defs.mig
+      PROPERTIES
+          XCODE_FILE_ATTRIBUTES "Client;Server"
+  )
diff --git a/Help/prop_test/DEPENDS.rst b/Help/prop_test/DEPENDS.rst
index ee946d9..89c7553 100644
--- a/Help/prop_test/DEPENDS.rst
+++ b/Help/prop_test/DEPENDS.rst
@@ -3,4 +3,8 @@ DEPENDS
 
 Specifies that this test should only be run after the specified list of tests.
 
-Set this to a list of tests that must finish before this test is run.
+Set this to a list of tests that must finish before this test is run. The
+results of those tests are not considered, the dependency relationship is
+purely for order of execution (i.e. it is really just a *run after*
+relationship). Consider using test fixtures with setup tests if a dependency
+with successful completion is required (see :prop_test:`FIXTURES_REQUIRED`).
diff --git a/Help/prop_test/FIXTURES_CLEANUP.rst b/Help/prop_test/FIXTURES_CLEANUP.rst
new file mode 100644
index 0000000..f0a4be0
--- /dev/null
+++ b/Help/prop_test/FIXTURES_CLEANUP.rst
@@ -0,0 +1,46 @@
+FIXTURES_CLEANUP
+----------------
+
+Specifies a list of fixtures for which the test is to be treated as a cleanup
+test.
+
+Fixture cleanup tests are ordinary tests with all of the usual test
+functionality. Setting the ``FIXTURES_CLEANUP`` property for a test has two
+primary effects:
+
+- CTest will ensure the test executes after all other tests which list any of
+  the fixtures in its :prop_test:`FIXTURES_REQUIRED` property.
+
+- If CTest is asked to run only a subset of tests (e.g. using regular
+  expressions or the ``--rerun-failed`` option) and the cleanup test is not in
+  the set of tests to run, it will automatically be added if any tests in the
+  set require any fixture listed in ``FIXTURES_CLEANUP``.
+
+A cleanup test can have multiple fixtures listed in its ``FIXTURES_CLEANUP``
+property. It will execute only once for the whole CTest run, not once for each
+fixture. A fixture can also have more than one cleanup test defined. If there
+are multiple cleanup tests for a fixture, projects can control their order with
+the usual :prop_test:`DEPENDS` test property if necessary.
+
+A cleanup test is allowed to require other fixtures, but not any fixture listed
+in its ``FIXTURES_CLEANUP`` property. For example:
+
+.. code-block:: cmake
+
+  # Ok: Dependent fixture is different to cleanup
+  set_tests_properties(cleanupFoo PROPERTIES
+    FIXTURES_CLEANUP  Foo
+    FIXTURES_REQUIRED Bar
+  )
+
+  # Error: cannot require same fixture as cleanup
+  set_tests_properties(cleanupFoo PROPERTIES
+    FIXTURES_CLEANUP  Foo
+    FIXTURES_REQUIRED Foo
+  )
+
+Cleanup tests will execute even if setup or regular tests for that fixture fail
+or are skipped.
+
+See :prop_test:`FIXTURES_REQUIRED` for a more complete discussion of how to use
+test fixtures.
diff --git a/Help/prop_test/FIXTURES_REQUIRED.rst b/Help/prop_test/FIXTURES_REQUIRED.rst
new file mode 100644
index 0000000..e37dfb5
--- /dev/null
+++ b/Help/prop_test/FIXTURES_REQUIRED.rst
@@ -0,0 +1,94 @@
+FIXTURES_REQUIRED
+-----------------
+
+Specifies a list of fixtures the test requires. Fixture names are case
+sensitive.
+
+Fixtures are a way to attach setup and cleanup tasks to a set of tests. If a
+test requires a given fixture, then all tests marked as setup tasks for that
+fixture will be executed first (once for the whole set of tests, not once per
+test requiring the fixture). After all tests requiring a particular fixture
+have completed, CTest will ensure all tests marked as cleanup tasks for that
+fixture are then executed. Tests are marked as setup tasks with the
+:prop_test:`FIXTURES_SETUP` property and as cleanup tasks with the
+:prop_test:`FIXTURES_CLEANUP` property. If any of a fixture's setup tests fail,
+all tests listing that fixture in their ``FIXTURES_REQUIRED`` property will not
+be executed. The cleanup tests for the fixture will always be executed, even if
+some setup tests fail.
+
+When CTest is asked to execute only a subset of tests (e.g. by the use of
+regular expressions or when run with the ``--rerun-failed`` command line
+option), it will automatically add any setup or cleanup tests for fixtures
+required by any of the tests that are in the execution set.
+
+Since setup and cleanup tasks are also tests, they can have an ordering
+specified by the :prop_test:`DEPENDS` test property just like any other tests.
+This can be exploited to implement setup or cleanup using multiple tests for a
+single fixture to modularise setup or cleanup logic.
+
+The concept of a fixture is different to that of a resource specified by
+:prop_test:`RESOURCE_LOCK`, but they may be used together. A fixture defines a
+set of tests which share setup and cleanup requirements, whereas a resource
+lock has the effect of ensuring a particular set of tests do not run in
+parallel. Some situations may need both, such as setting up a database,
+serialising test access to that database and deleting the database again at the
+end. For such cases, tests would populate both ``FIXTURES_REQUIRED`` and
+:prop_test:`RESOURCE_LOCK` to combine the two behaviours. Names used for
+:prop_test:`RESOURCE_LOCK` have no relationship with names of fixtures, so note
+that a resource lock does not imply a fixture and vice versa.
+
+Consider the following example which represents a database test scenario
+similar to that mentioned above:
+
+.. code-block:: cmake
+
+  add_test(NAME testsDone   COMMAND emailResults)
+  add_test(NAME fooOnly     COMMAND testFoo)
+  add_test(NAME dbOnly      COMMAND testDb)
+  add_test(NAME dbWithFoo   COMMAND testDbWithFoo)
+  add_test(NAME createDB    COMMAND initDB)
+  add_test(NAME setupUsers  COMMAND userCreation)
+  add_test(NAME cleanupDB   COMMAND deleteDB)
+  add_test(NAME cleanupFoo  COMMAND removeFoos)
+
+  set_tests_properties(setupUsers PROPERTIES DEPENDS createDB)
+
+  set_tests_properties(createDB   PROPERTIES FIXTURES_SETUP    DB)
+  set_tests_properties(setupUsers PROPERTIES FIXTURES_SETUP    DB)
+  set_tests_properties(cleanupDB  PROPERTIES FIXTURES_CLEANUP  DB)
+  set_tests_properties(cleanupFoo PROPERTIES FIXTURES_CLEANUP  Foo)
+  set_tests_properties(testsDone  PROPERTIES FIXTURES_CLEANUP  "DB;Foo")
+
+  set_tests_properties(fooOnly    PROPERTIES FIXTURES_REQUIRED Foo)
+  set_tests_properties(dbOnly     PROPERTIES FIXTURES_REQUIRED DB)
+  set_tests_properties(dbWithFoo  PROPERTIES FIXTURES_REQUIRED "DB;Foo")
+
+  set_tests_properties(dbOnly dbWithFoo createDB setupUsers cleanupDB
+                       PROPERTIES RESOURCE_LOCK DbAccess)
+
+Key points from this example:
+
+- Two fixtures are defined: ``DB`` and ``Foo``. Tests can require a single
+  fixture as ``fooOnly`` and ``dbOnly`` do, or they can depend on multiple
+  fixtures like ``dbWithFoo`` does.
+
+- A ``DEPENDS`` relationship is set up to ensure ``setupUsers`` happens after
+  ``createDB``, both of which are setup tests for the ``DB`` fixture and will
+  therefore be executed before the ``dbOnly`` and ``dbWithFoo`` tests
+  automatically.
+
+- No explicit ``DEPENDS`` relationships were needed to make the setup tests run
+  before or the cleanup tests run after the regular tests.
+
+- The ``Foo`` fixture has no setup tests defined, only a single cleanup test.
+
+- ``testsDone`` is a cleanup test for both the ``DB`` and ``Foo`` fixtures.
+  Therefore, it will only execute once regular tests for both fixtures have
+  finished (i.e. after ``fooOnly``, ``dbOnly`` and ``dbWithFoo``). No
+  ``DEPENDS`` relationship was specified for ``testsDone``, so it is free to
+  run before, after or concurrently with other cleanup tests for either
+  fixture.
+
+- The setup and cleanup tests never list the fixtures they are for in their own
+  ``FIXTURES_REQUIRED`` property, as that would result in a dependency on
+  themselves and be considered an error.
diff --git a/Help/prop_test/FIXTURES_SETUP.rst b/Help/prop_test/FIXTURES_SETUP.rst
new file mode 100644
index 0000000..a220215
--- /dev/null
+++ b/Help/prop_test/FIXTURES_SETUP.rst
@@ -0,0 +1,47 @@
+FIXTURES_SETUP
+--------------
+
+Specifies a list of fixtures for which the test is to be treated as a setup
+test.
+
+Fixture setup tests are ordinary tests with all of the usual test
+functionality. Setting the ``FIXTURES_SETUP`` property for a test has two
+primary effects:
+
+- CTest will ensure the test executes before any other test which lists the
+  fixture(s) in its :prop_test:`FIXTURES_REQUIRED` property.
+
+- If CTest is asked to run only a subset of tests (e.g. using regular
+  expressions or the ``--rerun-failed`` option) and the setup test is not in
+  the set of tests to run, it will automatically be added if any tests in the
+  set require any fixture listed in ``FIXTURES_SETUP``.
+
+A setup test can have multiple fixtures listed in its ``FIXTURES_SETUP``
+property. It will execute only once for the whole CTest run, not once for each
+fixture. A fixture can also have more than one setup test defined. If there are
+multiple setup tests for a fixture, projects can control their order with the
+usual :prop_test:`DEPENDS` test property if necessary.
+
+A setup test is allowed to require other fixtures, but not any fixture listed
+in its ``FIXTURES_SETUP`` property. For example:
+
+.. code-block:: cmake
+
+  # Ok: dependent fixture is different to setup
+  set_tests_properties(setupFoo PROPERTIES
+    FIXTURES_SETUP    Foo
+    FIXTURES_REQUIRED Bar
+  )
+
+  # Error: cannot require same fixture as setup
+  set_tests_properties(setupFoo PROPERTIES
+    FIXTURES_SETUP    Foo
+    FIXTURES_REQUIRED Foo
+  )
+
+If any of a fixture's setup tests fail, none of the tests listing that fixture
+in its :prop_test:`FIXTURES_REQUIRED` property will be run. Cleanup tests will,
+however, still be executed.
+
+See :prop_test:`FIXTURES_REQUIRED` for a more complete discussion of how to use
+test fixtures.
diff --git a/Help/prop_test/RESOURCE_LOCK.rst b/Help/prop_test/RESOURCE_LOCK.rst
index 8c30f01..755e0aa 100644
--- a/Help/prop_test/RESOURCE_LOCK.rst
+++ b/Help/prop_test/RESOURCE_LOCK.rst
@@ -5,3 +5,6 @@ Specify a list of resources that are locked by this test.
 
 If multiple tests specify the same resource lock, they are guaranteed
 not to run concurrently.
+
+See also :prop_test:`FIXTURES_REQUIRED` if the resource requires any setup or
+cleanup steps.
diff --git a/Help/prop_tgt/ANDROID_API.rst b/Help/prop_tgt/ANDROID_API.rst
index 714ad58..63464d7 100644
--- a/Help/prop_tgt/ANDROID_API.rst
+++ b/Help/prop_tgt/ANDROID_API.rst
@@ -1,7 +1,8 @@
 ANDROID_API
 -----------
 
-Set the Android Target API version (e.g. ``15``).  The version number
-must be a positive decimal integer.  This property is initialized by
-the value of the :variable:`CMAKE_ANDROID_API` variable if it is set
-when a target is created.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this property sets the Android target API version (e.g. ``15``).
+The version number must be a positive decimal integer.  This property is
+initialized by the value of the :variable:`CMAKE_ANDROID_API` variable if
+it is set when a target is created.
diff --git a/Help/prop_tgt/ANDROID_ARCH.rst b/Help/prop_tgt/ANDROID_ARCH.rst
index 5477fb5..3e07e5a 100644
--- a/Help/prop_tgt/ANDROID_ARCH.rst
+++ b/Help/prop_tgt/ANDROID_ARCH.rst
@@ -1,7 +1,8 @@
 ANDROID_ARCH
 ------------
 
-Set the Android target architecture.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this property sets the Android target architecture.
 
 This is a string property that could be set to the one of
 the following values:
diff --git a/Help/prop_tgt/ANDROID_GUI.rst b/Help/prop_tgt/ANDROID_GUI.rst
index abdba7a..92e2041 100644
--- a/Help/prop_tgt/ANDROID_GUI.rst
+++ b/Help/prop_tgt/ANDROID_GUI.rst
@@ -1,7 +1,9 @@
 ANDROID_GUI
 -----------
 
-Build an executable as an application package on Android.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this property specifies whether to build an executable as an
+application package on Android.
 
 When this property is set to true the executable when built for Android
 will be created as an application package.  This property is initialized
diff --git a/Help/prop_tgt/ANDROID_STL_TYPE.rst b/Help/prop_tgt/ANDROID_STL_TYPE.rst
index 7256e26..386e96e 100644
--- a/Help/prop_tgt/ANDROID_STL_TYPE.rst
+++ b/Help/prop_tgt/ANDROID_STL_TYPE.rst
@@ -1,15 +1,27 @@
 ANDROID_STL_TYPE
 ----------------
 
-Set the Android property that defines the type of STL support for the project.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this property specifies the type of STL support for the project.
 This is a string property that could set to the one of the following values:
-``none``           e.g. "No C++ Support"
-``system``         e.g. "Minimal C++ without STL"
-``gabi++_static``  e.g. "GAbi++ Static"
-``gabi++_shared``  e.g. "GAbi++ Shared"
-``gnustl_static``  e.g. "GNU libstdc++ Static"
-``gnustl_shared``  e.g. "GNU libstdc++ Shared"
-``stlport_static`` e.g. "STLport Static"
-``stlport_shared`` e.g. "STLport Shared"
+
+``none``
+  No C++ Support
+``system``
+  Minimal C++ without STL
+``gabi++_static``
+  GAbi++ Static
+``gabi++_shared``
+  GAbi++ Shared
+``gnustl_static``
+  GNU libstdc++ Static
+``gnustl_shared``
+  GNU libstdc++ Shared
+``stlport_static``
+  STLport Static
+``stlport_shared``
+  STLport Shared
+
 This property is initialized by the value of the
-variable:`CMAKE_ANDROID_STL_TYPE` variable if it is set when a target is created.
+:variable:`CMAKE_ANDROID_STL_TYPE` variable if it is set when a target is
+created.
diff --git a/Help/prop_tgt/AUTORCC.rst b/Help/prop_tgt/AUTORCC.rst
index 8dce6b1..158fdf8 100644
--- a/Help/prop_tgt/AUTORCC.rst
+++ b/Help/prop_tgt/AUTORCC.rst
@@ -19,5 +19,10 @@ Additional command line options for rcc can be set via the
 The global property :prop_gbl:`AUTOGEN_TARGETS_FOLDER` can be used to group
 the autorcc targets together in an IDE, e.g. in MSVS.
 
+When there are multiple ``.qrc`` files with the same name, CMake will
+generate unspecified unique names for ``rcc``.  Therefore if
+``Q_INIT_RESOURCE()`` or ``Q_CLEANUP_RESOURCE()`` need to be used the
+``.qrc`` file name must be unique.
+
 See the :manual:`cmake-qt(7)` manual for more information on using CMake
 with Qt.
diff --git a/Help/prop_tgt/BUNDLE_EXTENSION.rst b/Help/prop_tgt/BUNDLE_EXTENSION.rst
index ea265b3..6b3d580 100644
--- a/Help/prop_tgt/BUNDLE_EXTENSION.rst
+++ b/Help/prop_tgt/BUNDLE_EXTENSION.rst
@@ -1,7 +1,8 @@
 BUNDLE_EXTENSION
 ----------------
 
-The file extension used to name a :prop_tgt:`BUNDLE` target on the OS X and iOS.
+The file extension used to name a :prop_tgt:`BUNDLE`, a :prop_tgt:`FRAMEWORK`,
+or a :prop_tgt:`MACOSX_BUNDLE` target on the OS X and iOS.
 
-The default value is ``bundle`` - you can also use ``plugin`` or whatever
-file extension is required by the host app for your bundle.
+The default value is ``bundle``, ``framework``, or ``app`` for the respective
+target types.
diff --git a/Help/prop_tgt/LINK_WHAT_YOU_USE.rst b/Help/prop_tgt/LINK_WHAT_YOU_USE.rst
new file mode 100644
index 0000000..32d6edb
--- /dev/null
+++ b/Help/prop_tgt/LINK_WHAT_YOU_USE.rst
@@ -0,0 +1,15 @@
+LINK_WHAT_YOU_USE
+---------------------------
+
+This is a boolean option that when set to ``TRUE`` will automatically run
+``ldd -r -u`` on the target after it is linked. In addition, the linker flag
+``-Wl,--no-as-needed`` will be passed to the target with the link command so
+that all libraries specified on the command line will be linked into the
+target. This will result in the link producing a list of libraries that
+provide no symbols used by this target but are being linked to it.
+This is only applicable to executable and shared library targets and
+will only work when ld and ldd accept the flags used.
+
+This property is initialized by the value of
+the :variable:`CMAKE_LINK_WHAT_YOU_USE` variable if it is set
+when a target is created.
diff --git a/Help/prop_tgt/VS_SDK_REFERENCES.rst b/Help/prop_tgt/VS_SDK_REFERENCES.rst
new file mode 100644
index 0000000..769a0d1
--- /dev/null
+++ b/Help/prop_tgt/VS_SDK_REFERENCES.rst
@@ -0,0 +1,7 @@
+VS_SDK_REFERENCES
+-----------------
+
+Visual Studio project SDK references.
+Specify a :ref:`;-list <CMake Language Lists>` of SDK references
+to be added to a generated Visual Studio project, e.g.
+``Microsoft.AdMediatorWindows81, Version=1.0``.
diff --git a/Help/prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS.rst b/Help/prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS.rst
index 3f48af8..06c3e6d 100644
--- a/Help/prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS.rst
+++ b/Help/prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS.rst
@@ -5,8 +5,9 @@ This property is implemented only for MS-compatible tools on Windows.
 
 Enable this boolean property to automatically create a module definition
 (``.def``) file with all global symbols found in the input ``.obj`` files
-for a ``SHARED`` library on Windows.  The module definition file will be
-passed to the linker causing all symbols to be exported from the ``.dll``.
+for a ``SHARED`` library (or executable with :prop_tgt:`ENABLE_EXPORTS`)
+on Windows.  The module definition file will be passed to the linker
+causing all symbols to be exported from the ``.dll``.
 For global *data* symbols, ``__declspec(dllimport)`` must still be used when
 compiling against the code in the ``.dll``.  All other function symbols will
 be automatically exported and imported by callers.  This simplifies porting
diff --git a/Help/release/3.7.rst b/Help/release/3.7.rst
new file mode 100644
index 0000000..9794267
--- /dev/null
+++ b/Help/release/3.7.rst
@@ -0,0 +1,320 @@
+CMake 3.7 Release Notes
+***********************
+
+.. only:: html
+
+  .. contents::
+
+Changes made since CMake 3.6 include the following.
+
+New Features
+============
+
+Platforms
+---------
+
+* CMake now supports :ref:`Cross Compiling for Android` with simple
+  toolchain files.
+
+* The Clang compiler is now supported on AIX.
+
+Generators
+----------
+
+* The :generator:`Ninja` generator learned to conditionally support
+  Fortran when using a ``ninja`` tool that has the necessary features.
+  See generator documentation for details.
+
+* The :generator:`Ninja` generator learned to produce phony targets
+  of the form ``sub/dir/{test,install,package}`` to drive the build
+  of a subdirectory installation, test or packaging target.
+  This is equivalent to ``cd sub/dir; make {test,install,package}``
+  with :ref:`Makefile Generators`.
+
+* The :generator:`Visual Studio 15` generator was added.  This is
+  experimental and based on Preview 4 because this version of VS
+  has not been released.
+
+* :ref:`Visual Studio Generators` for VS 2010 and above learned to
+  place ``.natvis`` source files into VS project files properly.
+
+* The :generator:`Xcode` generator's rudimentary Swift language support
+  learned to honor a new :variable:`CMAKE_Swift_LANGUAGE_VERSION` variable
+  to tell Xcode what version of Swift is used by the source.
+
+* The :generator:`CodeLite` generator gained a new
+  :variable:`CMAKE_CODELITE_USE_TARGETS` option
+  to change project creation from projects to targets.
+
+Commands
+--------
+
+* The :command:`add_custom_command` command gained a new ``DEPFILE``
+  option that works with the :generator:`Ninja` generator to provide
+  implicit dependency information to the build tool.
+
+* The :command:`cmake_parse_arguments` command gained a new ``PARSE_ARGV``
+  mode to read arguments directly from ``ARGC`` and ``ARGV#``
+  variables inside a :command:`function` body.
+
+* The :command:`export` command gained an ``ANDROID_MK`` option
+  to generate ``Android.mk`` files referencing CMake-built
+  libraries as prebuilts for the Android NDK build system.
+
+* The :command:`file(DOWNLOAD)` and :command:`file(UPLOAD)` commands gained
+  ``HTTPHEADER <HTTP-header>`` and ``USERPWD <username>:<password>`` options.
+
+* The :command:`find_library` and :command:`find_package` commands learned
+  to search in ``lib32/`` directories when the build targets a 32-bit
+  architecture.  See the :prop_gbl:`FIND_LIBRARY_USE_LIB32_PATHS` global
+  property.
+
+* The :command:`find_package` command gained the possibility of
+  sorting compatible libraries by ``NAME`` or by ``NATURAL`` sorting by
+  setting the two new variables :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER`
+  and :variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION`.
+
+* The :command:`if` command gained new boolean comparison operations
+  ``LESS_EQUAL``, ``GREATER_EQUAL``, ``STRLESS_EQUAL``, ``STRGREATER_EQUAL``,
+  ``VERSION_LESS_EQUAL``, and ``VERSION_GREATER_EQUAL``.
+
+* The :command:`install` command gained an ``EXPORT_ANDROID_MK``
+  subcommand to install ``Android.mk`` files referencing installed
+  libraries as prebuilts for the Android NDK build system.
+
+* The :command:`string(TIMESTAMP)` and :command:`file(TIMESTAMP)`
+  commands gained support for the ``%a`` and ``%b`` placeholders.
+  These are the abbreviated weekday and month names.
+
+* The :command:`try_compile` command source file signature now honors
+  configuration-specific flags (e.g. :variable:`CMAKE_<LANG>_FLAGS_DEBUG`)
+  in the generated test project.  Previously only the default such flags
+  for the current toolchain were used.  See policy :policy:`CMP0066`.
+
+Variables
+---------
+
+* Variable :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER` was added to control
+  the sorting mode of the :command:`find_package` command.
+
+* Variable :variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION` was added to control
+  the sorting direction the :command:`find_package` command.
+
+* :variable:`Toolchain files <CMAKE_TOOLCHAIN_FILE>` may now set a
+  :variable:`CMAKE_<LANG>_FLAGS_INIT` variable to initialize the
+  :variable:`CMAKE_<LANG>_FLAGS` cache entry the first time a language is
+  enabled in a build tree.
+
+* :variable:`Toolchain files <CMAKE_TOOLCHAIN_FILE>` may now set
+  :variable:`CMAKE_EXE_LINKER_FLAGS_INIT`,
+  :variable:`CMAKE_SHARED_LINKER_FLAGS_INIT`, and
+  :variable:`CMAKE_MODULE_LINKER_FLAGS_INIT` variables to initialize the
+  :variable:`CMAKE_EXE_LINKER_FLAGS`,
+  :variable:`CMAKE_SHARED_LINKER_FLAGS`, and
+  :variable:`CMAKE_MODULE_LINKER_FLAGS` cache entries the first time
+  a language is enabled in a build tree.
+
+Properties
+----------
+
+* On Apple platforms the :prop_tgt:`BUNDLE_EXTENSION` target property
+  now also applies to Frameworks and App Bundles.
+
+* A :prop_dir:`BINARY_DIR` directory property was added to get the
+  absolute path to the binary directory corresponding to the source
+  directory on which the property is read.
+
+* A :prop_dir:`BUILDSYSTEM_TARGETS` directory property was added to
+  get the list of logical buildsystem target names added by the
+  project in a directory.
+
+* A :prop_tgt:`LINK_WHAT_YOU_USE` target property and supporting
+  :variable:`CMAKE_LINK_WHAT_YOU_USE` variable were introduced
+  to detect (on UNIX) shared libraries that are linked but not
+  needed by running ``ldd -r -u``.
+
+* A :prop_dir:`SOURCE_DIR` directory property was added to get the
+  absolute path to the source directory associated with a directory.
+
+* A :prop_dir:`SUBDIRECTORIES` directory property was added to
+  get the list of subdirectories added by a project in a directory.
+
+* A :prop_tgt:`VS_SDK_REFERENCES` target property was added to tell
+  :ref:`Visual Studio Generators` to reference the named SDKs.
+
+* A :prop_sf:`VS_TOOL_OVERRIDE` source file property was created to tell
+  :ref:`Visual Studio Generators` what tool to use for a source file.
+
+* The :prop_tgt:`WINDOWS_EXPORT_ALL_SYMBOLS` target property now applies
+  to executable targets with the :prop_tgt:`ENABLE_EXPORTS` property set.
+
+* A :prop_sf:`XCODE_FILE_ATTRIBUTES` source file property was
+  added to tell the :generator:`Xcode` generator to generate
+  custom content in the Xcode project attributes for the file.
+
+Modules
+-------
+
+* An :module:`AndroidTestUtilities` module was added to manage transfer
+  of test data to an Android device.
+
+* The :module:`CheckFortranSourceCompiles` module macro
+  ``CHECK_Fortran_SOURCE_COMPILES`` gained a ``SRC_EXT`` option
+  to specify a custom test Fortran source file extension.
+
+* The :module:`ExternalProject` module gained ``HTTP_USERNAME`` and
+  ``HTTP_PASSWORD`` options to set http download credentials.
+
+* The :module:`ExternalProject` module gained a ``HTTP_HEADER``
+  option to add http download headers.
+
+* The :module:`FindBISON` module ``BISON_TARGET`` macro learned a new
+  ``REPORT_FILE`` option to specify the bison ``--report-file=`` option.
+
+* The :module:`FindBZip2` module now provides imported targets.
+
+* A :module:`FindICU` module was introduced to find the International
+  Components for Unicode (ICU) libraries and programs.
+
+* The :module:`FindMatlab` module learned to find the SIMULINK and MAT
+  components.
+
+* The :module:`FindMatlab` module :command:`matlab_add_mex` command learned
+  to add executables and modules.
+
+* The :module:`FindMatlab` module :command:`matlab_add_unit_test` command
+  learned to support inline Matlab test code.
+
+* The :module:`FindOpenCL` module now provides imported targets.
+
+* The :module:`FindOpenMP` module learned to detect the OpenMP
+  version (specification date) from the compiler.
+
+* A :module:`FindVulkan` module was added.
+
+* The :module:`GenerateExportHeader` module learned a new
+  ``CUSTOM_CONTENT_FROM_VARIABLE`` option to specify a variable
+  containing custom content for inclusion in the generated header.
+
+* The :module:`GNUInstallDirs` module gained a new
+  :command:`GNUInstallDirs_get_absolute_install_dir` command.
+
+* The :module:`UseJava` module gained APIs to "export" jar targets
+  for use by external CMake projects.  See the ``install_jar_exports``
+  and ``export_jars`` functions.
+
+CTest
+-----
+
+* CTest now supports test fixtures through the new :prop_test:`FIXTURES_SETUP`,
+  :prop_test:`FIXTURES_CLEANUP` and :prop_test:`FIXTURES_REQUIRED` test
+  properties. When using regular expressions or ``--rerun-failed`` to limit
+  the tests to be run, a fixture's setup and cleanup tests will automatically
+  be added to the execution set if any test requires that fixture.
+
+* The :command:`ctest_configure`, :command:`ctest_build`,
+  :command:`ctest_test`, :command:`ctest_coverage`, and :command:`ctest_upload`
+  commands gained a new ``CAPTURE_CMAKE_ERROR`` option to capture any errors
+  that occur as the commands run into a variable and avoid affecting the return
+  code of the :manual:`ctest(1)` process.
+
+CPack
+-----
+
+* CPack gained a ``productbuild`` generator on OS X, configured by
+  the :module:`CPackProductBuild` module.
+
+* CPack gained a new :variable:`CPACK_PACKAGE_CHECKSUM` variable to
+  enable generation of a checksum file for each package file.
+
+* The :module:`CPackDeb` module learned to support long file names
+  when archive format is set to GNU tar.
+  See :variable:`CPACK_DEBIAN_ARCHIVE_TYPE`
+
+* The :module:`CPackIFW` module gained a new
+  :command:`cpack_ifw_add_package_resources` command to include additional
+  resources in the installer binary.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and
+  :command:`cpack_ifw_configure_component_group` commands gained a new
+  ``USER_INTERFACES`` option to add a list of additonal pages to the IFW
+  installer.
+
+* The :module:`CPackRPM` module learned to generate debuginfo
+  packages on demand. See :variable:`CPACK_RPM_DEBUGINFO_PACKAGE`
+  and its per component version.
+
+* The :module:`CPackRPM` module learned to generate source rpm
+  (SRPM) packages on demand. See :variable:`CPACK_RPM_PACKAGE_SOURCES`,
+  :variable:`CPACK_RPM_SOURCE_PKG_BUILD_PARAMS` and
+  :variable:`CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX`.
+
+* The CPack NSIS generator now supports
+  :variable:`CPACK_NSIS_<compName>_INSTALL_DIRECTORY`.
+  This can be used to set component specific installation directories.
+
+* The CPack WIX generator now supports
+  :variable:`CPACK_WIX_SKIP_PROGRAM_FOLDER` to allow specification
+  of a custom absolute installation prefix outside
+  of the ProgramFiles folders.
+
+* The CPack WIX generator now supports
+  :variable:`CPACK_COMPONENT_<compName>_DISABLED`.
+  This can be used to deselect a component from being installed by default.
+
+* The CPack WIX generator now supports :variable:`CPACK_WIX_PATCH_FILE`
+  fragments for Feature elements.
+
+* The CPack WIX generator now supports
+  :variable:`CPACK_WIX_ROOT_FEATURE_TITLE` and
+  :variable:`CPACK_WIX_ROOT_FEATURE_DESCRIPTION` to allow the specification
+  of a custom title and description for the root feature element.
+
+Other
+-----
+
+* :manual:`cmake(1)` gained a ``-E capabilities`` option to provide a
+  machine-readable (JSON) description of the capabilities of the
+  cmake tool (available generators, etc.).
+
+* A new :manual:`cmake-server(7)` mode was added to provide semantic
+  information about a CMake-generated buildsystem to clients through
+  a JSON protocol.  Currently all protocols are experimental and subject
+  to change.
+
+* The :manual:`cmake(1)` command learned a ``--trace-source=<file>`` option.
+
+* :manual:`ccmake(1)` learned to support vim-like navigation bindings.
+
+* :manual:`cmake-gui(1)` gained a button to open the generated project file
+  for :ref:`Visual Studio Generators` and the :generator:`Xcode` generator.
+
+Deprecated and Removed Features
+===============================
+
+* We no longer provide Linux i386 binaries for download from ``cmake.org``
+  for new versions of CMake.
+
+* Vim support files ``cmake-indent.vim``, ``cmake-syntax.vim``, and
+  ``cmake-help.vim`` have been removed in favor of the files now provided
+  from the `vim-cmake-syntax`_ project.
+
+* Support for building CMake itself with some compilers was dropped:
+
+  * Visual Studio 7.1 and 2005 -- superseded by VS 2008 and above
+  * MinGW.org mingw32 -- superseded by MSYS2 mingw32 and mingw64
+
+  CMake still supports generating build systems for other projects using
+  these compilers.
+
+Other Changes
+=============
+
+* The Fortran dependency scanner learned to support the syntax of
+  `Fortran Submodules`_.
+
+* Vim support files ``indent/cmake.vim`` and ``syntax/cmake.vim``
+  from the `vim-cmake-syntax`_ project are now distributed with CMake.
+
+.. _`Fortran Submodules`: http://fortranwiki.org/fortran/show/Submodules
+.. _`vim-cmake-syntax`: https://github.com/pboettch/vim-cmake-syntax
diff --git a/Help/release/index.rst b/Help/release/index.rst
index 92c3b63..25c6c3e 100644
--- a/Help/release/index.rst
+++ b/Help/release/index.rst
@@ -11,6 +11,7 @@ Releases
 .. toctree::
    :maxdepth: 1
 
+   3.7 <3.7>
    3.6 <3.6>
    3.5 <3.5>
    3.4 <3.4>
diff --git a/Help/variable/ANDROID.rst b/Help/variable/ANDROID.rst
new file mode 100644
index 0000000..fede4ca
--- /dev/null
+++ b/Help/variable/ANDROID.rst
@@ -0,0 +1,5 @@
+ANDROID
+-------
+
+Set to ``1`` when the target system (:variable:`CMAKE_SYSTEM_NAME`) is
+``Android``.
diff --git a/Help/variable/CMAKE_ANDROID_API.rst b/Help/variable/CMAKE_ANDROID_API.rst
index c8264e0..c07a05a 100644
--- a/Help/variable/CMAKE_ANDROID_API.rst
+++ b/Help/variable/CMAKE_ANDROID_API.rst
@@ -1,5 +1,11 @@
 CMAKE_ANDROID_API
 -----------------
 
-Default value for the :prop_tgt:`ANDROID_API` target property.
-See that target property for additional information.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this variable may be set to specify the default value for the
+:prop_tgt:`ANDROID_API` target property.  See that target property for
+additional information.
+
+Otherwise, when :ref:`Cross Compiling for Android`, this variable provides
+the Android API version number targeted.  This will be the same value as
+the :variable:`CMAKE_SYSTEM_VERSION` variable for ``Android`` platforms.
diff --git a/Help/variable/CMAKE_ANDROID_ARCH.rst b/Help/variable/CMAKE_ANDROID_ARCH.rst
index 8fbb46d..b91ca57 100644
--- a/Help/variable/CMAKE_ANDROID_ARCH.rst
+++ b/Help/variable/CMAKE_ANDROID_ARCH.rst
@@ -1,5 +1,19 @@
 CMAKE_ANDROID_ARCH
 ------------------
 
-Default value for the :prop_tgt:`ANDROID_ARCH` target property.
-See that target property for additional information.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this variable may be set to specify the default value for the
+:prop_tgt:`ANDROID_ARCH` target property.  See that target property for
+additional information.
+
+Otherwise, when :ref:`Cross Compiling for Android`, this variable provides
+the name of the Android architecture corresponding to the value of the
+:variable:`CMAKE_ANDROID_ARCH_ABI` variable.  The architecture name
+may be one of:
+
+* ``arm``
+* ``arm64``
+* ``mips``
+* ``mips64``
+* ``x86``
+* ``x86_64``
diff --git a/Help/variable/CMAKE_ANDROID_ARCH_ABI.rst b/Help/variable/CMAKE_ANDROID_ARCH_ABI.rst
new file mode 100644
index 0000000..0a3ed3c
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_ARCH_ABI.rst
@@ -0,0 +1,17 @@
+CMAKE_ANDROID_ARCH_ABI
+----------------------
+
+When :ref:`Cross Compiling for Android`, this variable specifies the
+target architecture and ABI to be used.  Valid values are:
+
+* ``arm64-v8a``
+* ``armeabi-v7a``
+* ``armeabi-v6``
+* ``armeabi``
+* ``mips``
+* ``mips64``
+* ``x86``
+* ``x86_64``
+
+See also the :variable:`CMAKE_ANDROID_ARM_MODE` and
+:variable:`CMAKE_ANDROID_ARM_NEON` variables.
diff --git a/Help/variable/CMAKE_ANDROID_ARM_MODE.rst b/Help/variable/CMAKE_ANDROID_ARM_MODE.rst
new file mode 100644
index 0000000..ad3c37c
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_ARM_MODE.rst
@@ -0,0 +1,7 @@
+CMAKE_ANDROID_ARM_MODE
+----------------------
+
+When :ref:`Cross Compiling for Android` and :variable:`CMAKE_ANDROID_ARCH_ABI`
+is set to one of the ``armeabi`` architectures, set ``CMAKE_ANDROID_ARM_MODE``
+to ``ON`` to target 32-bit ARM processors (``-marm``).  Otherwise, the
+default is to target the 16-bit Thumb processors (``-mthumb``).
diff --git a/Help/variable/CMAKE_ANDROID_ARM_NEON.rst b/Help/variable/CMAKE_ANDROID_ARM_NEON.rst
new file mode 100644
index 0000000..4b7ae03
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_ARM_NEON.rst
@@ -0,0 +1,6 @@
+CMAKE_ANDROID_ARM_NEON
+----------------------
+
+When :ref:`Cross Compiling for Android` and :variable:`CMAKE_ANDROID_ARCH_ABI`
+is set to ``armeabi-v7a`` set ``CMAKE_ANDROID_ARM_NEON`` to ``ON`` to target
+ARM NEON devices.
diff --git a/Help/variable/CMAKE_ANDROID_NDK.rst b/Help/variable/CMAKE_ANDROID_NDK.rst
new file mode 100644
index 0000000..d241dd0
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_NDK.rst
@@ -0,0 +1,7 @@
+CMAKE_ANDROID_NDK
+-----------------
+
+When :ref:`Cross Compiling for Android with the NDK`, this variable holds
+the absolute path to the root directory of the NDK.  The directory must
+contain a ``platforms`` subdirectory holding the ``android-<api>``
+directories.
diff --git a/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst
new file mode 100644
index 0000000..dff7d64
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst
@@ -0,0 +1,13 @@
+CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION
+-----------------------------------
+
+When :ref:`Cross Compiling for Android with the NDK`, this variable
+may be set to specify the version of the toolchain to be used
+as the compiler.  The variable must be set to one of these forms:
+
+* ``<major>.<minor>``: GCC of specified version
+* ``clang<major>.<minor>``: Clang of specified version
+* ``clang``: Clang of most recent available version
+
+A toolchain of the requested version will be selected automatically to
+match the ABI named in the :variable:`CMAKE_ANDROID_ARCH_ABI` variable.
diff --git a/Help/variable/CMAKE_ANDROID_STANDALONE_TOOLCHAIN.rst b/Help/variable/CMAKE_ANDROID_STANDALONE_TOOLCHAIN.rst
new file mode 100644
index 0000000..ea62cab
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_STANDALONE_TOOLCHAIN.rst
@@ -0,0 +1,6 @@
+CMAKE_ANDROID_STANDALONE_TOOLCHAIN
+----------------------------------
+
+When :ref:`Cross Compiling for Android with a Standalone Toolchain`, this
+variable holds the absolute path to the root directory of the toolchain.
+The specified directory must contain a ``sysroot`` subdirectory.
diff --git a/Help/variable/CMAKE_ANDROID_STL_TYPE.rst b/Help/variable/CMAKE_ANDROID_STL_TYPE.rst
index 766b2c8..cfb76aa 100644
--- a/Help/variable/CMAKE_ANDROID_STL_TYPE.rst
+++ b/Help/variable/CMAKE_ANDROID_STL_TYPE.rst
@@ -1,5 +1,36 @@
 CMAKE_ANDROID_STL_TYPE
 ----------------------
 
-Default value for the :prop_tgt:`ANDROID_STL_TYPE` target property.
-See that target property for additional information.
+When :ref:`Cross Compiling for Android with NVIDIA Nsight Tegra Visual Studio
+Edition`, this variable may be set to specify the default value for the
+:prop_tgt:`ANDROID_STL_TYPE` target property.  See that target property
+for additional information.
+
+When :ref:`Cross Compiling for Android with the NDK`, this variable may be
+set to specify the STL variant to be used.  The value may be one of:
+
+``none``
+  No C++ Support
+``system``
+  Minimal C++ without STL
+``gabi++_static``
+  GAbi++ Static
+``gabi++_shared``
+  GAbi++ Shared
+``gnustl_static``
+  GNU libstdc++ Static
+``gnustl_shared``
+  GNU libstdc++ Shared
+``c++_static``
+  LLVM libc++ Static
+``c++_shared``
+  LLVM libc++ Shared
+``stlport_static``
+  STLport Static
+``stlport_shared``
+  STLport Shared
+
+The default value is ``gnustl_static``.  Note that this default differs from
+the native NDK build system because CMake may be used to build projects for
+Android that are not natively implemented for it and use the C++ standard
+library.
diff --git a/Help/variable/CMAKE_CODELITE_USE_TARGETS.rst b/Help/variable/CMAKE_CODELITE_USE_TARGETS.rst
new file mode 100644
index 0000000..33cdf6c
--- /dev/null
+++ b/Help/variable/CMAKE_CODELITE_USE_TARGETS.rst
@@ -0,0 +1,8 @@
+CMAKE_CODELITE_USE_TARGETS
+--------------------------
+
+Change the way the CodeLite generator creates projectfiles.
+
+If this variable evaluates to ``ON`` at the end of the top-level
+``CMakeLists.txt`` file, the generator creates projectfiles based on targets
+rather than projects.
diff --git a/Help/variable/CMAKE_COMPILER_IS_GNUCC.rst b/Help/variable/CMAKE_COMPILER_IS_GNUCC.rst
new file mode 100644
index 0000000..a40667e
--- /dev/null
+++ b/Help/variable/CMAKE_COMPILER_IS_GNUCC.rst
@@ -0,0 +1,5 @@
+CMAKE_COMPILER_IS_GNUCC
+-----------------------
+
+True if the ``C`` compiler is GNU.
+Use :variable:`CMAKE_C_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` instead.
diff --git a/Help/variable/CMAKE_COMPILER_IS_GNUCXX.rst b/Help/variable/CMAKE_COMPILER_IS_GNUCXX.rst
new file mode 100644
index 0000000..f1f5cf7
--- /dev/null
+++ b/Help/variable/CMAKE_COMPILER_IS_GNUCXX.rst
@@ -0,0 +1,5 @@
+CMAKE_COMPILER_IS_GNUCXX
+------------------------
+
+True if the C++ (``CXX``) compiler is GNU.
+Use :variable:`CMAKE_CXX_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` instead.
diff --git a/Help/variable/CMAKE_COMPILER_IS_GNUG77.rst b/Help/variable/CMAKE_COMPILER_IS_GNUG77.rst
new file mode 100644
index 0000000..3d6dab4
--- /dev/null
+++ b/Help/variable/CMAKE_COMPILER_IS_GNUG77.rst
@@ -0,0 +1,5 @@
+CMAKE_COMPILER_IS_GNUG77
+------------------------
+
+True if the ``Fortran`` compiler is GNU.
+Use :variable:`CMAKE_Fortran_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` instead.
diff --git a/Help/variable/CMAKE_COMPILER_IS_GNULANG.rst b/Help/variable/CMAKE_COMPILER_IS_GNULANG.rst
deleted file mode 100644
index 4b652c0..0000000
--- a/Help/variable/CMAKE_COMPILER_IS_GNULANG.rst
+++ /dev/null
@@ -1,15 +0,0 @@
-CMAKE_COMPILER_IS_GNU<LANG>
----------------------------
-
-True if the compiler is GNU.
-
-If the selected ``<LANG>`` compiler is the GNU compiler then this is ``TRUE``,
-if not it is ``FALSE``.  Unlike the other per-language variables, this
-uses the GNU syntax for identifying languages instead of the CMake
-syntax.  Recognized values of the ``<LANG>`` suffix are:
-
-::
-
-  CC = C compiler
-  CXX = C++ compiler
-  G77 = Fortran compiler
diff --git a/Help/variable/CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT.rst b/Help/variable/CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT.rst
new file mode 100644
index 0000000..592a369
--- /dev/null
+++ b/Help/variable/CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_EXE_LINKER_FLAGS_<CONFIG>_INIT
+------------------------------------
+
+Value used to initialize the :variable:`CMAKE_EXE_LINKER_FLAGS_<CONFIG>`
+cache entry the first time a build tree is configured.
+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_EXE_LINKER_FLAGS_INIT`.
diff --git a/Help/variable/CMAKE_EXE_LINKER_FLAGS_INIT.rst b/Help/variable/CMAKE_EXE_LINKER_FLAGS_INIT.rst
new file mode 100644
index 0000000..0b8afe4
--- /dev/null
+++ b/Help/variable/CMAKE_EXE_LINKER_FLAGS_INIT.rst
@@ -0,0 +1,11 @@
+CMAKE_EXE_LINKER_FLAGS_INIT
+---------------------------
+
+Value used to initialize the :variable:`CMAKE_EXE_LINKER_FLAGS`
+cache entry the first time a build tree is configured.
+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 the configuration-specific variable
+:variable:`CMAKE_EXE_LINKER_FLAGS_<CONFIG>_INIT`.
diff --git a/Help/variable/CMAKE_FIND_PACKAGE_SORT_DIRECTION.rst b/Help/variable/CMAKE_FIND_PACKAGE_SORT_DIRECTION.rst
new file mode 100644
index 0000000..99e4ec1
--- /dev/null
+++ b/Help/variable/CMAKE_FIND_PACKAGE_SORT_DIRECTION.rst
@@ -0,0 +1,16 @@
+CMAKE_FIND_PACKAGE_SORT_DIRECTION
+---------------------------------
+
+The sorting direction used by :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER`.
+It can assume one of the following values:
+
+``DEC``
+  Default.  Ordering is done in descending mode.
+  The highest folder found will be tested first.
+
+``ASC``
+  Ordering is done in ascending mode.
+  The lowest folder found will be tested first.
+
+If :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER` is not set or is set to ``NONE``
+this variable has no effect.
diff --git a/Help/variable/CMAKE_FIND_PACKAGE_SORT_ORDER.rst b/Help/variable/CMAKE_FIND_PACKAGE_SORT_ORDER.rst
new file mode 100644
index 0000000..ba5f3a8
--- /dev/null
+++ b/Help/variable/CMAKE_FIND_PACKAGE_SORT_ORDER.rst
@@ -0,0 +1,36 @@
+CMAKE_FIND_PACKAGE_SORT_ORDER
+-----------------------------
+
+The default order for sorting packages found using :command:`find_package`.
+It can assume one of the following values:
+
+``NONE``
+  Default.  No attempt is done to sort packages.
+  The first valid package found will be selected.
+
+``NAME``
+  Sort packages lexicographically before selecting one.
+
+``NATURAL``
+  Sort packages using natural order (see ``strverscmp(3)`` manual),
+  i.e. such that contiguous digits are compared as whole numbers.
+
+Natural sorting can be employed to return the highest version when multiple
+versions of the same library are found by :command:`find_package`.  For
+example suppose that the following libraries have been found:
+
+* libX-1.1.0
+* libX-1.2.9
+* libX-1.2.10
+
+By setting ``NATURAL`` order we can select the one with the highest
+version number ``libX-1.2.10``.
+
+.. code-block:: cmake
+
+  set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
+  find_package(libX CONFIG)
+
+The sort direction can be controlled using the
+:variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION` variable
+(by default decrescent, e.g. lib-B will be tested before lib-A).
diff --git a/Help/variable/CMAKE_INSTALL_PREFIX.rst b/Help/variable/CMAKE_INSTALL_PREFIX.rst
index 3f3347f..86f1944 100644
--- a/Help/variable/CMAKE_INSTALL_PREFIX.rst
+++ b/Help/variable/CMAKE_INSTALL_PREFIX.rst
@@ -5,7 +5,7 @@ Install directory used by :command:`install`.
 
 If ``make install`` is invoked or ``INSTALL`` is built, this directory is
 prepended onto all install directories.  This variable defaults to
-``/usr/local`` on UNIX and ``c:/Program Files`` on Windows.
+``/usr/local`` on UNIX and ``c:/Program Files/${PROJECT_NAME}`` on Windows.
 
 On UNIX one can use the ``DESTDIR`` mechanism in order to relocate the
 whole installation.  ``DESTDIR`` means DESTination DIRectory.  It is
diff --git a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst
new file mode 100644
index 0000000..b51422f
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst
@@ -0,0 +1,11 @@
+CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX
+-------------------------------------
+
+When :ref:`Cross Compiling for Android` this variable contains the absolute
+path prefixing the toolchain GNU compiler and its binutils.
+
+See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`.
+
+For example, the path to the linker is::
+
+  ${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}ld${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}
diff --git a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst
new file mode 100644
index 0000000..a4af640
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst
@@ -0,0 +1,7 @@
+CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX
+-------------------------------------
+
+When :ref:`Cross Compiling for Android` this variable contains the
+host platform suffix of the toolchain GNU compiler and its binutils.
+
+See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`.
diff --git a/Help/variable/CMAKE_LANG_FLAGS_DEBUG_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_DEBUG_INIT.rst
new file mode 100644
index 0000000..dcddb2e
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_DEBUG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_<LANG>_FLAGS_DEBUG_INIT
+-----------------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS_DEBUG` 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_FLAGS_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_INIT.rst
new file mode 100644
index 0000000..1d32cc3
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_INIT.rst
@@ -0,0 +1,15 @@
+CMAKE_<LANG>_FLAGS_INIT
+-----------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS` 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 the configuration-specific variables:
+
+* :variable:`CMAKE_<LANG>_FLAGS_DEBUG_INIT`
+* :variable:`CMAKE_<LANG>_FLAGS_RELEASE_INIT`
+* :variable:`CMAKE_<LANG>_FLAGS_MINSIZEREL_INIT`
+* :variable:`CMAKE_<LANG>_FLAGS_RELWITHDEBINFO_INIT`
diff --git a/Help/variable/CMAKE_LANG_FLAGS_MINSIZEREL_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_MINSIZEREL_INIT.rst
new file mode 100644
index 0000000..c0aedf4
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_MINSIZEREL_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_<LANG>_FLAGS_MINSIZEREL_INIT
+----------------------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS_MINSIZEREL`
+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_FLAGS_RELEASE_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_RELEASE_INIT.rst
new file mode 100644
index 0000000..59f92ff
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_RELEASE_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_<LANG>_FLAGS_RELEASE_INIT
+-------------------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS_RELEASE`
+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_FLAGS_RELWITHDEBINFO_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_RELWITHDEBINFO_INIT.rst
new file mode 100644
index 0000000..915f023
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_RELWITHDEBINFO_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_<LANG>_FLAGS_RELWITHDEBINFO_INIT
+--------------------------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS_RELWITHDEBINFO`
+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_LINK_WHAT_YOU_USE.rst b/Help/variable/CMAKE_LINK_WHAT_YOU_USE.rst
new file mode 100644
index 0000000..90c4d3f
--- /dev/null
+++ b/Help/variable/CMAKE_LINK_WHAT_YOU_USE.rst
@@ -0,0 +1,6 @@
+CMAKE_LINK_WHAT_YOU_USE
+---------------------------------
+
+Default value for :prop_tgt:`LINK_WHAT_YOU_USE` target property.
+This variable is used to initialize the property on each target as it is
+created.
diff --git a/Help/variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT.rst b/Help/variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT.rst
new file mode 100644
index 0000000..3279014
--- /dev/null
+++ b/Help/variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT
+---------------------------------------
+
+Value used to initialize the :variable:`CMAKE_MODULE_LINKER_FLAGS_<CONFIG>`
+cache entry the first time a build tree is configured.
+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_MODULE_LINKER_FLAGS_INIT`.
diff --git a/Help/variable/CMAKE_MODULE_LINKER_FLAGS_INIT.rst b/Help/variable/CMAKE_MODULE_LINKER_FLAGS_INIT.rst
new file mode 100644
index 0000000..91b39f6
--- /dev/null
+++ b/Help/variable/CMAKE_MODULE_LINKER_FLAGS_INIT.rst
@@ -0,0 +1,11 @@
+CMAKE_MODULE_LINKER_FLAGS_INIT
+------------------------------
+
+Value used to initialize the :variable:`CMAKE_MODULE_LINKER_FLAGS`
+cache entry the first time a build tree is configured.
+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 the configuration-specific variable
+:variable:`CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT`.
diff --git a/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst b/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
index 582f9e4..36cf75f 100644
--- a/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
+++ b/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
@@ -15,6 +15,8 @@ warn by default:
   policy :policy:`CMP0060`.
 * ``CMAKE_POLICY_WARNING_CMP0065`` controls the warning for
   policy :policy:`CMP0065`.
+* ``CMAKE_POLICY_WARNING_CMP0066`` controls the warning for
+  policy :policy:`CMP0066`.
 
 This variable should not be set by a project in CMake code.  Project
 developers running CMake may set this variable in their cache to
diff --git a/Help/variable/CMAKE_SHARED_LINKER_FLAGS_CONFIG_INIT.rst b/Help/variable/CMAKE_SHARED_LINKER_FLAGS_CONFIG_INIT.rst
new file mode 100644
index 0000000..185df38
--- /dev/null
+++ b/Help/variable/CMAKE_SHARED_LINKER_FLAGS_CONFIG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_SHARED_LINKER_FLAGS_<CONFIG>_INIT
+---------------------------------------
+
+Value used to initialize the :variable:`CMAKE_SHARED_LINKER_FLAGS_<CONFIG>`
+cache entry the first time a build tree is configured.
+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_SHARED_LINKER_FLAGS_INIT`.
diff --git a/Help/variable/CMAKE_SHARED_LINKER_FLAGS_INIT.rst b/Help/variable/CMAKE_SHARED_LINKER_FLAGS_INIT.rst
new file mode 100644
index 0000000..cb819a7
--- /dev/null
+++ b/Help/variable/CMAKE_SHARED_LINKER_FLAGS_INIT.rst
@@ -0,0 +1,11 @@
+CMAKE_SHARED_LINKER_FLAGS_INIT
+------------------------------
+
+Value used to initialize the :variable:`CMAKE_SHARED_LINKER_FLAGS`
+cache entry the first time a build tree is configured.
+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 the configuration-specific variable
+:variable:`CMAKE_SHARED_LINKER_FLAGS_<CONFIG>_INIT`.
diff --git a/Help/variable/CMAKE_STATIC_LINKER_FLAGS_CONFIG_INIT.rst b/Help/variable/CMAKE_STATIC_LINKER_FLAGS_CONFIG_INIT.rst
new file mode 100644
index 0000000..a49d1cb
--- /dev/null
+++ b/Help/variable/CMAKE_STATIC_LINKER_FLAGS_CONFIG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_STATIC_LINKER_FLAGS_<CONFIG>_INIT
+---------------------------------------
+
+Value used to initialize the :variable:`CMAKE_STATIC_LINKER_FLAGS_<CONFIG>`
+cache entry the first time a build tree is configured.
+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_STATIC_LINKER_FLAGS_INIT`.
diff --git a/Help/variable/CMAKE_STATIC_LINKER_FLAGS_INIT.rst b/Help/variable/CMAKE_STATIC_LINKER_FLAGS_INIT.rst
new file mode 100644
index 0000000..113ca71
--- /dev/null
+++ b/Help/variable/CMAKE_STATIC_LINKER_FLAGS_INIT.rst
@@ -0,0 +1,11 @@
+CMAKE_STATIC_LINKER_FLAGS_INIT
+------------------------------
+
+Value used to initialize the :variable:`CMAKE_STATIC_LINKER_FLAGS`
+cache entry the first time a build tree is configured.
+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 the configuration-specific variable
+:variable:`CMAKE_STATIC_LINKER_FLAGS_<CONFIG>_INIT`.
diff --git a/Help/variable/CMAKE_Swift_LANGUAGE_VERSION.rst b/Help/variable/CMAKE_Swift_LANGUAGE_VERSION.rst
new file mode 100644
index 0000000..50121e2
--- /dev/null
+++ b/Help/variable/CMAKE_Swift_LANGUAGE_VERSION.rst
@@ -0,0 +1,5 @@
+CMAKE_Swift_LANGUAGE_VERSION
+----------------------------
+
+Set to the Swift language version number.  If not set, the legacy "2.3"
+version is assumed.
diff --git a/Help/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.rst b/Help/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.rst
index 9af0d97..622278e 100644
--- a/Help/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.rst
+++ b/Help/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.rst
@@ -14,8 +14,10 @@ variables that must be set before CMake builds its first test project
 to check that the compiler for a language works.  It should not be
 used to load a file in cases that a normal :command:`include` will work.  Use
 it only as a last resort for behavior that cannot be achieved any
-other way.  For example, one may set ``CMAKE_C_FLAGS_INIT`` to change the
-default value used to initialize :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>`
+other way.  For example, one may set the
+:variable:`CMAKE_C_FLAGS_INIT <CMAKE_<LANG>_FLAGS_INIT>` variable
+to change the default value used to initialize the
+:variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>` variable
 before it is cached.  The override file should NOT be used to set anything
 that could be set after languages are enabled, such as variables like
 :variable:`CMAKE_RUNTIME_OUTPUT_DIRECTORY` that affect the placement of
diff --git a/Help/variable/CMAKE_VERSION.rst b/Help/variable/CMAKE_VERSION.rst
index bbb1d91..872e2fa 100644
--- a/Help/variable/CMAKE_VERSION.rst
+++ b/Help/variable/CMAKE_VERSION.rst
@@ -26,11 +26,11 @@ Individual component values are also available in variables:
 * :variable:`CMAKE_PATCH_VERSION`
 * :variable:`CMAKE_TWEAK_VERSION`
 
-Use the :command:`if` command ``VERSION_LESS``, ``VERSION_EQUAL``, or
-``VERSION_GREATER`` operators to compare version string values against
-``CMAKE_VERSION`` using a component-wise test.  Version component
-values may be 10 or larger so do not attempt to compare version
-strings as floating-point numbers.
+Use the :command:`if` command ``VERSION_LESS``, ``VERSION_GREATER``,
+``VERSION_EQUAL``, ``VERSION_LESS_EQUAL``, or ``VERSION_GREATER_EQUAL``
+operators to compare version string values against ``CMAKE_VERSION`` using a
+component-wise test.  Version component values may be 10 or larger so do not
+attempt to compare version strings as floating-point numbers.
 
 .. note::
 
diff --git a/Help/variable/MSVC10.rst b/Help/variable/MSVC10.rst
index 33692ad..98e0493 100644
--- a/Help/variable/MSVC10.rst
+++ b/Help/variable/MSVC10.rst
@@ -1,6 +1,5 @@
 MSVC10
 ------
 
-``True`` when using Microsoft Visual C++ 10.0
-
-Set to ``true`` when the compiler is version 10.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v100`` toolset
+(``cl`` version 16) or another compiler that simulates it.
diff --git a/Help/variable/MSVC11.rst b/Help/variable/MSVC11.rst
index 3ab606d..42b7b86 100644
--- a/Help/variable/MSVC11.rst
+++ b/Help/variable/MSVC11.rst
@@ -1,6 +1,5 @@
 MSVC11
 ------
 
-``True`` when using Microsoft Visual C++ 11.0
-
-Set to ``true`` when the compiler is version 11.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v110`` toolset
+(``cl`` version 17) or another compiler that simulates it.
diff --git a/Help/variable/MSVC12.rst b/Help/variable/MSVC12.rst
index 15fa64b..0648f35 100644
--- a/Help/variable/MSVC12.rst
+++ b/Help/variable/MSVC12.rst
@@ -1,6 +1,5 @@
 MSVC12
 ------
 
-``True`` when using Microsoft Visual C++ 12.0.
-
-Set to ``true`` when the compiler is version 12.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v120`` toolset
+(``cl`` version 18) or another compiler that simulates it.
diff --git a/Help/variable/MSVC14.rst b/Help/variable/MSVC14.rst
index 0b9125d..f67ebc7 100644
--- a/Help/variable/MSVC14.rst
+++ b/Help/variable/MSVC14.rst
@@ -1,6 +1,5 @@
 MSVC14
 ------
 
-``True`` when using Microsoft Visual C++ 14.0.
-
-Set to ``true`` when the compiler is version 14.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v140`` toolset
+(``cl`` version 19) or another compiler that simulates it.
diff --git a/Help/variable/MSVC80.rst b/Help/variable/MSVC80.rst
index b17777c..0d33e82 100644
--- a/Help/variable/MSVC80.rst
+++ b/Help/variable/MSVC80.rst
@@ -1,6 +1,5 @@
 MSVC80
 ------
 
-``True`` when using Microsoft Visual C++ 8.0.
-
-Set to ``true`` when the compiler is version 8.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v80`` toolset
+(``cl`` version 14) or another compiler that simulates it.
diff --git a/Help/variable/MSVC90.rst b/Help/variable/MSVC90.rst
index 7162d6c..1716e6f 100644
--- a/Help/variable/MSVC90.rst
+++ b/Help/variable/MSVC90.rst
@@ -1,6 +1,5 @@
 MSVC90
 ------
 
-``True`` when using Microsoft Visual C++ 9.0.
-
-Set to ``true`` when the compiler is version 9.0 of Microsoft Visual C++.
+``True`` when using the Microsoft Visual Studio ``v90`` toolset
+(``cl`` version 15) or another compiler that simulates it.
diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst
index ef3b0b5..e2aff3c 100644
--- a/Help/variable/MSVC_VERSION.rst
+++ b/Help/variable/MSVC_VERSION.rst
@@ -13,4 +13,4 @@ Known version numbers are::
   1600 = VS 10.0
   1700 = VS 11.0
   1800 = VS 12.0
-  1900 = VS 14.0
+  1900 = VS 14.0, 15.0
diff --git a/Help/variable/XCODE.rst b/Help/variable/XCODE.rst
new file mode 100644
index 0000000..99f20fb
--- /dev/null
+++ b/Help/variable/XCODE.rst
@@ -0,0 +1,4 @@
+XCODE
+-----
+
+``True`` when using :generator:`Xcode` generator.
diff --git a/Licenses/LGPLv3.txt b/Licenses/LGPLv3.txt
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/Licenses/LGPLv3.txt
@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/Modules/AddFileDependencies.cmake b/Modules/AddFileDependencies.cmake
index 4d01a52..fdd8432 100644
--- a/Modules/AddFileDependencies.cmake
+++ b/Modules/AddFileDependencies.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # AddFileDependencies
 # -------------------
@@ -6,19 +9,6 @@
 #
 # Adds the given files as dependencies to source_file
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(ADD_FILE_DEPENDENCIES _file)
 
    get_source_file_property(_deps ${_file} OBJECT_DEPENDS)
diff --git a/Modules/AndroidTestUtilities.cmake b/Modules/AndroidTestUtilities.cmake
new file mode 100644
index 0000000..a0a74fa
--- /dev/null
+++ b/Modules/AndroidTestUtilities.cmake
@@ -0,0 +1,157 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[======================================================================[.rst:
+AndroidTestUtilities
+------------------------
+
+Create a test that automatically loads specified data onto an Android device.
+
+Introduction
+^^^^^^^^^^^^
+
+Use this module to push data needed for testing an Android device behavior
+onto a connected Android device. The module will accept files and libraries as
+well as separate destinations for each. It will create a test that loads the
+files into a device object store and link to them from the specified
+destination. The files are only uploaded if they are not already in the object
+store.
+
+For example:
+
+.. code-block:: cmake
+
+  include(AndroidTestUtilities)
+  android_add_test_data(
+    example_setup_test
+    FILES <files>...
+    LIBS <libs>...
+    DEVICE_TEST_DIR "/data/local/tests/example"
+    DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA"
+    )
+
+
+At build time a test named "example_setup_test" will be created.  Run this test
+on the command line with :manual:`ctest(1)` to load the data onto the Android
+device.
+
+Module Functions
+^^^^^^^^^^^^^^^^
+
+.. command:: android_add_test_data
+
+  ::
+
+    android_add_test_data(<test-name>
+      [FILES <files>...] [FILES_DEST <device-dir>]
+      [LIBS <libs>...]   [LIBS_DEST <device-dir>]
+      [DEVICE_OBJECT_STORE <device-dir>]
+      [DEVICE_TEST_DIR <device-dir>]
+      [NO_LINK_REGEX <strings>...]
+      )
+
+  The ``android_add_test_data`` function is used to copy files and libraries
+  needed to run project-specific tests. On the host operating system, this is
+  done at build time. For on-device testing, the files are loaded onto the
+  device by the manufactured test at run time.
+
+  This function accepts the following named parameters:
+
+  ``FILES <files>...``
+    zero or more files needed for testing
+  ``LIBS <libs>...``
+    zero or more libraries needed for testing
+  ``FILES_DEST <device-dir>``
+    absolute path where the data files are expected to be
+  ``LIBS_DEST <device-dir>``
+    absolute path where the libraries are expected to be
+  ``DEVICE_OBJECT_STORE <device-dir>``
+    absolute path to the location where the data is stored on-device
+  ``DEVICE_TEST_DIR <device-dir>``
+    absolute path to the root directory of the on-device test location
+  ``NO_LINK_REGEX <strings>...``
+    list of regex strings matching the names of files that should be
+    copied from the object store to the testing directory
+#]======================================================================]
+
+include(${CMAKE_CURRENT_LIST_DIR}/ExternalData.cmake)
+
+set(_AndroidTestUtilities_SELF_DIR "${CMAKE_CURRENT_LIST_DIR}")
+
+# The parameters to this function should be set to the list of directories,
+# files, and libraries that need to be installed prior to testing.
+function(android_add_test_data test_name)
+  # As the names suggest, oneValueArgs lists the arguments that specify a
+  # single value, while multiValueArgs can contain one or more values.
+  set(keywordArgs)
+  set(oneValueArgs FILES_DEST LIBS_DEST DEVICE_OBJECT_STORE DEVICE_TEST_DIR)
+  set(multiValueArgs FILES LIBS NO_LINK_REGEX)
+
+  # For example, if you called this function with FILES </path/to/file>
+  # then this path would be stored in the variable AST_FILES.
+  # The AST prefix stands for the name of this function (android_add_test_data).
+  cmake_parse_arguments(AST "${keywordArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+  if(NOT AST_DEVICE_TEST_DIR)
+    message(FATAL_ERROR "-- You must specify the location of the on device test directory.")
+  endif()
+  if(NOT AST_DEVICE_OBJECT_STORE)
+    message(FATAL_ERROR "-- You must specify the location of the on device object store.")
+  endif()
+  if(${AST_DEVICE_TEST_DIR} STREQUAL "/")
+    message(FATAL_ERROR "-- The device test directory cannot be '/'")
+  endif()
+
+  # Copy all test data files into the binary directory, where tests are run.
+  # ExternalData will handle fetching DATA{...} references.
+  string(REPLACE "|" ";" hash_algs "${_ExternalData_REGEX_EXT}")
+  # Convert ExternalData placeholder file names to DATA{} syntax.
+  foreach(alg ${hash_algs})
+    string(REGEX REPLACE "([^ ;]+)\\.${alg}" "DATA{\\1}" AST_FILES "${AST_FILES}")
+  endforeach()
+
+  set(DATA_TARGET_NAME "${test_name}")
+  ExternalData_Expand_Arguments(
+    ${DATA_TARGET_NAME}
+    extern_data_output
+    ${AST_FILES})
+  ExternalData_Add_Target(${DATA_TARGET_NAME})
+
+  # For regular files on Linux, just copy them directly.
+  foreach(path ${AST_FILES})
+    foreach(output ${extern_data_output})
+      if(${output} STREQUAL ${path})
+        # Check if a destination was specified.  If not, we copy by default
+        # into this project's binary directory, preserving its relative path.
+        if(AST_${VAR}_DEST)
+          set(DEST ${CMAKE_BINARY_DIR}/${parent_dir}/${AST_${VAR}_DEST})
+        else()
+          get_filename_component(parent_dir ${path} DIRECTORY)
+          set(DEST "${CMAKE_BINARY_DIR}/${parent_dir}")
+        endif()
+        get_filename_component(extern_data_source ${output} REALPATH)
+        get_filename_component(extern_data_basename ${output} NAME)
+        add_custom_command(
+          TARGET ${DATA_TARGET_NAME} POST_BUILD
+          DEPENDS ${extern_data_source}
+          COMMAND ${CMAKE_COMMAND} -E copy_if_different ${extern_data_source} ${DEST}/${extern_data_basename}
+        )
+      endif()
+    endforeach()
+  endforeach()
+
+  if(ANDROID)
+    string(REGEX REPLACE "DATA{([^ ;]+)}" "\\1"  processed_FILES "${AST_FILES}")
+    add_test(
+      NAME ${test_name}
+      COMMAND ${CMAKE_COMMAND}
+      "-Darg_files_dest=${AST_FILES_DEST}"
+      "-Darg_libs_dest=${AST_LIBS_DEST}"
+      "-Darg_dev_test_dir=${AST_DEVICE_TEST_DIR}"
+      "-Darg_dev_obj_store=${AST_DEVICE_OBJECT_STORE}"
+      "-Darg_no_link_regex=${AST_NO_LINK_REGEX}"
+      "-Darg_files=${processed_FILES}"
+      "-Darg_libs=${AST_LIBS}"
+      "-Darg_src_dir=${CMAKE_CURRENT_SOURCE_DIR}"
+      -P ${_AndroidTestUtilities_SELF_DIR}/AndroidTestUtilities/PushToAndroidDevice.cmake)
+  endif()
+endfunction()
diff --git a/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake b/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake
new file mode 100644
index 0000000..f5f2564
--- /dev/null
+++ b/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake
@@ -0,0 +1,174 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This function handles pushing all of the test files needed to the device.
+# It places the data files in the object store and makes links to them from
+# the appropriate directories.
+#
+# This function accepts the following named parameters:
+# DIRS          : one or more directories needed for testing.
+# FILES         : one or more files needed for testing.
+# LIBS          : one or more libraries needed for testing.
+# DIRS_DEST     : specify where the directories should be installed.
+# FILES_DEST    : specify where the files should be installed.
+# LIBS_DEST     : specify where the libraries should be installed.
+# DEV_OBJ_STORE : specify where the actual data files should be placed.
+# DEV_TEST_DIR  : specify the root file for the module test directory.
+# The DEV_OBJ_STORE and DEV_TEST_DIR variables are required.
+
+# The parameters to this function should be set to the list of directories,
+# files, and libraries that need to be installed prior to testing.
+function(android_push_test_files_to_device)
+
+  # The functions in the module need the adb executable.
+  find_program(adb_executable adb)
+  if(NOT adb_executable)
+    message(FATAL_ERROR "could not find adb")
+  endif()
+
+  function(execute_adb_command)
+    execute_process(COMMAND ${adb_executable} ${ARGN} RESULT_VARIABLE res_var OUTPUT_VARIABLE out_var ERROR_VARIABLE err_var)
+    set(out_var ${out_var} PARENT_SCOPE)
+    if(res_var)
+      string(REGEX REPLACE ";" " " com "${ARGN}")
+      message(FATAL_ERROR "Error occured during adb command: adb ${com}\nError: ${err_var}.")
+    endif()
+  endfunction()
+
+  # Checks to make sure that a given file exists on the device. If it does,
+  # if(file_exists) will return true.
+  macro(check_device_file_exists device_file file_exists)
+    set(${file_exists} "")
+    execute_adb_command(shell ls ${device_file})
+    if(NOT out_var) # when a directory exists but is empty the output is empty
+      set(${file_exists} "YES")
+    else()
+      string(FIND ${out_var} "No such file or directory" no_file_exists)
+      if(${no_file_exists} STREQUAL "-1") # -1 means the file exists
+        set(${file_exists} "YES")
+      endif()
+    endif()
+  endmacro()
+
+  # Checks to see if a filename matches a regex.
+  function(filename_regex filename reg_ex)
+    string(REGEX MATCH ${reg_ex} filename_match ${filename})
+    set(filename_match ${filename_match} PARENT_SCOPE)
+  endfunction()
+
+  # If a file with given name exists in the CMAKE_BINARY_DIR then use that file.
+  # Otherwise use the file with root in CMAKE_CURRENT_SOURCE_DIR.
+  macro(set_absolute_path relative_path absolute_path)
+    set(${absolute_path} ${arg_src_dir}/${relative_path})
+    if(EXISTS ${CMAKE_BINARY_DIR}/${relative_path})
+      set(${absolute_path} ${CMAKE_BINARY_DIR}/${relative_path})
+    endif()
+    if(NOT EXISTS ${${absolute_path}})
+      if(EXISTS ${relative_path})
+        set(${absolute_path} ${relative_path})
+      else()
+        message(FATAL_ERROR "Cannot find file for specified path: ${relative_path}")
+      endif()
+    endif()
+  endmacro()
+
+  # This function pushes the data into the device object store and
+  # creates a link to that data file in a specified location.
+  #
+  # This function requires the following un-named parameters:
+  # data_path        : absolute path to data to load into dev obj store.
+  # dev_object_store : absolute path to the device object store directory.
+  # link_origin      : absolute path to the origin of the link to the dev obj store data file.
+  function(push_and_link data_path dev_object_store link_origin)
+    FILE(SHA1 ${data_path} hash_val)
+    set(obj_store_dst ${dev_object_store}/${hash_val})
+    check_device_file_exists(${obj_store_dst} obj_store_file_exists)
+    # TODO: Verify that the object store file is indeed hashed correctly. Could use md5.
+    if(NOT obj_store_file_exists)
+      execute_adb_command(push ${data_path} ${obj_store_dst})
+    endif()
+    check_device_file_exists(${link_origin} link_exists)
+    if(link_exists)
+      execute_adb_command(shell rm -f ${link_origin})
+    endif()
+    foreach(ex ${arg_no_link_regex})
+      filename_regex(${data_path} ${ex})
+      LIST(APPEND match_ex ${filename_match})
+    endforeach()
+    if(match_ex)
+      execute_adb_command(shell cp ${obj_store_dst} ${link_origin})
+    else()
+      execute_adb_command(shell ln -s ${obj_store_dst} ${link_origin})
+    endif()
+  endfunction()
+
+  #----------------------------------------------------------------------------
+  #--------------------Beginning of actual function----------------------------
+  #----------------------------------------------------------------------------
+  set(oneValueArgs FILES_DEST LIBS_DEST DEV_TEST_DIR DEV_OBJ_STORE)
+  set(multiValueArgs FILES LIBS)
+  cmake_parse_arguments(_ptd "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+  # Setup of object store and test dir.
+  check_device_file_exists(${_ptd_DEV_OBJ_STORE} dev_obj_store_exists)
+  if(NOT dev_obj_store_exists)
+    execute_adb_command(shell mkdir -p ${_ptd_DEV_OBJ_STORE})
+  endif()
+  check_device_file_exists(${_ptd_DEV_TEST_DIR} test_dir_exists)
+  if(test_dir_exists)
+    # This is protected in the SetupProjectTests module.
+    execute_adb_command(shell echo rm -r ${_ptd_DEV_TEST_DIR} | su)
+  endif()
+  execute_adb_command(shell mkdir -p ${_ptd_DEV_TEST_DIR})
+
+  # Looping over the various types of test data possible.
+  foreach(TYPE ${multiValueArgs})
+    if(_ptd_${TYPE})
+
+      # determine if the data type destination has been explicitly specified.
+      if(_ptd_${TYPE}_DEST)
+        set(dest ${_ptd_${TYPE}_DEST})
+      else()
+        if(${TYPE} STREQUAL LIBS)
+          set(dest ${_ptd_DEV_TEST_DIR}/lib)
+        else()
+          set(dest ${_ptd_DEV_TEST_DIR})
+        endif()
+      endif()
+      execute_adb_command(shell mkdir -p ${dest})
+
+      # Loop over the files passed in
+      foreach(relative_path ${_ptd_${TYPE}})
+        # The absolute path can be through the source directory or the build directory.
+        # If the file/dir exists in the build directory that version is chosen.
+        set_absolute_path(${relative_path} absolute_path)
+        # Need to transfer all data files in the data directories to the device
+        # except those explicitly ignored.
+        if(${TYPE} STREQUAL FILES)
+          get_filename_component(file_dir ${relative_path} DIRECTORY)
+          # dest was determined earlier, relative_path is a dir, file is path from relative path to a data
+          set(cur_dest ${dest}/${relative_path})
+          set(on_dev_dir ${dest}/${file_dir})
+          execute_adb_command(shell mkdir -p ${on_dev_dir})
+          if(IS_SYMLINK ${absolute_path})
+            get_filename_component(real_data_origin ${absolute_path} REALPATH)
+            push_and_link(${real_data_origin} ${_ptd_DEV_OBJ_STORE} ${cur_dest})
+          else()
+            push_and_link(${absolute_path} ${_ptd_DEV_OBJ_STORE} ${cur_dest})
+          endif()
+        else() # LIBS
+          execute_adb_command(push ${absolute_path} ${dest})
+        endif()
+      endforeach()
+    endif()
+  endforeach()
+endfunction()
+
+android_push_test_files_to_device(
+  FILES_DEST ${arg_files_dest}
+  LIBS_DEST ${arg_libs_dest}
+  DEV_TEST_DIR ${arg_dev_test_dir}
+  DEV_OBJ_STORE ${arg_dev_obj_store}
+  FILES ${arg_files}
+  LIBS ${arg_libs}
+  )
diff --git a/Modules/BundleUtilities.cmake b/Modules/BundleUtilities.cmake
index cfb6450..b1610e2 100644
--- a/Modules/BundleUtilities.cmake
+++ b/Modules/BundleUtilities.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # BundleUtilities
 # ---------------
@@ -216,19 +219,6 @@
 # that are already also in the bundle...  Anything that points to an
 # external file causes this function to fail the verification.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # The functions defined in this file depend on the get_prerequisites function
 # (and possibly others) found in:
 #
diff --git a/Modules/CMake.cmake b/Modules/CMake.cmake
index 53a0ddf..caa5479 100644
--- a/Modules/CMake.cmake
+++ b/Modules/CMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by cmake.cxx to compute the CMAKE_ROOT location.
 # Do not remove this file from cvs without updating cmake.cxx to look
diff --git a/Modules/CMakeASM-ATTInformation.cmake b/Modules/CMakeASM-ATTInformation.cmake
index 07a2d38..d1970a2 100644
--- a/Modules/CMakeASM-ATTInformation.cmake
+++ b/Modules/CMakeASM-ATTInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # support for AT&T syntax assemblers, e.g. GNU as
 
diff --git a/Modules/CMakeASMInformation.cmake b/Modules/CMakeASMInformation.cmake
index 0e547c4..01355ff 100644
--- a/Modules/CMakeASMInformation.cmake
+++ b/Modules/CMakeASMInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(UNIX)
   set(CMAKE_ASM${ASM_DIALECT}_OUTPUT_EXTENSION .o)
@@ -76,10 +66,11 @@ endif()
 
 # Support for CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT and friends:
 set(CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT "$ENV{ASM${ASM_DIALECT}FLAGS} ${CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT}")
-# avoid just having a space as the initial value for the cache
-if(CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT STREQUAL " ")
-  set(CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT)
-endif()
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_ASM${ASM_DIALECT}_FLAGS${c}_INIT}" CMAKE_ASM${ASM_DIALECT}_FLAGS${c}_INIT)
+endforeach()
+
 set (CMAKE_ASM${ASM_DIALECT}_FLAGS "${CMAKE_ASM${ASM_DIALECT}_FLAGS_INIT}" CACHE STRING
      "Flags used by the assembler during all build types.")
 
diff --git a/Modules/CMakeASM_MASMInformation.cmake b/Modules/CMakeASM_MASMInformation.cmake
index bd76b98..a38c114 100644
--- a/Modules/CMakeASM_MASMInformation.cmake
+++ b/Modules/CMakeASM_MASMInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # support for the MS assembler, masm and masm64
 
diff --git a/Modules/CMakeASM_NASMInformation.cmake b/Modules/CMakeASM_NASMInformation.cmake
index 146f412..1e3c608 100644
--- a/Modules/CMakeASM_NASMInformation.cmake
+++ b/Modules/CMakeASM_NASMInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # support for the nasm assembler
 
diff --git a/Modules/CMakeAddFortranSubdirectory.cmake b/Modules/CMakeAddFortranSubdirectory.cmake
index 2e5a76f..3b39bce 100644
--- a/Modules/CMakeAddFortranSubdirectory.cmake
+++ b/Modules/CMakeAddFortranSubdirectory.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeAddFortranSubdirectory
 # ---------------------------
@@ -39,20 +42,6 @@
 # future version that supports installation of the external project
 # binaries during "make install".
 
-#=============================================================================
-# Copyright 2011-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 set(_MS_MINGW_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR})
 include(CheckLanguage)
 include(ExternalProject)
diff --git a/Modules/CMakeBackwardCompatibilityC.cmake b/Modules/CMakeBackwardCompatibilityC.cmake
index 685cd52..228e063 100644
--- a/Modules/CMakeBackwardCompatibilityC.cmake
+++ b/Modules/CMakeBackwardCompatibilityC.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Nothing here yet
 if(CMAKE_GENERATOR MATCHES "Visual Studio 7")
diff --git a/Modules/CMakeBackwardCompatibilityCXX.cmake b/Modules/CMakeBackwardCompatibilityCXX.cmake
index f1db46e..cbd5ea7 100644
--- a/Modules/CMakeBackwardCompatibilityCXX.cmake
+++ b/Modules/CMakeBackwardCompatibilityCXX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeBackwardCompatibilityCXX
 # -----------------------------
@@ -13,19 +16,6 @@
 #   include(TestForSTDNamespace)
 #   include(TestForANSIForScope)
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT CMAKE_SKIP_COMPATIBILITY_TESTS)
   # check for some ANSI flags in the CXX compiler if it is not gnu
   if(NOT CMAKE_COMPILER_IS_GNUCXX)
@@ -50,7 +40,7 @@ if(NOT CMAKE_SKIP_COMPATIBILITY_TESTS)
     endif()
   endif()
   set(CMAKE_CXX_FLAGS_SAVE ${CMAKE_CXX_FLAGS})
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_ANSI_CXXFLAGS}")
+  string(APPEND CMAKE_CXX_FLAGS " ${CMAKE_ANSI_CXXFLAGS}")
   include(TestForANSIStreamHeaders)
   include(CheckIncludeFileCXX)
   include(TestForSTDNamespace)
diff --git a/Modules/CMakeBorlandFindMake.cmake b/Modules/CMakeBorlandFindMake.cmake
index 43b31c6..18b9962 100644
--- a/Modules/CMakeBorlandFindMake.cmake
+++ b/Modules/CMakeBorlandFindMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 set (CMAKE_MAKE_PROGRAM "make" CACHE STRING
      "Program used to build from makefiles.")
diff --git a/Modules/CMakeCCompiler.cmake.in b/Modules/CMakeCCompiler.cmake.in
index f109a14..50b12f2 100644
--- a/Modules/CMakeCCompiler.cmake.in
+++ b/Modules/CMakeCCompiler.cmake.in
@@ -59,6 +59,7 @@ if(CMAKE_C_CL_SHOWINCLUDES_PREFIX)
   set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}")
 endif()
 
+ at CMAKE_C_COMPILER_CUSTOM_CODE@
 @CMAKE_C_SYSROOT_FLAG_CODE@
 @CMAKE_C_OSX_DEPLOYMENT_TARGET_FLAG_CODE@
 
diff --git a/Modules/CMakeCInformation.cmake b/Modules/CMakeCInformation.cmake
index fa87ca8..709e316 100644
--- a/Modules/CMakeCInformation.cmake
+++ b/Modules/CMakeCInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file sets the basic flags for the C language in CMake.
 # It also loads the available platform file for the system-compiler
@@ -111,10 +101,11 @@ if(NOT CMAKE_MODULE_EXISTS)
 endif()
 
 set(CMAKE_C_FLAGS_INIT "$ENV{CFLAGS} ${CMAKE_C_FLAGS_INIT}")
-# avoid just having a space as the initial value for the cache
-if(CMAKE_C_FLAGS_INIT STREQUAL " ")
-  set(CMAKE_C_FLAGS_INIT)
-endif()
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_C_FLAGS${c}_INIT}" CMAKE_C_FLAGS${c}_INIT)
+endforeach()
+
 set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS_INIT}" CACHE STRING
      "Flags used by the compiler during all build types.")
 
diff --git a/Modules/CMakeCXXCompiler.cmake.in b/Modules/CMakeCXXCompiler.cmake.in
index 9e90aea..c295b74 100644
--- a/Modules/CMakeCXXCompiler.cmake.in
+++ b/Modules/CMakeCXXCompiler.cmake.in
@@ -60,6 +60,7 @@ if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX)
   set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}")
 endif()
 
+ at CMAKE_CXX_COMPILER_CUSTOM_CODE@
 @CMAKE_CXX_SYSROOT_FLAG_CODE@
 @CMAKE_CXX_OSX_DEPLOYMENT_TARGET_FLAG_CODE@
 
diff --git a/Modules/CMakeCXXInformation.cmake b/Modules/CMakeCXXInformation.cmake
index b35280f..ec731fa 100644
--- a/Modules/CMakeCXXInformation.cmake
+++ b/Modules/CMakeCXXInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file sets the basic flags for the C++ language in CMake.
 # It also loads the available platform file for the system-compiler
@@ -206,10 +196,11 @@ endforeach()
 # use _INIT variables so that this only happens the first time
 # and you can set these flags in the cmake cache
 set(CMAKE_CXX_FLAGS_INIT "$ENV{CXXFLAGS} ${CMAKE_CXX_FLAGS_INIT}")
-# avoid just having a space as the initial value for the cache
-if(CMAKE_CXX_FLAGS_INIT STREQUAL " ")
-  set(CMAKE_CXX_FLAGS_INIT)
-endif()
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_CXX_FLAGS${c}_INIT}" CMAKE_CXX_FLAGS${c}_INIT)
+endforeach()
+
 set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_INIT}" CACHE STRING
      "Flags used by the compiler during all build types.")
 
diff --git a/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake b/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
index a350a84..1b5178d 100644
--- a/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
+++ b/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
@@ -1,19 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2011 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2011 Matthias Kretz <kretz at kde.org>
-# Copyright 2013 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Do NOT include this module directly into any of your code. It is meant as
 # a library for Check*CompilerFlag.cmake modules. It's content may change in
diff --git a/Modules/CMakeCommonLanguageInclude.cmake b/Modules/CMakeCommonLanguageInclude.cmake
index fa025a8..418860e 100644
--- a/Modules/CMakeCommonLanguageInclude.cmake
+++ b/Modules/CMakeCommonLanguageInclude.cmake
@@ -1,26 +1,20 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # this file has flags that are shared across languages and sets
 # cache values that can be initialized in the platform-compiler.cmake file
 # it may be included by more than one language.
 
-if(NOT "x$ENV{LDFLAGS}" STREQUAL "x")
-  set (CMAKE_EXE_LINKER_FLAGS_INIT "${CMAKE_EXE_LINKER_FLAGS_INIT} $ENV{LDFLAGS}")
-  set (CMAKE_SHARED_LINKER_FLAGS_INIT "${CMAKE_SHARED_LINKER_FLAGS_INIT} $ENV{LDFLAGS}")
-  set (CMAKE_MODULE_LINKER_FLAGS_INIT "${CMAKE_MODULE_LINKER_FLAGS_INIT} $ENV{LDFLAGS}")
-endif()
+string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " $ENV{LDFLAGS}")
+string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " $ENV{LDFLAGS}")
+string(APPEND CMAKE_MODULE_LINKER_FLAGS_INIT " $ENV{LDFLAGS}")
+
+foreach(t EXE SHARED MODULE STATIC)
+  foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+    string(STRIP "${CMAKE_${t}_LINKER_FLAGS${c}_INIT}" CMAKE_${t}_LINKER_FLAGS${c}_INIT)
+  endforeach()
+endforeach()
 
 if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
 # default build type is none
diff --git a/Modules/CMakeCompilerIdDetection.cmake b/Modules/CMakeCompilerIdDetection.cmake
index 1d341e5..4732250 100644
--- a/Modules/CMakeCompilerIdDetection.cmake
+++ b/Modules/CMakeCompilerIdDetection.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2014 Stephen Kelly <steveire at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 function(_readFile file)
   include(${file})
@@ -120,18 +110,18 @@ function(compiler_id_detection outvar lang)
       if (CID_ID_STRING)
         set(PREFIX ${CID_PREFIX})
         string(CONFIGURE "${_compiler_id_simulate_${Id}}" SIMULATE_BLOCK @ONLY)
-        set(id_content "${id_content}# define ${CID_PREFIX}COMPILER_ID \"${Id}\"${SIMULATE_BLOCK}")
+        string(APPEND id_content "# define ${CID_PREFIX}COMPILER_ID \"${Id}\"${SIMULATE_BLOCK}")
       endif()
       if (CID_ID_DEFINE)
-        set(id_content "${id_content}# undef ${CID_PREFIX}COMPILER_IS_${Id}\n")
-        set(id_content "${id_content}# define ${CID_PREFIX}COMPILER_IS_${Id} 1\n")
+        string(APPEND id_content "# undef ${CID_PREFIX}COMPILER_IS_${Id}\n")
+        string(APPEND id_content "# define ${CID_PREFIX}COMPILER_IS_${Id} 1\n")
       endif()
       if (CID_VERSION_STRINGS)
         set(PREFIX ${CID_PREFIX})
         set(MACRO_DEC DEC)
         set(MACRO_HEX HEX)
         string(CONFIGURE "${_compiler_id_version_compute_${Id}}" VERSION_BLOCK @ONLY)
-        set(id_content "${id_content}${VERSION_BLOCK}\n")
+        string(APPEND id_content "${VERSION_BLOCK}\n")
       endif()
       set(CMAKE_${lang}_COMPILER_ID_CONTENT "${CMAKE_${lang}_COMPILER_ID_CONTENT}\n${id_content}")
       set(pp_if "#elif")
diff --git a/Modules/CMakeDependentOption.cmake b/Modules/CMakeDependentOption.cmake
index 7e9f183..21d3c96 100644
--- a/Modules/CMakeDependentOption.cmake
+++ b/Modules/CMakeDependentOption.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeDependentOption
 # --------------------
@@ -20,19 +23,6 @@
 # the USE_FOO option is saved so that when the option is re-enabled it
 # retains its old value.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CMAKE_DEPENDENT_OPTION option doc default depends force)
   if(${option}_ISSET MATCHES "^${option}_ISSET$")
     set(${option}_AVAILABLE 1)
diff --git a/Modules/CMakeDetermineASM-ATTCompiler.cmake b/Modules/CMakeDetermineASM-ATTCompiler.cmake
index 03c5668..a2efb6a 100644
--- a/Modules/CMakeDetermineASM-ATTCompiler.cmake
+++ b/Modules/CMakeDetermineASM-ATTCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for ASM using AT&T syntax, e.g. GNU as
 
diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake
index 91111d2..deb10fb 100644
--- a/Modules/CMakeDetermineASMCompiler.cmake
+++ b/Modules/CMakeDetermineASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for ASM programs
 
diff --git a/Modules/CMakeDetermineASM_MASMCompiler.cmake b/Modules/CMakeDetermineASM_MASMCompiler.cmake
index 142ef95..789b049 100644
--- a/Modules/CMakeDetermineASM_MASMCompiler.cmake
+++ b/Modules/CMakeDetermineASM_MASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Find the MS assembler (masm or masm64)
 
diff --git a/Modules/CMakeDetermineASM_NASMCompiler.cmake b/Modules/CMakeDetermineASM_NASMCompiler.cmake
index 5d783b1..4c8e422 100644
--- a/Modules/CMakeDetermineASM_NASMCompiler.cmake
+++ b/Modules/CMakeDetermineASM_NASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Find the nasm assembler. yasm (http://www.tortall.net/projects/yasm/) is nasm compatible
 
diff --git a/Modules/CMakeDetermineCCompiler.cmake b/Modules/CMakeDetermineCCompiler.cmake
index f8c6303..4a315e0 100644
--- a/Modules/CMakeDetermineCCompiler.cmake
+++ b/Modules/CMakeDetermineCCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for C programs
 # NOTE, a generator may set CMAKE_C_COMPILER before
@@ -34,6 +24,7 @@
 include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
 
 # Load system-specific compiler preferences for this language.
+include(Platform/${CMAKE_SYSTEM_NAME}-Determine-C OPTIONAL)
 include(Platform/${CMAKE_SYSTEM_NAME}-C OPTIONAL)
 if(NOT CMAKE_C_COMPILER_NAMES)
   set(CMAKE_C_COMPILER_NAMES cc)
@@ -104,7 +95,7 @@ if(NOT CMAKE_C_COMPILER_ID_RUN)
     CMAKE_C_COMPILER_ID_PLATFORM_CONTENT)
 
   # The IAR compiler produces weird output.
-  # See https://cmake.org/Bug/view.php?id=10176#c19598
+  # See https://gitlab.kitware.com/cmake/cmake/issues/10176#note_153591
   list(APPEND CMAKE_C_COMPILER_ID_VENDORS IAR)
   set(CMAKE_C_COMPILER_ID_VENDOR_FLAGS_IAR )
   set(CMAKE_C_COMPILER_ID_VENDOR_REGEX_IAR "IAR .+ Compiler")
diff --git a/Modules/CMakeDetermineCXXCompiler.cmake b/Modules/CMakeDetermineCXXCompiler.cmake
index 3c9bbc2..f2e0bb2 100644
--- a/Modules/CMakeDetermineCXXCompiler.cmake
+++ b/Modules/CMakeDetermineCXXCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for C++ programs
 # NOTE, a generator may set CMAKE_CXX_COMPILER before
@@ -33,6 +23,7 @@
 include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
 
 # Load system-specific compiler preferences for this language.
+include(Platform/${CMAKE_SYSTEM_NAME}-Determine-CXX OPTIONAL)
 include(Platform/${CMAKE_SYSTEM_NAME}-CXX OPTIONAL)
 if(NOT CMAKE_CXX_COMPILER_NAMES)
   set(CMAKE_CXX_COMPILER_NAMES CC)
@@ -96,7 +87,7 @@ if(NOT CMAKE_CXX_COMPILER_ID_RUN)
     CMAKE_CXX_COMPILER_ID_PLATFORM_CONTENT)
 
   # The IAR compiler produces weird output.
-  # See https://cmake.org/Bug/view.php?id=10176#c19598
+  # See https://gitlab.kitware.com/cmake/cmake/issues/10176#note_153591
   list(APPEND CMAKE_CXX_COMPILER_ID_VENDORS IAR)
   set(CMAKE_CXX_COMPILER_ID_VENDOR_FLAGS_IAR )
   set(CMAKE_CXX_COMPILER_ID_VENDOR_REGEX_IAR "IAR .+ Compiler")
diff --git a/Modules/CMakeDetermineCompileFeatures.cmake b/Modules/CMakeDetermineCompileFeatures.cmake
index 2bb7a74..5ca72cc 100644
--- a/Modules/CMakeDetermineCompileFeatures.cmake
+++ b/Modules/CMakeDetermineCompileFeatures.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2013 Stephen Kelly <steveire at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 function(cmake_determine_compile_features lang)
 
diff --git a/Modules/CMakeDetermineCompiler.cmake b/Modules/CMakeDetermineCompiler.cmake
index 85c8662..c37adae 100644
--- a/Modules/CMakeDetermineCompiler.cmake
+++ b/Modules/CMakeDetermineCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 macro(_cmake_find_compiler lang)
   # Use already-enabled languages for reference.
diff --git a/Modules/CMakeDetermineCompilerABI.cmake b/Modules/CMakeDetermineCompilerABI.cmake
index 344ae47..604ac27 100644
--- a/Modules/CMakeDetermineCompilerABI.cmake
+++ b/Modules/CMakeDetermineCompilerABI.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Function to compile a source file to identify the compiler ABI.
 # This is used internally by CMake and should not be included by user
diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake
index 465989d..145efc6 100644
--- a/Modules/CMakeDetermineCompilerId.cmake
+++ b/Modules/CMakeDetermineCompilerId.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Function to compile a source file to identify the compiler.  This is
 # used internally by CMake and should not be included by user code.
@@ -266,6 +256,11 @@ Id flags: ${testflags}
     else()
       set(id_toolset "")
     endif()
+    if("${lang}" STREQUAL "Swift")
+      set(id_lang_version "SWIFT_VERSION = 2.3;")
+    else()
+      set(id_lang_version "")
+    endif()
     if(CMAKE_OSX_DEPLOYMENT_TARGET)
       set(id_deployment_target
         "MACOSX_DEPLOYMENT_TARGET = \"${CMAKE_OSX_DEPLOYMENT_TARGET}\";")
@@ -365,14 +360,15 @@ ${CMAKE_${lang}_COMPILER_ID_OUTPUT}
 
     # Find the executable produced by the compiler, try all files in the
     # binary dir.
+    string(REGEX REPLACE "([][])" "[\\1]" _glob_id_dir "${CMAKE_${lang}_COMPILER_ID_DIR}")
     file(GLOB files
       RELATIVE ${CMAKE_${lang}_COMPILER_ID_DIR}
 
       # normal case
-      ${CMAKE_${lang}_COMPILER_ID_DIR}/*
+      ${_glob_id_dir}/*
 
       # com.apple.package-type.bundle.unit-test
-      ${CMAKE_${lang}_COMPILER_ID_DIR}/*.xctest/*
+      ${_glob_id_dir}/*.xctest/*
       )
     list(REMOVE_ITEM files "${src}")
     set(COMPILER_${lang}_PRODUCED_FILES "")
@@ -492,11 +488,11 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
     if(NOT DEFINED COMPILER_VERSION AND HAVE_COMPILER_VERSION_MAJOR)
       set(COMPILER_VERSION "${COMPILER_VERSION_MAJOR}")
       if(HAVE_COMPILER_VERSION_MINOR)
-        set(COMPILER_VERSION "${COMPILER_VERSION}.${COMPILER_VERSION_MINOR}")
+        string(APPEND COMPILER_VERSION ".${COMPILER_VERSION_MINOR}")
         if(HAVE_COMPILER_VERSION_PATCH)
-          set(COMPILER_VERSION "${COMPILER_VERSION}.${COMPILER_VERSION_PATCH}")
+          string(APPEND COMPILER_VERSION ".${COMPILER_VERSION_PATCH}")
           if(HAVE_COMPILER_VERSION_TWEAK)
-            set(COMPILER_VERSION "${COMPILER_VERSION}.${COMPILER_VERSION_TWEAK}")
+            string(APPEND COMPILER_VERSION ".${COMPILER_VERSION_TWEAK}")
           endif()
         endif()
       endif()
diff --git a/Modules/CMakeDetermineFortranCompiler.cmake b/Modules/CMakeDetermineFortranCompiler.cmake
index 4f2a70c..484fa66 100644
--- a/Modules/CMakeDetermineFortranCompiler.cmake
+++ b/Modules/CMakeDetermineFortranCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for Fortran programs
 # NOTE, a generator may set CMAKE_Fortran_COMPILER before
@@ -20,6 +10,7 @@
 # as a default compiler
 
 include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
+include(Platform/${CMAKE_SYSTEM_NAME}-Determine-Fortran OPTIONAL)
 include(Platform/${CMAKE_SYSTEM_NAME}-Fortran OPTIONAL)
 if(NOT CMAKE_Fortran_COMPILER_NAMES)
   set(CMAKE_Fortran_COMPILER_NAMES f95)
@@ -140,10 +131,10 @@ if(NOT CMAKE_Fortran_COMPILER_ID_RUN)
   set(_version_info "")
   foreach(m MAJOR MINOR PATCH TWEAK)
     set(_COMP "_${m}")
-    set(_version_info "${_version_info}
+    string(APPEND _version_info "
 #if defined(COMPILER_VERSION${_COMP})")
     foreach(d 1 2 3 4 5 6 7 8)
-      set(_version_info "${_version_info}
+      string(APPEND _version_info "
 # undef DEC
 # undef HEX
 # define DEC(n) DEC_${d}(n)
@@ -171,7 +162,7 @@ if(NOT CMAKE_Fortran_COMPILER_ID_RUN)
 # endif
 ")
     endforeach()
-    set(_version_info "${_version_info}
+    string(APPEND _version_info "
 #endif")
   endforeach()
   set(CMAKE_Fortran_COMPILER_ID_VERSION_INFO "${_version_info}")
diff --git a/Modules/CMakeDetermineJavaCompiler.cmake b/Modules/CMakeDetermineJavaCompiler.cmake
index f657801..3092bb5 100644
--- a/Modules/CMakeDetermineJavaCompiler.cmake
+++ b/Modules/CMakeDetermineJavaCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for Java programs
 # NOTE, a generator may set CMAKE_Java_COMPILER before
diff --git a/Modules/CMakeDetermineRCCompiler.cmake b/Modules/CMakeDetermineRCCompiler.cmake
index e5414eb..8801e16 100644
--- a/Modules/CMakeDetermineRCCompiler.cmake
+++ b/Modules/CMakeDetermineRCCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # determine the compiler to use for RC programs
 # NOTE, a generator may set CMAKE_RC_COMPILER before
diff --git a/Modules/CMakeDetermineSwiftCompiler.cmake b/Modules/CMakeDetermineSwiftCompiler.cmake
index bff1ae9..2604906 100644
--- a/Modules/CMakeDetermineSwiftCompiler.cmake
+++ b/Modules/CMakeDetermineSwiftCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
 
diff --git a/Modules/CMakeDetermineSystem.cmake b/Modules/CMakeDetermineSystem.cmake
index d9f7579..8675553 100644
--- a/Modules/CMakeDetermineSystem.cmake
+++ b/Modules/CMakeDetermineSystem.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is used by the Makefile generator to determin the following variables:
 # CMAKE_SYSTEM_NAME - on unix this is uname -s, for windows it is Windows
@@ -131,6 +121,7 @@ else()
   set(PRESET_CMAKE_SYSTEM_NAME FALSE)
 endif()
 
+include(Platform/${CMAKE_SYSTEM_NAME}-Determine OPTIONAL)
 
 macro(ADJUST_CMAKE_SYSTEM_VARIABLES _PREFIX)
   if(NOT ${_PREFIX}_NAME)
diff --git a/Modules/CMakeDetermineVSServicePack.cmake b/Modules/CMakeDetermineVSServicePack.cmake
index 6886084..0264621 100644
--- a/Modules/CMakeDetermineVSServicePack.cmake
+++ b/Modules/CMakeDetermineVSServicePack.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeDetermineVSServicePack
 # ---------------------------
@@ -28,21 +31,6 @@
 #   vc100, vc100sp1
 #   vc110, vc110sp1, vc110sp2, vc110sp3, vc110sp4
 
-#=============================================================================
-# Copyright 2009-2013 Kitware, Inc.
-# Copyright 2009-2010 Philip Lowman <philip at yhbt.com>
-# Copyright 2010-2011 Aaron C. meadows <cmake at shadowguarddev.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.8)
   message(DEPRECATION
     "This module is deprecated and should not be used.  "
diff --git a/Modules/CMakeExpandImportedTargets.cmake b/Modules/CMakeExpandImportedTargets.cmake
index 28f2e46..add0c6d 100644
--- a/Modules/CMakeExpandImportedTargets.cmake
+++ b/Modules/CMakeExpandImportedTargets.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeExpandImportedTargets
 # --------------------------
@@ -35,20 +38,6 @@
 #       CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}" )
 
 
-#=============================================================================
-# Copyright 2012 Kitware, Inc.
-# Copyright 2009-2012 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 
 function(CMAKE_EXPAND_IMPORTED_TARGETS _RESULT )
diff --git a/Modules/CMakeExportBuildSettings.cmake b/Modules/CMakeExportBuildSettings.cmake
index a8dd8c2..cafc830 100644
--- a/Modules/CMakeExportBuildSettings.cmake
+++ b/Modules/CMakeExportBuildSettings.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is purposely no longer documented.  It does nothing useful.
 if(NOT "${CMAKE_MINIMUM_REQUIRED_VERSION}" VERSION_LESS 2.7)
diff --git a/Modules/CMakeExtraGeneratorDetermineCompilerMacrosAndIncludeDirs.cmake b/Modules/CMakeExtraGeneratorDetermineCompilerMacrosAndIncludeDirs.cmake
index 3bfb876..3a72622 100644
--- a/Modules/CMakeExtraGeneratorDetermineCompilerMacrosAndIncludeDirs.cmake
+++ b/Modules/CMakeExtraGeneratorDetermineCompilerMacrosAndIncludeDirs.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included by CMakeFindEclipseCDT4.cmake and CMakeFindCodeBlocks.cmake
 
diff --git a/Modules/CMakeFindBinUtils.cmake b/Modules/CMakeFindBinUtils.cmake
index 376a6dc..75a031e 100644
--- a/Modules/CMakeFindBinUtils.cmake
+++ b/Modules/CMakeFindBinUtils.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 
 # search for additional tools required for C/C++ (and other languages ?)
 #
@@ -16,19 +19,6 @@
 
 # on UNIX, cygwin and mingw
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # if it's the MS C/CXX compiler, search for link
 if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC"
    OR "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC"
diff --git a/Modules/CMakeFindCodeBlocks.cmake b/Modules/CMakeFindCodeBlocks.cmake
index bf85ea0..b76e5c5 100644
--- a/Modules/CMakeFindCodeBlocks.cmake
+++ b/Modules/CMakeFindCodeBlocks.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included in CMakeSystemSpecificInformation.cmake if
 # the CodeBlocks extra generator has been selected.
diff --git a/Modules/CMakeFindDependencyMacro.cmake b/Modules/CMakeFindDependencyMacro.cmake
index 73efaae..61f74ef 100644
--- a/Modules/CMakeFindDependencyMacro.cmake
+++ b/Modules/CMakeFindDependencyMacro.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeFindDependencyMacro
 # -------------------------
@@ -14,19 +17,6 @@
 # informative diagnostic message if the dependency could not be found.
 #
 
-#=============================================================================
-# Copyright 2013 Stephen Kelly <steveire at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(find_dependency dep)
   if (NOT ${dep}_FOUND)
     set(cmake_fd_version)
diff --git a/Modules/CMakeFindEclipseCDT4.cmake b/Modules/CMakeFindEclipseCDT4.cmake
index 5bf738a..199005d 100644
--- a/Modules/CMakeFindEclipseCDT4.cmake
+++ b/Modules/CMakeFindEclipseCDT4.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included in CMakeSystemSpecificInformation.cmake if
 # the Eclipse CDT4 extra generator has been selected.
@@ -35,7 +25,7 @@ function(_FIND_ECLIPSE_VERSION)
 
   if(NOT DEFINED CMAKE_ECLIPSE_VERSION)
     if(CMAKE_ECLIPSE_EXECUTABLE)
-      # use REALPATH to resolve symlinks (http://public.kitware.com/Bug/view.php?id=13036)
+      # use REALPATH to resolve symlinks (https://gitlab.kitware.com/cmake/cmake/issues/13036)
       get_filename_component(_REALPATH_CMAKE_ECLIPSE_EXECUTABLE "${CMAKE_ECLIPSE_EXECUTABLE}" REALPATH)
       get_filename_component(_ECLIPSE_DIR "${_REALPATH_CMAKE_ECLIPSE_EXECUTABLE}" PATH)
       file(GLOB _ECLIPSE_FEATURE_DIR "${_ECLIPSE_DIR}/features/org.eclipse.platform*")
diff --git a/Modules/CMakeFindFrameworks.cmake b/Modules/CMakeFindFrameworks.cmake
index 6a8bcd4..6c4c527 100644
--- a/Modules/CMakeFindFrameworks.cmake
+++ b/Modules/CMakeFindFrameworks.cmake
@@ -1,21 +1,15 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeFindFrameworks
 # -------------------
 #
 # helper module to find OSX frameworks
-
-#=============================================================================
-# Copyright 2003-2009 Kitware, Inc.
 #
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
+# This module reads hints about search locations from variables::
 #
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+#   CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS - Extra directories
 
 if(NOT CMAKE_FIND_FRAMEWORKS_INCLUDED)
   set(CMAKE_FIND_FRAMEWORKS_INCLUDED 1)
@@ -24,9 +18,11 @@ if(NOT CMAKE_FIND_FRAMEWORKS_INCLUDED)
     if(APPLE)
       foreach(dir
           ~/Library/Frameworks/${fwk}.framework
+          /usr/local/Frameworks/${fwk}.framework
           /Library/Frameworks/${fwk}.framework
           /System/Library/Frameworks/${fwk}.framework
-          /Network/Library/Frameworks/${fwk}.framework)
+          /Network/Library/Frameworks/${fwk}.framework
+          ${CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS})
         if(EXISTS ${dir})
           set(${fwk}_FRAMEWORKS ${${fwk}_FRAMEWORKS} ${dir})
         endif()
diff --git a/Modules/CMakeFindJavaCommon.cmake b/Modules/CMakeFindJavaCommon.cmake
index fcf0389..46b6280 100644
--- a/Modules/CMakeFindJavaCommon.cmake
+++ b/Modules/CMakeFindJavaCommon.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2013-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Do not include this module directly from code outside CMake!
 set(_JAVA_HOME "")
diff --git a/Modules/CMakeFindKDevelop3.cmake b/Modules/CMakeFindKDevelop3.cmake
index 2abd523..488acf7 100644
--- a/Modules/CMakeFindKDevelop3.cmake
+++ b/Modules/CMakeFindKDevelop3.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included in CMakeSystemSpecificInformation.cmake if
 # the KDevelop3 extra generator has been selected.
diff --git a/Modules/CMakeFindKate.cmake b/Modules/CMakeFindKate.cmake
index 4dcdb28..9aaf6e5 100644
--- a/Modules/CMakeFindKate.cmake
+++ b/Modules/CMakeFindKate.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included in CMakeSystemSpecificInformation.cmake if
 # the Eclipse CDT4 extra generator has been selected.
diff --git a/Modules/CMakeFindPackageMode.cmake b/Modules/CMakeFindPackageMode.cmake
index 26731dc..1261137 100644
--- a/Modules/CMakeFindPackageMode.cmake
+++ b/Modules/CMakeFindPackageMode.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeFindPackageMode
 # --------------------
@@ -26,19 +29,6 @@
 # ``QUIET``
 #   if TRUE, don't print anything
 
-#=============================================================================
-# Copyright 2006-2011 Alexander Neundorf, <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT NAME)
   message(FATAL_ERROR "Name of the package to be searched not specified. Set the CMake variable NAME, e.g. -DNAME=JPEG .")
 endif()
diff --git a/Modules/CMakeFindWMake.cmake b/Modules/CMakeFindWMake.cmake
index 60275ae..a20d069 100644
--- a/Modules/CMakeFindWMake.cmake
+++ b/Modules/CMakeFindWMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 set (CMAKE_MAKE_PROGRAM "wmake" CACHE STRING
      "Program used to build from makefiles.")
diff --git a/Modules/CMakeFindXCode.cmake b/Modules/CMakeFindXCode.cmake
index da0b97b..281af96 100644
--- a/Modules/CMakeFindXCode.cmake
+++ b/Modules/CMakeFindXCode.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Empty placeholder for input dependencies in existing
 # build trees produced by older versions of CMake.
diff --git a/Modules/CMakeForceCompiler.cmake b/Modules/CMakeForceCompiler.cmake
index d16d184..1bc80fd 100644
--- a/Modules/CMakeForceCompiler.cmake
+++ b/Modules/CMakeForceCompiler.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeForceCompiler
 # ------------------
@@ -62,19 +65,6 @@
 #    CMAKE_FORCE_C_COMPILER   (chc12 MetrowerksHicross)
 #    CMAKE_FORCE_CXX_COMPILER (chc12 MetrowerksHicross)
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CMAKE_FORCE_C_COMPILER compiler id)
   message(DEPRECATION "The CMAKE_FORCE_C_COMPILER macro is deprecated.  "
     "Instead just set CMAKE_C_COMPILER and allow CMake to identify the compiler.")
diff --git a/Modules/CMakeFortranCompiler.cmake.in b/Modules/CMakeFortranCompiler.cmake.in
index 2a4bea4..69800d7 100644
--- a/Modules/CMakeFortranCompiler.cmake.in
+++ b/Modules/CMakeFortranCompiler.cmake.in
@@ -54,6 +54,10 @@ if(CMAKE_Fortran_LIBRARY_ARCHITECTURE)
   set(CMAKE_LIBRARY_ARCHITECTURE "@CMAKE_Fortran_LIBRARY_ARCHITECTURE@")
 endif()
 
+ at CMAKE_Fortran_COMPILER_CUSTOM_CODE@
+ at CMAKE_Fortran_SYSROOT_FLAG_CODE@
+ at CMAKE_Fortran_OSX_DEPLOYMENT_TARGET_FLAG_CODE@
+
 set(CMAKE_Fortran_IMPLICIT_LINK_LIBRARIES "@CMAKE_Fortran_IMPLICIT_LINK_LIBRARIES@")
 set(CMAKE_Fortran_IMPLICIT_LINK_DIRECTORIES "@CMAKE_Fortran_IMPLICIT_LINK_DIRECTORIES@")
 set(CMAKE_Fortran_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "@CMAKE_Fortran_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES@")
diff --git a/Modules/CMakeFortranInformation.cmake b/Modules/CMakeFortranInformation.cmake
index 1fd0972..8005da6 100644
--- a/Modules/CMakeFortranInformation.cmake
+++ b/Modules/CMakeFortranInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(CMakeLanguageInformation)
 
@@ -173,10 +163,11 @@ endif()
 set(CMAKE_VERBOSE_MAKEFILE FALSE CACHE BOOL "If this value is on, makefiles will be generated without the .SILENT directive, and all commands will be echoed to the console during the make.  This is useful for debugging only. With Visual Studio IDE projects all commands are done without /nologo.")
 
 set(CMAKE_Fortran_FLAGS_INIT "$ENV{FFLAGS} ${CMAKE_Fortran_FLAGS_INIT}")
-# avoid just having a space as the initial value for the cache
-if(CMAKE_Fortran_FLAGS_INIT STREQUAL " ")
-  set(CMAKE_Fortran_FLAGS_INIT)
-endif()
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_Fortran_FLAGS${c}_INIT}" CMAKE_Fortran_FLAGS${c}_INIT)
+endforeach()
+
 set (CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS_INIT}" CACHE STRING
      "Flags for Fortran compiler.")
 
diff --git a/Modules/CMakeGenericSystem.cmake b/Modules/CMakeGenericSystem.cmake
index 5ae757d..cd05237 100644
--- a/Modules/CMakeGenericSystem.cmake
+++ b/Modules/CMakeGenericSystem.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 set(CMAKE_SHARED_LIBRARY_C_FLAGS "")            # -pic
 set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-shared")       # -shared
diff --git a/Modules/CMakeGraphVizOptions.cmake b/Modules/CMakeGraphVizOptions.cmake
index ff18267..e7c4de6 100644
--- a/Modules/CMakeGraphVizOptions.cmake
+++ b/Modules/CMakeGraphVizOptions.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeGraphVizOptions
 # --------------------
@@ -107,17 +110,3 @@
 #
 #  * Mandatory : NO
 #  * Default   : TRUE
-
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2013 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
diff --git a/Modules/CMakeIOSInstallCombined.cmake b/Modules/CMakeIOSInstallCombined.cmake
index 1256f56..fad2e8f 100644
--- a/Modules/CMakeIOSInstallCombined.cmake
+++ b/Modules/CMakeIOSInstallCombined.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2014-2015 Ruslan Baratov, Gregor Jasny
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Function to print messages of this module
 function(_ios_install_combined_message)
@@ -237,20 +227,30 @@ function(ios_install_combined target destination)
   endif()
 
   set(cmd xcrun -f lipo)
+
+  # Do not merge OUTPUT_VARIABLE and ERROR_VARIABLE since latter may contain
+  # some diagnostic information even for the successful run.
   execute_process(
       COMMAND ${cmd}
       RESULT_VARIABLE result
       OUTPUT_VARIABLE output
-      ERROR_VARIABLE output
+      ERROR_VARIABLE error_output
       OUTPUT_STRIP_TRAILING_WHITESPACE
       ERROR_STRIP_TRAILING_WHITESPACE
   )
   if(NOT result EQUAL 0)
     message(
-        FATAL_ERROR "Command failed (${result}): ${cmd}\n\nOutput:\n${output}"
+        FATAL_ERROR "Command failed (${result}): ${cmd}\n\nOutput:\n${output}\nOutput(error):\n${error_output}"
     )
   endif()
   set(_lipo_path ${output})
+  list(LENGTH _lipo_path len)
+  if(NOT len EQUAL 1)
+    message(FATAL_ERROR "Unexpected xcrun output: ${_lipo_path}")
+  endif()
+  if(NOT EXISTS "${_lipo_path}")
+    message(FATAL_ERROR "File not found: ${_lipo_path}")
+  endif()
 
   set(CURRENT_CONFIG "${CMAKE_INSTALL_CONFIG_NAME}")
   set(CURRENT_TARGET "${target}")
diff --git a/Modules/CMakeImportBuildSettings.cmake b/Modules/CMakeImportBuildSettings.cmake
index edecc1f..ec1effb 100644
--- a/Modules/CMakeImportBuildSettings.cmake
+++ b/Modules/CMakeImportBuildSettings.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is purposely no longer documented.  It does nothing useful.
 
diff --git a/Modules/CMakeJOMFindMake.cmake b/Modules/CMakeJOMFindMake.cmake
index cb3cf12..f56a588 100644
--- a/Modules/CMakeJOMFindMake.cmake
+++ b/Modules/CMakeJOMFindMake.cmake
@@ -1,16 +1,5 @@
-
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 
 set (CMAKE_MAKE_PROGRAM "jom" CACHE STRING
diff --git a/Modules/CMakeJavaInformation.cmake b/Modules/CMakeJavaInformation.cmake
index 928c6ac..844bbbb 100644
--- a/Modules/CMakeJavaInformation.cmake
+++ b/Modules/CMakeJavaInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This should be included before the _INIT variables are
 # used to initialize the cache.  Since the rule variables
diff --git a/Modules/CMakeLanguageInformation.cmake b/Modules/CMakeLanguageInformation.cmake
index e03d149..18c8624 100644
--- a/Modules/CMakeLanguageInformation.cmake
+++ b/Modules/CMakeLanguageInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file contains common code blocks used by all the language information
 # files
diff --git a/Modules/CMakeMSYSFindMake.cmake b/Modules/CMakeMSYSFindMake.cmake
index bc0f89f..33b02c9 100644
--- a/Modules/CMakeMSYSFindMake.cmake
+++ b/Modules/CMakeMSYSFindMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 find_program(CMAKE_MAKE_PROGRAM make
   PATHS
diff --git a/Modules/CMakeMinGWFindMake.cmake b/Modules/CMakeMinGWFindMake.cmake
index d7298dc..523f00c 100644
--- a/Modules/CMakeMinGWFindMake.cmake
+++ b/Modules/CMakeMinGWFindMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 find_program(CMAKE_MAKE_PROGRAM mingw32-make.exe PATHS
   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MinGW;InstallLocation]/bin"
diff --git a/Modules/CMakeNMakeFindMake.cmake b/Modules/CMakeNMakeFindMake.cmake
index d807df8..0335744 100644
--- a/Modules/CMakeNMakeFindMake.cmake
+++ b/Modules/CMakeNMakeFindMake.cmake
@@ -1,16 +1,5 @@
-
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 
 set (CMAKE_MAKE_PROGRAM "nmake" CACHE STRING
diff --git a/Modules/CMakeNinjaFindMake.cmake b/Modules/CMakeNinjaFindMake.cmake
index 2f35cf4..6a0c47e 100644
--- a/Modules/CMakeNinjaFindMake.cmake
+++ b/Modules/CMakeNinjaFindMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 find_program(CMAKE_MAKE_PROGRAM
   NAMES ninja-build ninja
diff --git a/Modules/CMakePackageConfigHelpers.cmake b/Modules/CMakePackageConfigHelpers.cmake
index 5e5302f..8415641 100644
--- a/Modules/CMakePackageConfigHelpers.cmake
+++ b/Modules/CMakePackageConfigHelpers.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakePackageConfigHelpers
 # -------------------------
@@ -199,19 +202,6 @@
 #    check_required_components(Foo)
 
 
-#=============================================================================
-# Copyright 2012 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CMakeParseArguments)
 
 include(WriteBasicConfigVersionFile)
@@ -280,7 +270,7 @@ get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE
 
   if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+")
     # Handle "/usr move" symlinks created by some Linux distros.
-    set(PACKAGE_INIT "${PACKAGE_INIT}
+    string(APPEND PACKAGE_INIT "
 # Use original install prefix when loaded through a \"/usr move\"
 # cross-prefix symbolic link such as /lib -> /usr/lib.
 get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH)
@@ -294,7 +284,7 @@ unset(_realCurr)
   endif()
 
   if(NOT CCF_NO_SET_AND_CHECK_MACRO)
-    set(PACKAGE_INIT "${PACKAGE_INIT}
+    string(APPEND PACKAGE_INIT "
 macro(set_and_check _var _file)
   set(\${_var} \"\${_file}\")
   if(NOT EXISTS \"\${_file}\")
@@ -306,7 +296,7 @@ endmacro()
 
 
   if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO)
-    set(PACKAGE_INIT "${PACKAGE_INIT}
+    string(APPEND PACKAGE_INIT "
 macro(check_required_components _NAME)
   foreach(comp \${\${_NAME}_FIND_COMPONENTS})
     if(NOT \${_NAME}_\${comp}_FOUND)
@@ -319,7 +309,7 @@ endmacro()
 ")
   endif()
 
-  set(PACKAGE_INIT "${PACKAGE_INIT}
+  string(APPEND PACKAGE_INIT "
 ####################################################################################")
 
   configure_file("${_inputFile}" "${_outputFile}" @ONLY)
diff --git a/Modules/CMakeParseArguments.cmake b/Modules/CMakeParseArguments.cmake
index fc64ab9..7ee2bba 100644
--- a/Modules/CMakeParseArguments.cmake
+++ b/Modules/CMakeParseArguments.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeParseArguments
 # -------------------
@@ -6,16 +9,3 @@
 # that is now implemented natively by CMake.  It is now an empty placeholder
 # for compatibility with projects that include it to get the command from
 # CMake 3.4 and lower.
-
-#=============================================================================
-# Copyright 2010 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
diff --git a/Modules/CMakeParseImplicitLinkInfo.cmake b/Modules/CMakeParseImplicitLinkInfo.cmake
index ef9a2eb..2031ba5 100644
--- a/Modules/CMakeParseImplicitLinkInfo.cmake
+++ b/Modules/CMakeParseImplicitLinkInfo.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Function parse implicit linker options.
 # This is used internally by CMake and should not be included by user
@@ -32,7 +22,7 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
   # whole line and just the command (argv[0]).
   set(linker_regex "^( *|.*[/\\])(${linker}|([^/\\]+-)?ld|collect2)[^/\\]*( |$)")
   set(linker_exclude_regex "collect2 version |^[A-Za-z0-9_]+=|/ldfe ")
-  set(log "${log}  link line regex: [${linker_regex}]\n")
+  string(APPEND log "  link line regex: [${linker_regex}]\n")
   string(REGEX REPLACE "\r?\n" ";" output_lines "${text}")
   foreach(line IN LISTS output_lines)
     set(cmd)
@@ -44,7 +34,7 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
         string(REGEX REPLACE "([][+.*()^])" "\\\\\\1" _dir_regex "${CMAKE_BINARY_DIR}")
         string(REGEX REPLACE " -[FL]${_dir_regex}/([^ ]| [^-])+( |$)" " " xline "${line}")
         if(NOT "x${xline}" STREQUAL "x${line}")
-          set(log "${log}  reduced line: [${line}]\n            to: [${xline}]\n")
+          string(APPEND log "  reduced line: [${line}]\n            to: [${xline}]\n")
           set(line "${xline}")
         endif()
       endif()
@@ -56,67 +46,67 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
       list(GET args 0 cmd)
     endif()
     if("${cmd}" MATCHES "${linker_regex}")
-      set(log "${log}  link line: [${line}]\n")
+      string(APPEND log "  link line: [${line}]\n")
       string(REGEX REPLACE ";-([LYz]);" ";-\\1" args "${args}")
       foreach(arg IN LISTS args)
         if("${arg}" MATCHES "^-L(.:)?[/\\]")
           # Unix search path.
           string(REGEX REPLACE "^-L" "" dir "${arg}")
           list(APPEND implicit_dirs_tmp ${dir})
-          set(log "${log}    arg [${arg}] ==> dir [${dir}]\n")
+          string(APPEND log "    arg [${arg}] ==> dir [${dir}]\n")
         elseif("${arg}" MATCHES "^-l([^:].*)$")
           # Unix library.
           set(lib "${CMAKE_MATCH_1}")
           list(APPEND implicit_libs_tmp ${lib})
-          set(log "${log}    arg [${arg}] ==> lib [${lib}]\n")
+          string(APPEND log "    arg [${arg}] ==> lib [${lib}]\n")
         elseif("${arg}" MATCHES "^(.:)?[/\\].*\\.a$")
           # Unix library full path.
           list(APPEND implicit_libs_tmp ${arg})
-          set(log "${log}    arg [${arg}] ==> lib [${arg}]\n")
+          string(APPEND log "    arg [${arg}] ==> lib [${arg}]\n")
         elseif("${arg}" MATCHES "^(.:)?[/\\].*\\.o$"
             AND obj_regex AND "${arg}" MATCHES "${obj_regex}")
           # Object file full path.
           list(APPEND implicit_libs_tmp ${arg})
-          set(log "${log}    arg [${arg}] ==> obj [${arg}]\n")
+          string(APPEND log "    arg [${arg}] ==> obj [${arg}]\n")
         elseif("${arg}" MATCHES "^-Y(P,)?[^0-9]")
           # Sun search path ([^0-9] avoids conflict with Mac -Y<num>).
           string(REGEX REPLACE "^-Y(P,)?" "" dirs "${arg}")
           string(REPLACE ":" ";" dirs "${dirs}")
           list(APPEND implicit_dirs_tmp ${dirs})
-          set(log "${log}    arg [${arg}] ==> dirs [${dirs}]\n")
+          string(APPEND log "    arg [${arg}] ==> dirs [${dirs}]\n")
         elseif("${arg}" MATCHES "^-l:")
           # HP named library.
           list(APPEND implicit_libs_tmp ${arg})
-          set(log "${log}    arg [${arg}] ==> lib [${arg}]\n")
+          string(APPEND log "    arg [${arg}] ==> lib [${arg}]\n")
         elseif("${arg}" MATCHES "^-z(all|default|weak)extract")
           # Link editor option.
           list(APPEND implicit_libs_tmp ${arg})
-          set(log "${log}    arg [${arg}] ==> opt [${arg}]\n")
+          string(APPEND log "    arg [${arg}] ==> opt [${arg}]\n")
         else()
-          set(log "${log}    arg [${arg}] ==> ignore\n")
+          string(APPEND log "    arg [${arg}] ==> ignore\n")
         endif()
       endforeach()
       break()
     elseif("${line}" MATCHES "LPATH(=| is:? *)(.*)$")
-      set(log "${log}  LPATH line: [${line}]\n")
+      string(APPEND log "  LPATH line: [${line}]\n")
       # HP search path.
       string(REPLACE ":" ";" paths "${CMAKE_MATCH_2}")
       list(APPEND implicit_dirs_tmp ${paths})
-      set(log "${log}    dirs [${paths}]\n")
+      string(APPEND log "    dirs [${paths}]\n")
     else()
-      set(log "${log}  ignore line: [${line}]\n")
+      string(APPEND log "  ignore line: [${line}]\n")
     endif()
   endforeach()
 
   # Look for library search paths reported by linker.
   if("${output_lines}" MATCHES ";Library search paths:((;\t[^;]+)+)")
     string(REPLACE ";\t" ";" implicit_dirs_match "${CMAKE_MATCH_1}")
-    set(log "${log}  Library search paths: [${implicit_dirs_match}]\n")
+    string(APPEND log "  Library search paths: [${implicit_dirs_match}]\n")
     list(APPEND implicit_dirs_tmp ${implicit_dirs_match})
   endif()
   if("${output_lines}" MATCHES ";Framework search paths:((;\t[^;]+)+)")
     string(REPLACE ";\t" ";" implicit_fwks_match "${CMAKE_MATCH_1}")
-    set(log "${log}  Framework search paths: [${implicit_fwks_match}]\n")
+    string(APPEND log "  Framework search paths: [${implicit_fwks_match}]\n")
     list(APPEND implicit_fwks_tmp ${implicit_fwks_match})
   endif()
 
@@ -124,12 +114,12 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
   # We remove items that are not language-specific.
   set(implicit_libs "")
   foreach(lib IN LISTS implicit_libs_tmp)
-    if("x${lib}" MATCHES "^x(crt.*\\.o|gcc.*|System.*)$")
-      set(log "${log}  remove lib [${lib}]\n")
+    if("x${lib}" MATCHES "^x(crt.*\\.o|gcc.*|System.*|.*libclang_rt.*)$")
+      string(APPEND log "  remove lib [${lib}]\n")
     elseif(IS_ABSOLUTE "${lib}")
       get_filename_component(abs "${lib}" ABSOLUTE)
       if(NOT "x${lib}" STREQUAL "x${abs}")
-        set(log "${log}  collapse lib [${lib}] ==> [${abs}]\n")
+        string(APPEND log "  collapse lib [${lib}] ==> [${abs}]\n")
       endif()
       list(APPEND implicit_libs "${abs}")
     else()
@@ -151,15 +141,15 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
         set(msg "")
         list(APPEND implicit_${t} "${dir}")
       endif()
-      set(log "${log}  collapse ${desc_${t}} dir [${d}] ==> [${dir}]${msg}\n")
+      string(APPEND log "  collapse ${desc_${t}} dir [${d}] ==> [${dir}]${msg}\n")
     endforeach()
     list(REMOVE_DUPLICATES implicit_${t})
   endforeach()
 
   # Log results.
-  set(log "${log}  implicit libs: [${implicit_libs}]\n")
-  set(log "${log}  implicit dirs: [${implicit_dirs}]\n")
-  set(log "${log}  implicit fwks: [${implicit_fwks}]\n")
+  string(APPEND log "  implicit libs: [${implicit_libs}]\n")
+  string(APPEND log "  implicit dirs: [${implicit_dirs}]\n")
+  string(APPEND log "  implicit fwks: [${implicit_fwks}]\n")
 
   # Return results.
   set(${lib_var} "${implicit_libs}" PARENT_SCOPE)
diff --git a/Modules/CMakePrintHelpers.cmake b/Modules/CMakePrintHelpers.cmake
index 474fa41..bf98a42 100644
--- a/Modules/CMakePrintHelpers.cmake
+++ b/Modules/CMakePrintHelpers.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakePrintHelpers
 # -----------------
@@ -36,28 +39,15 @@
 #
 #   -- CMAKE_C_COMPILER="/usr/bin/gcc" ; CMAKE_MAJOR_VERSION="2" ; DOES_NOT_EXIST=""
 
-#=============================================================================
-# Copyright 2013 Alexander Neundorf, <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CMakeParseArguments)
 
 function(CMAKE_PRINT_VARIABLES)
    set(msg "")
    foreach(var ${ARGN})
       if(msg)
-         set(msg "${msg} ; ")
+         string(APPEND msg " ; ")
       endif()
-      set(msg "${msg}${var}=\"${${var}}\"")
+      string(APPEND msg "${var}=\"${${var}}\"")
    endforeach()
    message(STATUS "${msg}")
 endfunction()
@@ -132,21 +122,21 @@ function(CMAKE_PRINT_PROPERTIES )
     if(keyword STREQUAL "TARGET")
       if(NOT TARGET ${item})
       set(itemExists FALSE)
-      set(msg "${msg}\n No such TARGET \"${item}\" !\n\n")
+      string(APPEND msg "\n No such TARGET \"${item}\" !\n\n")
       endif()
     endif()
 
     if (itemExists)
-      set(msg "${msg} Properties for ${keyword} ${item}:\n")
+      string(APPEND msg " Properties for ${keyword} ${item}:\n")
       foreach(prop ${CPP_PROPERTIES})
 
         get_property(propertySet ${keyword} ${item} PROPERTY "${prop}" SET)
 
         if(propertySet)
           get_property(property ${keyword} ${item} PROPERTY "${prop}")
-          set(msg "${msg}   ${item}.${prop} = \"${property}\"\n")
+          string(APPEND msg "   ${item}.${prop} = \"${property}\"\n")
         else()
-          set(msg "${msg}   ${item}.${prop} = <NOTFOUND>\n")
+          string(APPEND msg "   ${item}.${prop} = <NOTFOUND>\n")
         endif()
       endforeach()
     endif()
diff --git a/Modules/CMakePrintSystemInformation.cmake b/Modules/CMakePrintSystemInformation.cmake
index 355c47d..e74c801 100644
--- a/Modules/CMakePrintSystemInformation.cmake
+++ b/Modules/CMakePrintSystemInformation.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakePrintSystemInformation
 # ---------------------------
@@ -7,19 +10,6 @@
 # This file can be used for diagnostic purposes just include it in a
 # project to see various internal CMake variables.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 message("CMAKE_SYSTEM is ${CMAKE_SYSTEM} ${CMAKE_SYSTEM_NAME} ${CMAKE_SYSTEM_VERSION}")
 message("CMAKE_SYSTEM file is ${CMAKE_SYSTEM_INFO_FILE}")
 message("CMAKE_C_COMPILER is ${CMAKE_C_COMPILER}")
diff --git a/Modules/CMakePushCheckState.cmake b/Modules/CMakePushCheckState.cmake
index 6958da1..2a527d5 100644
--- a/Modules/CMakePushCheckState.cmake
+++ b/Modules/CMakePushCheckState.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakePushCheckState
 # -------------------
@@ -33,20 +36,6 @@
 #    check_function_exists(...)
 #    cmake_pop_check_state()
 
-#=============================================================================
-# Copyright 2006-2011 Alexander Neundorf, <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 macro(CMAKE_RESET_CHECK_STATE)
 
    set(CMAKE_EXTRA_INCLUDE_FILES)
diff --git a/Modules/CMakeRCInformation.cmake b/Modules/CMakeRCInformation.cmake
index 94abd4b..10f2cfb 100644
--- a/Modules/CMakeRCInformation.cmake
+++ b/Modules/CMakeRCInformation.cmake
@@ -1,16 +1,5 @@
-
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 
 # This file sets the basic flags for the Windows Resource Compiler.
@@ -28,9 +17,9 @@ set(CMAKE_SYSTEM_AND_RC_COMPILER_INFO_FILE
   ${CMAKE_ROOT}/Modules/Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}.cmake)
 include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL)
 
+string(STRIP "$ENV{RCFLAGS} ${CMAKE_RC_FLAGS_INIT}" CMAKE_RC_FLAGS_INIT)
 
-
-set (CMAKE_RC_FLAGS "$ENV{RCFLAGS} ${CMAKE_RC_FLAGS_INIT}" CACHE STRING
+set (CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS_INIT}" CACHE STRING
      "Flags for Windows Resource Compiler.")
 
 # These are the only types of flags that should be passed to the rc
diff --git a/Modules/CMakeSwiftInformation.cmake b/Modules/CMakeSwiftInformation.cmake
index 61ad928..d9b408d 100644
--- a/Modules/CMakeSwiftInformation.cmake
+++ b/Modules/CMakeSwiftInformation.cmake
@@ -1,18 +1,9 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 set(CMAKE_Swift_OUTPUT_EXTENSION .o)
+set(CMAKE_INCLUDE_FLAG_Swift "-I")
 
 # Load compiler-specific information.
 if(CMAKE_Swift_COMPILER_ID)
diff --git a/Modules/CMakeSystem.cmake.in b/Modules/CMakeSystem.cmake.in
index 70c98d5..ef8aaa0 100644
--- a/Modules/CMakeSystem.cmake.in
+++ b/Modules/CMakeSystem.cmake.in
@@ -9,7 +9,7 @@ set(CMAKE_SYSTEM "@CMAKE_SYSTEM@")
 set(CMAKE_SYSTEM_NAME "@CMAKE_SYSTEM_NAME@")
 set(CMAKE_SYSTEM_VERSION "@CMAKE_SYSTEM_VERSION@")
 set(CMAKE_SYSTEM_PROCESSOR "@CMAKE_SYSTEM_PROCESSOR@")
-
+ at CMAKE_SYSTEM_CUSTOM_CODE@
 set(CMAKE_CROSSCOMPILING "@CMAKE_CROSSCOMPILING@")
 
 set(CMAKE_SYSTEM_LOADED 1)
diff --git a/Modules/CMakeSystemSpecificInformation.cmake b/Modules/CMakeSystemSpecificInformation.cmake
index b9f8e0a..03f348d 100644
--- a/Modules/CMakeSystemSpecificInformation.cmake
+++ b/Modules/CMakeSystemSpecificInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included by cmGlobalGenerator::EnableLanguage.
 # It is included after the compiler has been determined, so
diff --git a/Modules/CMakeSystemSpecificInitialize.cmake b/Modules/CMakeSystemSpecificInitialize.cmake
index 5327ac1..6200e9c 100644
--- a/Modules/CMakeSystemSpecificInitialize.cmake
+++ b/Modules/CMakeSystemSpecificInitialize.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is included by cmGlobalGenerator::EnableLanguage.
 # It is included before the compiler has been determined.
diff --git a/Modules/CMakeTestASM-ATTCompiler.cmake b/Modules/CMakeTestASM-ATTCompiler.cmake
index 0cc6857..df735c4 100644
--- a/Modules/CMakeTestASM-ATTCompiler.cmake
+++ b/Modules/CMakeTestASM-ATTCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that the selected ASM-ATT "compiler" works.
diff --git a/Modules/CMakeTestASMCompiler.cmake b/Modules/CMakeTestASMCompiler.cmake
index 9381619..7f0b9a7 100644
--- a/Modules/CMakeTestASMCompiler.cmake
+++ b/Modules/CMakeTestASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that the selected ASM compiler works.
diff --git a/Modules/CMakeTestASM_MASMCompiler.cmake b/Modules/CMakeTestASM_MASMCompiler.cmake
index 462b1fc..c1308ff 100644
--- a/Modules/CMakeTestASM_MASMCompiler.cmake
+++ b/Modules/CMakeTestASM_MASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that the selected ASM_MASM "compiler" (should be masm or masm64)
diff --git a/Modules/CMakeTestASM_NASMCompiler.cmake b/Modules/CMakeTestASM_NASMCompiler.cmake
index 414c2f5..a9ee39d 100644
--- a/Modules/CMakeTestASM_NASMCompiler.cmake
+++ b/Modules/CMakeTestASM_NASMCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that the selected ASM_NASM "compiler" works.
diff --git a/Modules/CMakeTestCCompiler.cmake b/Modules/CMakeTestCCompiler.cmake
index 29a58bd..7f19969 100644
--- a/Modules/CMakeTestCCompiler.cmake
+++ b/Modules/CMakeTestCCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2003-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(CMAKE_C_COMPILER_FORCED)
   # The compiler configuration was forced by the user.
diff --git a/Modules/CMakeTestCXXCompiler.cmake b/Modules/CMakeTestCXXCompiler.cmake
index 81561b2..a31067b 100644
--- a/Modules/CMakeTestCXXCompiler.cmake
+++ b/Modules/CMakeTestCXXCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2003-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(CMAKE_CXX_COMPILER_FORCED)
   # The compiler configuration was forced by the user.
diff --git a/Modules/CMakeTestCompilerCommon.cmake b/Modules/CMakeTestCompilerCommon.cmake
index e0d45e7..f76076f 100644
--- a/Modules/CMakeTestCompilerCommon.cmake
+++ b/Modules/CMakeTestCompilerCommon.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 function(PrintTestCompilerStatus LANG MSG)
   message(STATUS "Check for working ${LANG} compiler: ${CMAKE_${LANG}_COMPILER}${MSG}")
diff --git a/Modules/CMakeTestFortranCompiler.cmake b/Modules/CMakeTestFortranCompiler.cmake
index b50e832..c81694e 100644
--- a/Modules/CMakeTestFortranCompiler.cmake
+++ b/Modules/CMakeTestFortranCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(CMAKE_Fortran_COMPILER_FORCED)
   # The compiler configuration was forced by the user.
diff --git a/Modules/CMakeTestJavaCompiler.cmake b/Modules/CMakeTestJavaCompiler.cmake
index d763412..23fdbdc 100644
--- a/Modules/CMakeTestJavaCompiler.cmake
+++ b/Modules/CMakeTestJavaCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that that selected Fortran compiler can actually compile
diff --git a/Modules/CMakeTestRCCompiler.cmake b/Modules/CMakeTestRCCompiler.cmake
index 7969da1..c510d3a 100644
--- a/Modules/CMakeTestRCCompiler.cmake
+++ b/Modules/CMakeTestRCCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This file is used by EnableLanguage in cmGlobalGenerator to
 # determine that that selected RC compiler can actually compile
diff --git a/Modules/CMakeTestSwiftCompiler.cmake b/Modules/CMakeTestSwiftCompiler.cmake
index 89849fb..6393f44 100644
--- a/Modules/CMakeTestSwiftCompiler.cmake
+++ b/Modules/CMakeTestSwiftCompiler.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2003-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(CMAKE_Swift_COMPILER_FORCED)
   # The compiler configuration was forced by the user.
diff --git a/Modules/CMakeUnixFindMake.cmake b/Modules/CMakeUnixFindMake.cmake
index 3714926..1165656 100644
--- a/Modules/CMakeUnixFindMake.cmake
+++ b/Modules/CMakeUnixFindMake.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 find_program(CMAKE_MAKE_PROGRAM NAMES gmake make smake)
 mark_as_advanced(CMAKE_MAKE_PROGRAM)
diff --git a/Modules/CMakeVS7BackwardCompatibility.cmake b/Modules/CMakeVS7BackwardCompatibility.cmake
index e9622ee..cf477c8 100644
--- a/Modules/CMakeVS7BackwardCompatibility.cmake
+++ b/Modules/CMakeVS7BackwardCompatibility.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # hard code these for fast backwards compatibility tests
 set (CMAKE_SIZEOF_INT       4   CACHE INTERNAL "Size of int data type")
diff --git a/Modules/CMakeVerifyManifest.cmake b/Modules/CMakeVerifyManifest.cmake
index a54b9d2..c477ab1 100644
--- a/Modules/CMakeVerifyManifest.cmake
+++ b/Modules/CMakeVerifyManifest.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CMakeVerifyManifest
 # -------------------
@@ -21,20 +24,6 @@
 # of CRT are compared to those found in the .manifest files
 # from the first glob.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 # crt_version:
 # function to extract the CRT version from a file
 # this can be passed a .exe, .dll, or a .manifest file
diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake
index 77f854d..cee1914 100644
--- a/Modules/CPack.cmake
+++ b/Modules/CPack.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPack
 # -----
@@ -116,6 +119,15 @@
 #  A branding image that will be displayed inside the installer (used by GUI
 #  installers).
 #
+# .. variable:: CPACK_PACKAGE_CHECKSUM
+#
+#  An algorithm that will be used to generate additional file with checksum
+#  of the package. Output file name will be::
+#
+#     ${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}
+#
+#  Current supported alogorithms: MD5|SHA1|SHA224|SHA256|SHA384|SHA512.
+#
 # .. variable:: CPACK_PROJECT_CONFIG_FILE
 #
 #  CPack-time project CPack configuration file. This file included at cpack
@@ -275,19 +287,6 @@
 #  Each desktop link requires a corresponding start menu shortcut
 #  as created by :variable:`CPACK_PACKAGE_EXECUTABLES`.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Define this var in order to avoid (or warn) concerning multiple inclusion
 if(CPack_CMake_INCLUDED)
   message(WARNING "CPack.cmake has already been included!!")
@@ -332,7 +331,7 @@ function(cpack_encode_variables)
         set(value "${${var}}")
       endif()
 
-      set(commands "${commands}\nSET(${var} \"${value}\")")
+      string(APPEND commands "\nSET(${var} \"${value}\")")
     endif()
   endforeach()
 
@@ -455,6 +454,7 @@ if(NOT CPACK_GENERATOR)
         option(CPACK_BINARY_DRAGNDROP    "Enable to build OSX Drag And Drop package" OFF)
         option(CPACK_BINARY_OSXX11       "Enable to build OSX X11 packages"      OFF)
         option(CPACK_BINARY_PACKAGEMAKER "Enable to build PackageMaker packages" OFF)
+        option(CPACK_BINARY_PRODUCTBUILD "Enable to build productbuild packages" OFF)
       else()
         option(CPACK_BINARY_TZ  "Enable to build TZ packages"     ON)
       endif()
@@ -483,6 +483,7 @@ if(NOT CPACK_GENERATOR)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_NSIS         NSIS)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_OSXX11       OSXX11)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_PACKAGEMAKER PackageMaker)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_PRODUCTBUILD productbuild)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_RPM          RPM)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_STGZ         STGZ)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TBZ2         TBZ2)
@@ -500,6 +501,7 @@ if(NOT CPACK_SOURCE_GENERATOR)
     if(CYGWIN)
       option(CPACK_SOURCE_CYGWIN "Enable to build Cygwin source packages" ON)
     else()
+      option(CPACK_SOURCE_RPM  "Enable to build RPM source packages"  OFF)
       option(CPACK_SOURCE_TBZ2 "Enable to build TBZ2 source packages" ON)
       option(CPACK_SOURCE_TGZ  "Enable to build TGZ source packages"  ON)
       option(CPACK_SOURCE_TXZ  "Enable to build TXZ source packages"  ON)
@@ -513,6 +515,7 @@ if(NOT CPACK_SOURCE_GENERATOR)
 
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_7Z      7Z)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_CYGWIN  CygwinSource)
+  cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_RPM     RPM)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TBZ2    TBZ2)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TGZ     TGZ)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TXZ     TXZ)
@@ -531,6 +534,7 @@ mark_as_advanced(
   CPACK_BINARY_NSIS
   CPACK_BINARY_OSXX11
   CPACK_BINARY_PACKAGEMAKER
+  CPACK_BINARY_PRODUCTBUILD
   CPACK_BINARY_RPM
   CPACK_BINARY_STGZ
   CPACK_BINARY_TBZ2
@@ -541,6 +545,7 @@ mark_as_advanced(
   CPACK_BINARY_ZIP
   CPACK_SOURCE_7Z
   CPACK_SOURCE_CYGWIN
+  CPACK_SOURCE_RPM
   CPACK_SOURCE_TBZ2
   CPACK_SOURCE_TGZ
   CPACK_SOURCE_TXZ
@@ -589,6 +594,8 @@ if(CMAKE_OSX_SYSROOT)
   _cpack_set_default(CPACK_OSX_SYSROOT "${_CMAKE_OSX_SYSROOT_PATH}")
 endif()
 
+_cpack_set_default(CPACK_BUILD_SOURCE_DIRS "${CMAKE_SOURCE_DIR};${CMAKE_BINARY_DIR}")
+
 if(DEFINED CPACK_COMPONENTS_ALL)
   if(CPACK_MONOLITHIC_INSTALL)
     message("CPack warning: both CPACK_COMPONENTS_ALL and CPACK_MONOLITHIC_INSTALL have been set.\nDefaulting to a monolithic installation.")
@@ -648,6 +655,8 @@ set(CPACK_PACKAGE_FILE_NAME "${CPACK_SOURCE_PACKAGE_FILE_NAME}")
 set(CPACK_IGNORE_FILES "${CPACK_SOURCE_IGNORE_FILES}")
 set(CPACK_STRIP_FILES "${CPACK_SOURCE_STRIP_FILES}")
 
+set(CPACK_RPM_PACKAGE_SOURCES "ON")
+
 cpack_encode_variables()
 configure_file("${cpack_source_input_file}"
   "${CPACK_SOURCE_OUTPUT_CONFIG_FILE}" @ONLY)
diff --git a/Modules/CPackBundle.cmake b/Modules/CPackBundle.cmake
index b412216..8f37ef8 100644
--- a/Modules/CPackBundle.cmake
+++ b/Modules/CPackBundle.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackBundle
 # -----------
@@ -64,17 +67,4 @@
 #  detected command (or specify its location if the auto-detection fails
 #  to find it.)
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #Bundle Generator specific code should be put here
diff --git a/Modules/CPackComponent.cmake b/Modules/CPackComponent.cmake
index 038a717..188dde3 100644
--- a/Modules/CPackComponent.cmake
+++ b/Modules/CPackComponent.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackComponent
 # --------------
@@ -75,9 +78,17 @@
 #
 #  The dependencies (list of components) on which this component depends.
 #
+# .. variable:: CPACK_COMPONENT_<compName>_HIDDEN
+#
+#  True if this component is hidden from the user.
+#
 # .. variable:: CPACK_COMPONENT_<compName>_REQUIRED
 #
-#  True is this component is required.
+#  True if this component is required.
+#
+# .. variable:: CPACK_COMPONENT_<compName>_DISABLED
+#
+#  True if this component is not selected to be installed by default.
 #
 # .. command:: cpack_add_component
 #
@@ -284,19 +295,6 @@
 # NO_ADD_REMOVE turns off this behavior.  This option is ignored on Mac
 # OS X.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Define var in order to avoid multiple inclusion
 if(NOT CPackComponent_CMake_INCLUDED)
 set(CPackComponent_CMake_INCLUDED 1)
@@ -360,6 +358,20 @@ macro(cpack_append_string_variable_set_command var strvar)
   endif ()
 endmacro()
 
+# Macro that appends a SET command for the given list variable name (var)
+# to the macro named strvar, but only if the variable named "var"
+# has been defined. It's like add variable, but wrap each item to quotes.
+# The string will eventually be appended to a CPack configuration file.
+macro(cpack_append_list_variable_set_command var strvar)
+  if (DEFINED ${var})
+    string(APPEND ${strvar} "set(${var}")
+    foreach(_val IN LISTS ${var})
+      string(APPEND ${strvar} "\n  \"${_val}\"")
+    endforeach()
+    string(APPEND ${strvar} ")\n")
+  endif ()
+endmacro()
+
 # Macro that appends a SET command for the given variable name (var)
 # to the macro named strvar, but only if the variable named "var"
 # has been set to true. The string will eventually be
@@ -395,11 +407,11 @@ macro(cpack_add_component compname)
     # moduled was included.
     if(NOT CPACK_COMPONENTS_ALL_SET_BY_USER)
       get_cmake_property(_CPACK_ADDCOMP_COMPONENTS COMPONENTS)
-      set(_CPACK_ADDCOMP_STR "${_CPACK_ADDCOMP_STR}\nSET(CPACK_COMPONENTS_ALL")
+      string(APPEND _CPACK_ADDCOMP_STR "\nSET(CPACK_COMPONENTS_ALL")
       foreach(COMP ${_CPACK_ADDCOMP_COMPONENTS})
-       set(_CPACK_ADDCOMP_STR "${_CPACK_ADDCOMP_STR} ${COMP}")
+       string(APPEND _CPACK_ADDCOMP_STR " ${COMP}")
       endforeach()
-      set(_CPACK_ADDCOMP_STR "${_CPACK_ADDCOMP_STR})\n")
+      string(APPEND _CPACK_ADDCOMP_STR ")\n")
     endif()
   endif()
 
@@ -487,8 +499,8 @@ macro(cpack_add_install_type insttype)
 
   set(_CPACK_INSTTYPE_STR
     "\n# Configuration for installation type \"${insttype}\"\n")
-  set(_CPACK_INSTTYPE_STR
-    "${_CPACK_INSTTYPE_STR}list(APPEND CPACK_ALL_INSTALL_TYPES ${insttype})\n")
+  string(APPEND _CPACK_INSTTYPE_STR
+    "list(APPEND CPACK_ALL_INSTALL_TYPES ${insttype})\n")
   cpack_append_string_variable_set_command(
     CPACK_INSTALL_TYPE_${_CPACK_INSTTYPE_UNAME}_DISPLAY_NAME
     _CPACK_INSTTYPE_STR)
diff --git a/Modules/CPackCygwin.cmake b/Modules/CPackCygwin.cmake
index abfc1f6..6d203c3 100644
--- a/Modules/CPackCygwin.cmake
+++ b/Modules/CPackCygwin.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackCygwin
 # -----------
@@ -22,16 +25,3 @@
 # .. variable:: CPACK_CYGWIN_BUILD_SCRIPT
 #
 #  The Cygwin build script.  FIXME: This documentation is incomplete.
-
-#=============================================================================
-# Copyright 2006-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
diff --git a/Modules/CPackDMG.cmake b/Modules/CPackDMG.cmake
index 929b2f6..bda600f 100644
--- a/Modules/CPackDMG.cmake
+++ b/Modules/CPackDMG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackDMG
 # --------
@@ -100,16 +103,3 @@
 #  Path to the Rez(1) command used to compile resources on Mac OS X. This
 #  variable can be used to override the automatically detected command (or
 #  specify its location if the auto-detection fails to find it.)
-
-#=============================================================================
-# Copyright 2006-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake
index c9678d6..653283c 100644
--- a/Modules/CPackDeb.cmake
+++ b/Modules/CPackDeb.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackDeb
 # --------
@@ -177,6 +180,24 @@
 #
 #  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   : "paxr"
+#
+#  Possible values are:
+#
+#  - paxr
+#  - gnutar
+#
+#  .. note::
+#
+#    Default pax archive format is the most portable format and generates
+#    packages that do not treat sparse files specially.
+#    GNU tar format on the other hand supports longer filenames.
+#
 # .. variable:: CPACK_DEBIAN_COMPRESSION_TYPE
 #
 #  The compression used for creating the Debian package.
@@ -477,24 +498,6 @@
 #    This value is not interpreted. It is possible to pass an optional
 #    revision number of the referenced source package as well.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2007-2009 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-# Copyright 2014-2016 Alexander Smorkalov <alexander.smorkalov at itseez.com>
-# Copyright 2014-2016 Roman Donchenko <roman.donchenko at itseez.com>
-# Copyright 2014-2016 Roman Kharitonov <roman.kharitonov at itseez.com>
-# Copyright 2014-2016 Ilya Lavrenov <ilya.lavrenov at itseez.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # CPack script for creating Debian package
 # Author: Mathieu Malaterre
 #
@@ -842,12 +845,24 @@ function(cpack_deb_prepare_package_vars)
     set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
   endif()
 
+  if(CPACK_DEBIAN_ARCHIVE_TYPE)
+    set(archive_types_ "paxr;gnutar")
+    cmake_policy(PUSH)
+      cmake_policy(SET CMP0057 NEW)
+      if(NOT CPACK_DEBIAN_ARCHIVE_TYPE IN_LIST archive_types_)
+        message(FATAL_ERROR "CPACK_DEBIAN_ARCHIVE_TYPE set to unsupported"
+          "type ${CPACK_DEBIAN_ARCHIVE_TYPE}")
+      endif()
+    cmake_policy(POP)
+  else()
+    set(CPACK_DEBIAN_ARCHIVE_TYPE "paxr")
+  endif()
+
   # Compression: (recommended)
   if(NOT CPACK_DEBIAN_COMPRESSION_TYPE)
     set(CPACK_DEBIAN_COMPRESSION_TYPE "gzip")
   endif()
 
-
   # Recommends:
   # You should set: CPACK_DEBIAN_PACKAGE_RECOMMENDS
 
@@ -1000,6 +1015,7 @@ function(cpack_deb_prepare_package_vars)
   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)
diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake
index 083fc28..6c93ddb 100644
--- a/Modules/CPackIFW.cmake
+++ b/Modules/CPackIFW.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackIFW
 # --------
@@ -131,6 +134,14 @@
 #
 #  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_REPOSITORIES_ALL
 #
 #  The list of remote repositories.
@@ -181,136 +192,174 @@
 #
 # The module defines the following commands:
 #
-# --------------------------------------------------------------------------
-#
 # .. command:: cpack_ifw_configure_component
 #
-# Sets the arguments specific to the CPack IFW generator.
+#   Sets the arguments specific to the CPack IFW generator.
+#
+#   ::
 #
-# ::
+#     cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL]
+#                         [NAME <name>]
+#                         [VERSION <version>]
+#                         [SCRIPT <script>]
+#                         [PRIORITY <priority>]
+#                         [DEPENDS <com_id> ...]
+#                         [LICENSES <display_name> <file_path> ...]
+#                         [USER_INTERFACES <file_path> <file_path> ...])
 #
-#   cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL]
-#                       [NAME <name>]
-#                       [VERSION <version>]
-#                       [SCRIPT <script>]
-#                       [PRIORITY <priority>]
-#                       [DEPENDS <com_id> ...]
-#                       [LICENSES <display_name> <file_path> ...])
+#   This command should be called after :command:`cpack_add_component` command.
 #
-# This command should be called after :command:`cpack_add_component` command.
+#   ``COMMON``
+#     if set, then the component will be packaged and installed as part
+#     of a group to which it belongs.
 #
-# ``COMMON`` if set, then the component will be packaged and installed as part
-# of a group to which it belongs.
+#   ``ESSENTIAL``
+#     if set, then the package manager stays disabled until that
+#     component is updated.
 #
-# ``ESSENTIAL`` if set, then the package manager stays disabled until that
-# component is updated.
+#   ``NAME``
+#     is used to create domain-like identification for this component.
+#     By default used origin component name.
 #
-# ``NAME`` is used to create domain-like identification for this component.
-# By default used origin component name.
+#   ``VERSION``
+#     is version of component.
+#     By default used :variable:`CPACK_PACKAGE_VERSION`.
 #
-# ``VERSION`` is version of component.
-# By default used :variable:`CPACK_PACKAGE_VERSION`.
+#   ``SCRIPT``
+#     is a relative or absolute path to operations script
+#     for this component.
 #
-# ``SCRIPT`` is a relative or absolute path to operations script
-# for this component.
+#   ``PRIORITY``
+#     is priority of the component in the tree.
 #
-# ``PRIORITY`` is priority of the component in the tree.
+#   ``DEPENDS``
+#     list of dependency component identifiers in QtIFW_ style.
 #
-# ``DEPENDS`` list of dependency component identifiers in QtIFW_ style.
+#   ``LICENSES``
+#     pair of <display_name> and <file_path> of license text for this
+#     component. You can specify more then one license.
 #
-# ``LICENSES`` pair of <display_name> and <file_path> of license text for this
-# component. You can specify more then one license.
+#   ``USER_INTERFACES``
+#     a list of <file_path> representing pages to load
 #
-# --------------------------------------------------------------------------
 #
 # .. command:: cpack_ifw_configure_component_group
 #
-# Sets the arguments specific to the CPack IFW generator.
+#   Sets the arguments specific to the CPack IFW generator.
 #
-# ::
+#   ::
 #
-#   cpack_ifw_configure_component_group(<groupname>
-#                       [NAME <name>]
-#                       [VERSION <version>]
-#                       [SCRIPT <script>]
-#                       [PRIORITY <priority>]
-#                       [LICENSES <display_name> <file_path> ...])
+#     cpack_ifw_configure_component_group(<groupname>
+#                         [NAME <name>]
+#                         [VERSION <version>]
+#                         [SCRIPT <script>]
+#                         [PRIORITY <priority>]
+#                         [LICENSES <display_name> <file_path> ...]
+#                         [USER_INTERFACES <file_path> <file_path> ...])
 #
-# This command should be called after :command:`cpack_add_component_group`
-# command.
+#   This command should be called after :command:`cpack_add_component_group`
+#   command.
 #
-# ``NAME`` is used to create domain-like identification for this component
-# group.
-# By default used origin component group name.
+#   ``NAME``
+#     is used to create domain-like identification for this component group.
+#     By default used origin component group name.
 #
-# ``VERSION`` is version of component group.
-# By default used :variable:`CPACK_PACKAGE_VERSION`.
+#   ``VERSION``
+#     is version of component group.
+#     By default used :variable:`CPACK_PACKAGE_VERSION`.
 #
-# ``SCRIPT`` is a relative or absolute path to operations script
-# for this component group.
+#   ``SCRIPT``
+#     is a relative or absolute path to operations script
+#     for this component group.
 #
-# ``PRIORITY`` is priority of the component group in the tree.
+#   ``PRIORITY``
+#     is priority of the component group in the tree.
 #
-# ``LICENSES`` pair of <display_name> and <file_path> of license text for this
-# component group. You can specify more then one license.
+#   ``LICENSES``
+#     pair of <display_name> and <file_path> of license text for this
+#     component group. You can specify more then one license.
 #
-# --------------------------------------------------------------------------
+#   ``USER_INTERFACES``
+#     a list of <file_path> representing pages to load
 #
-# .. command:: cpack_ifw_add_repository
 #
-# Add QtIFW_ specific remote repository to binary installer.
+# .. command:: cpack_ifw_add_repository
 #
-# ::
+#   Add QtIFW_ specific remote repository to binary installer.
 #
-#   cpack_ifw_add_repository(<reponame> [DISABLED]
-#                       URL <url>
-#                       [USERNAME <username>]
-#                       [PASSWORD <password>]
-#                       [DISPLAY_NAME <display_name>])
+#   ::
 #
-# This command will also add the <reponame> repository
-# to a variable :variable:`CPACK_IFW_REPOSITORIES_ALL`.
+#     cpack_ifw_add_repository(<reponame> [DISABLED]
+#                         URL <url>
+#                         [USERNAME <username>]
+#                         [PASSWORD <password>]
+#                         [DISPLAY_NAME <display_name>])
 #
-# ``DISABLED`` if set, then the repository will be disabled by default.
+#   This command will also add the <reponame> repository
+#   to a variable :variable:`CPACK_IFW_REPOSITORIES_ALL`.
 #
-# ``URL`` is points to a list of available components.
+#   ``DISABLED``
+#     if set, then the repository will be disabled by default.
 #
-# ``USERNAME`` is used as user on a protected repository.
+#   ``URL``
+#     is points to a list of available components.
 #
-# ``PASSWORD`` is password to use on a protected repository.
+#   ``USERNAME``
+#     is used as user on a protected repository.
 #
-# ``DISPLAY_NAME`` is string to display instead of the URL.
+#   ``PASSWORD``
+#     is password to use on a protected repository.
 #
+#   ``DISPLAY_NAME``
+#     is string to display instead of the URL.
 #
-# --------------------------------------------------------------------------
 #
 # .. command:: cpack_ifw_update_repository
 #
-# Update QtIFW_ specific repository from remote repository.
+#   Update QtIFW_ specific repository from remote repository.
 #
-# ::
+#   ::
 #
-#   cpack_ifw_update_repository(<reponame>
-#                       [[ADD|REMOVE] URL <url>]|
-#                        [REPLACE OLD_URL <old_url> NEW_URL <new_url>]]
-#                       [USERNAME <username>]
-#                       [PASSWORD <password>]
-#                       [DISPLAY_NAME <display_name>])
+#     cpack_ifw_update_repository(<reponame>
+#                         [[ADD|REMOVE] URL <url>]|
+#                          [REPLACE OLD_URL <old_url> NEW_URL <new_url>]]
+#                         [USERNAME <username>]
+#                         [PASSWORD <password>]
+#                         [DISPLAY_NAME <display_name>])
 #
-# This command will also add the <reponame> repository
-# to a variable :variable:`CPACK_IFW_REPOSITORIES_ALL`.
+#   This command will also add the <reponame> repository
+#   to a variable :variable:`CPACK_IFW_REPOSITORIES_ALL`.
 #
-# ``URL`` is points to a list of available components.
+#   ``URL``
+#     is points to a list of available components.
 #
-# ``OLD_URL`` is points to a list that will replaced.
+#   ``OLD_URL``
+#     is points to a list that will replaced.
 #
-# ``NEW_URL`` is points to a list that will replace to.
+#   ``NEW_URL``
+#     is points to a list that will replace to.
 #
-# ``USERNAME`` is used as user on a protected repository.
+#   ``USERNAME``
+#     is used as user on a protected repository.
 #
-# ``PASSWORD`` is password to use on a protected repository.
+#   ``PASSWORD``
+#     is password to use on a protected repository.
+#
+#   ``DISPLAY_NAME``
+#     is string to display instead of the URL.
+#
+#
+# .. command:: cpack_ifw_add_package_resources
+#
+#   Add additional resources in the installer binary.
+#
+#   ::
+#
+#     cpack_ifw_add_package_resources(<file_path> <file_path> ...)
+#
+#   This command will also add the specified files
+#   to a variable :variable:`CPACK_IFW_PACKAGE_RESOURCES`.
 #
-# ``DISPLAY_NAME`` is string to display instead of the URL.
 #
 # Example usage
 # ^^^^^^^^^^^^^
@@ -362,16 +411,16 @@
 #
 # Qt Installer Framework Manual:
 #
-#  Index page
+# * Index page:
 #   http://doc.qt.io/qtinstallerframework/index.html
 #
-#  Component Scripting
+# * Component Scripting:
 #   http://doc.qt.io/qtinstallerframework/scripting.html
 #
-#  Predefined Variables
+# * Predefined Variables:
 #   http://doc.qt.io/qtinstallerframework/scripting.html#predefined-variables
 #
-#  Promoting Updates
+# * Promoting Updates:
 #   http://doc.qt.io/qtinstallerframework/ifw-updates.html
 #
 # Download Qt Installer Framework for you platform from Qt site:
@@ -379,20 +428,6 @@
 #
 
 #=============================================================================
-# Copyright 2014 Kitware, Inc.
-# Copyright 2014 Konstantin Podsvirov <konstantin at podsvirov.pro>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-#=============================================================================
 # Search Qt Installer Framework tools
 #=============================================================================
 
@@ -543,6 +578,22 @@ macro(_cpack_ifw_resolve_lisenses _variable)
   endif()
 endmacro()
 
+# Resolve full path to a list of provided files
+macro(_cpack_ifw_resolve_file_list _variable)
+  if(${_variable})
+    set(_ifw_list_fix)
+    foreach(_ifw_file_arg ${${_variable}})
+      get_filename_component(_ifw_file_arg "${_ifw_file_arg}" ABSOLUTE)
+      if(EXISTS ${_ifw_file_arg})
+        list(APPEND _ifw_list_fix "${_ifw_file_arg}")
+      else()
+        message(WARNING "CPack IFW: page file \"${_ifw_file_arg}\" does not exist. Skipping")
+      endif()
+    endforeach(_ifw_file_arg)
+    set(${_variable} "${_ifw_list_fix}")
+  endif()
+endmacro()
+
 # Macro for configure component
 macro(cpack_ifw_configure_component compname)
 
@@ -550,11 +601,12 @@ macro(cpack_ifw_configure_component compname)
 
   set(_IFW_OPT COMMON ESSENTIAL)
   set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
-  set(_IFW_MULTI_ARGS DEPENDS LICENSES)
+  set(_IFW_MULTI_ARGS DEPENDS LICENSES USER_INTERFACES)
   cmake_parse_arguments(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
 
   _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_SCRIPT)
   _cpack_ifw_resolve_lisenses(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_LICENSES)
+  _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_USER_INTERFACES)
 
   set(_CPACK_IFWCOMP_STR "\n# Configuration for IFW component \"${compname}\"\n")
 
@@ -571,7 +623,7 @@ macro(cpack_ifw_configure_component compname)
   endforeach()
 
   foreach(_IFW_ARG_NAME ${_IFW_MULTI_ARGS})
-  cpack_append_variable_set_command(
+  cpack_append_list_variable_set_command(
     CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_${_IFW_ARG_NAME}
     _CPACK_IFWCOMP_STR)
   endforeach()
@@ -589,11 +641,12 @@ macro(cpack_ifw_configure_component_group grpname)
 
   set(_IFW_OPT)
   set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
-  set(_IFW_MULTI_ARGS LICENSES)
+  set(_IFW_MULTI_ARGS LICENSES USER_INTERFACES)
   cmake_parse_arguments(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
 
   _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_SCRIPT)
   _cpack_ifw_resolve_lisenses(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_LICENSES)
+  _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_USER_INTERFACES)
 
   set(_CPACK_IFWGRP_STR "\n# Configuration for IFW component group \"${grpname}\"\n")
 
@@ -604,7 +657,7 @@ macro(cpack_ifw_configure_component_group grpname)
   endforeach()
 
   foreach(_IFW_ARG_NAME ${_IFW_MULTI_ARGS})
-  cpack_append_variable_set_command(
+  cpack_append_list_variable_set_command(
     CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_${_IFW_ARG_NAME}
     _CPACK_IFWGRP_STR)
   endforeach()
@@ -645,7 +698,7 @@ macro(cpack_ifw_add_repository reponame)
   endforeach()
 
   list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})
-  set(_CPACK_IFWREPO_STR "${_CPACK_IFWREPO_STR}list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})\n")
+  string(APPEND _CPACK_IFWREPO_STR "list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})\n")
 
   if(CPack_CMake_INCLUDED)
     file(APPEND "${CPACK_OUTPUT_CONFIG_FILE}" "${_CPACK_IFWREPO_STR}")
@@ -687,7 +740,7 @@ macro(cpack_ifw_update_repository reponame)
     OR CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME}_REMOVE
     OR CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME}_REPLACE)
     list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})
-    set(_CPACK_IFWREPO_STR "${_CPACK_IFWREPO_STR}list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})\n")
+    string(APPEND _CPACK_IFWREPO_STR "list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})\n")
   else()
     set(_CPACK_IFWREPO_STR)
   endif()
@@ -698,6 +751,17 @@ macro(cpack_ifw_update_repository reponame)
 
 endmacro()
 
+# Macro for adding resources
+macro(cpack_ifw_add_package_resources)
+  set(_CPACK_IFW_PACKAGE_RESOURCES ${ARGV})
+  _cpack_ifw_resolve_file_list(_CPACK_IFW_PACKAGE_RESOURCES)
+  list(APPEND CPACK_IFW_PACKAGE_RESOURCES ${_CPACK_IFW_PACKAGE_RESOURCES})
+  set(_CPACK_IFWQRC_STR "list(APPEND CPACK_IFW_PACKAGE_RESOURCES \"${_CPACK_IFW_PACKAGE_RESOURCES}\")\n")
+  if(CPack_CMake_INCLUDED)
+    file(APPEND "${CPACK_OUTPUT_CONFIG_FILE}" "${_CPACK_IFWQRC_STR}")
+  endif()
+endmacro()
+
 # Resolve package control script
 _cpack_ifw_resolve_script(CPACK_IFW_PACKAGE_CONTROL_SCRIPT)
 
diff --git a/Modules/CPackNSIS.cmake b/Modules/CPackNSIS.cmake
index db5984a..18d1871 100644
--- a/Modules/CPackNSIS.cmake
+++ b/Modules/CPackNSIS.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackNSIS
 # ---------
@@ -96,6 +99,11 @@
 #  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.
@@ -126,18 +134,5 @@
 #       "CMake Help" "https://cmake.org" "CMake Web Site")
 #
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #FIXME we should put NSIS specific code here
 #FIXME but I'm not doing it because I'm not able to test it...
diff --git a/Modules/CPackPackageMaker.cmake b/Modules/CPackPackageMaker.cmake
index 4160425..c2ca4c6 100644
--- a/Modules/CPackPackageMaker.cmake
+++ b/Modules/CPackPackageMaker.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackPackageMaker
 # -----------------
@@ -22,16 +25,3 @@
 #  guarantee that your installer will work on that version of Mac OS X, and
 #  don't mind missing extra features available in the installer shipping with
 #  later versions of Mac OS X.
-
-#=============================================================================
-# Copyright 2006-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
diff --git a/Modules/CPackProductBuild.cmake b/Modules/CPackProductBuild.cmake
new file mode 100644
index 0000000..ea2fa7c
--- /dev/null
+++ b/Modules/CPackProductBuild.cmake
@@ -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.
+
+#.rst:
+# CPackProductBuild
+# -----------------
+#
+# productbuild CPack generator (Mac OS X).
+#
+# Variables specific to CPack productbuild generator
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# The following variable is specific to installers built on Mac
+# OS X using productbuild:
+#
+# .. variable:: CPACK_COMMAND_PRODUCTBUILD
+#
+#  Path to the productbuild(1) command used to generate a product archive for
+#  the OS X 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_COMMAND_PKGBUILD
+#
+#  Path to the pkgbuild(1) command used to generate an OS X component package
+#  on OS X.  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/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake
index 9cc496f..15b62c7 100644
--- a/Modules/CPackRPM.cmake
+++ b/Modules/CPackRPM.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackRPM
 # --------
@@ -698,19 +701,167 @@
 #   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.
-
-#=============================================================================
-# Copyright 2007-2016 Kitware, Inc.
 #
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
+# Packaging of debug information
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# Debuginfo packages contain debug symbols and sources for debugging packaged
+# binaries.
+#
+# .. note::
+#
+#  Currently multiple debuginfo packages are generated if component based
+#  packaging is used - one debuginfo package per component. This duplicates
+#  sources if multiple binaries are using them. This is a side effect of
+#  how CPackRPM currently generates component packages and will be addressed
+#  in later versions of the generator.
+#
+# Debuginfo RPM packaging has it's 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 be empty.
+#
+# .. 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 additionaly 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   : -
+#
+# 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 product by executing:
+#
+# ``cpack -G RPM --config ./CPackSourceConfig.cmake``
 #
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# .. 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 it's 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   : "/"
 
 # Author: Eric Noulard with the help of Alexander Neundorf.
 
@@ -761,7 +912,7 @@ function(cpack_rpm_prepare_relocation_paths)
     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)
-      set(TMP_RPM_PREFIXES "${TMP_RPM_PREFIXES}Prefix: ${PATH_PREFIX}\n")
+      string(APPEND TMP_RPM_PREFIXES "Prefix: ${PATH_PREFIX}\n")
       list(APPEND RPM_USED_PACKAGE_PREFIXES "${PATH_PREFIX}")
 
       if(CPACK_RPM_PACKAGE_DEBUG)
@@ -779,7 +930,7 @@ function(cpack_rpm_prepare_relocation_paths)
     endif()
 
     if(EXISTS "${WDIR}/${PREPARED_RELOCATION_PATH}")
-      set(TMP_RPM_PREFIXES "${TMP_RPM_PREFIXES}Prefix: ${PREPARED_RELOCATION_PATH}\n")
+      string(APPEND TMP_RPM_PREFIXES "Prefix: ${PREPARED_RELOCATION_PATH}\n")
       list(APPEND RPM_USED_PACKAGE_PREFIXES "${PREPARED_RELOCATION_PATH}")
     endif()
   endforeach()
@@ -839,7 +990,10 @@ function(cpack_rpm_prepare_content_list)
         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)
+        cmake_policy(PUSH)
+          cmake_policy(SET CMP0007 NEW)
+          list(REMOVE_AT _CPACK_RPM_PACKAGE_PREFIX_ELEMS -1)
+        cmake_policy(POP)
         unset(_TMP_LIST)
         # Now generate all of the parent dirs of the relocation path
         foreach(_PREFIX_PATH_ELEM ${_CPACK_RPM_PACKAGE_PREFIX_ELEMS})
@@ -859,7 +1013,9 @@ function(cpack_rpm_prepare_content_list)
   if(NOT DEFINED CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST)
     set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/include)
     if(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION)
-      message("CPackRPM:Debug: Adding ${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION} to builtin omit list.")
+      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()
@@ -952,7 +1108,7 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
         if("${SYMLINK_INDEX}" EQUAL "${POINT_INDEX}")
           set(INDENT "")
         else()
-          set(SCRIPT_PART "${SCRIPT_PART}  if [ \"$RPM_INSTALL_PREFIX${POINT_INDEX}\" != \"${POINT_PATH}\" ]; then\n")
+          string(APPEND SCRIPT_PART "  if [ \"$RPM_INSTALL_PREFIX${POINT_INDEX}\" != \"${POINT_PATH}\" ]; then\n")
           set(INDENT "  ")
         endif()
 
@@ -969,14 +1125,14 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
           math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1+${POINT_PATH_LEN})
           string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
 
-          set(SCRIPT_PART "${SCRIPT_PART}  ${INDENT}if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
-          set(SCRIPT_PART "${SCRIPT_PART}    ${INDENT}ln -s \"$RPM_INSTALL_PREFIX${POINT_INDEX}${POINT_}\" \"$RPM_INSTALL_PREFIX${SYMLINK_INDEX}${SYMLINK_}\"\n")
-          set(SCRIPT_PART "${SCRIPT_PART}    ${INDENT}CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
-          set(SCRIPT_PART "${SCRIPT_PART}  ${INDENT}fi\n")
+          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}")
-          set(SCRIPT_PART "${SCRIPT_PART}  fi\n")
+          string(APPEND SCRIPT_PART "  fi\n")
         endif()
       endif()
     endforeach()
@@ -996,16 +1152,16 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
         math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1)
         string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
 
-        set(SCRIPT_PART "${SCRIPT_PART}  if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
-        set(SCRIPT_PART "${SCRIPT_PART}    ln -s \"${POINT_}\" \"$RPM_INSTALL_PREFIX${SYMLINK_INDEX}${SYMLINK_}\"\n")
-        set(SCRIPT_PART "${SCRIPT_PART}    CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
-        set(SCRIPT_PART "${SCRIPT_PART}  fi\n")
+        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}")
-      set(SCRIPT "${SCRIPT}fi\n")
+      string(APPEND SCRIPT "fi\n")
     endif()
   endforeach()
 
@@ -1016,7 +1172,7 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
     string(LENGTH "${POINT_PATH}" POINT_PATH_LEN)
 
     if(_RPM_RELOCATION_SCRIPT_X_${POINT_INDEX})
-      set(SCRIPT "${SCRIPT}if [ \"$RPM_INSTALL_PREFIX${POINT_INDEX}\" != \"${POINT_PATH}\" ]; then\n")
+      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)
@@ -1028,13 +1184,13 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
         math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1+${POINT_PATH_LEN})
         string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
 
-        set(SCRIPT "${SCRIPT}  if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
-        set(SCRIPT "${SCRIPT}    ln -s \"$RPM_INSTALL_PREFIX${POINT_INDEX}${POINT_}\" \"${SYMLINK_}\"\n")
-        set(SCRIPT "${SCRIPT}    CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
-        set(SCRIPT "${SCRIPT}  fi\n")
+        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()
 
-      set(SCRIPT "${SCRIPT}fi\n")
+      string(APPEND SCRIPT "fi\n")
     endif()
   endforeach()
 
@@ -1050,9 +1206,9 @@ function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
       math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1)
       string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
 
-      set(SCRIPT "${SCRIPT}if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
-      set(SCRIPT "${SCRIPT}  ln -s \"${POINT_}\" \"${SYMLINK_}\"\n")
-      set(SCRIPT "${SCRIPT}fi\n")
+      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()
 
@@ -1215,7 +1371,7 @@ function(cpack_rpm_prepare_install_files INSTALL_FILES_LIST WDIR PACKAGE_PREFIXE
       set(DIRECTIVE "%dir ")
     endif()
 
-    set(INSTALL_FILES "${INSTALL_FILES}${DIRECTIVE}\"${F}\"\n")
+    string(APPEND INSTALL_FILES "${DIRECTIVE}\"${F}\"\n")
   endforeach()
 
   if(REQUIRES_SYMLINK_RELOCATION_SCRIPT)
@@ -1234,6 +1390,153 @@ 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 that if the given file was 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"
+              " longer than debuginfo sources dir path '${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}'!"
+              " Source dir path must be shorter 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()
+    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})
 
@@ -1346,7 +1649,7 @@ function(cpack_rpm_generate_package)
   endif()
 
   if(CPACK_RPM_PACKAGE_COMPONENT)
-    set(CPACK_RPM_PACKAGE_NAME "${CPACK_RPM_PACKAGE_NAME}-${CPACK_RPM_PACKAGE_COMPONENT}")
+    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")
@@ -1405,7 +1708,7 @@ function(cpack_rpm_generate_package)
   endif()
 
   if(CPACK_RPM_PACKAGE_RELEASE_DIST)
-    set(CPACK_RPM_PACKAGE_RELEASE "${CPACK_RPM_PACKAGE_RELEASE}%{?dist}")
+    string(APPEND CPACK_RPM_PACKAGE_RELEASE "%{?dist}")
   endif()
 
   # CPACK_RPM_PACKAGE_LICENSE
@@ -1481,18 +1784,27 @@ function(cpack_rpm_generate_package)
      set(CPACK_RPM_COMPRESSION_TYPE_TMP "")
   endif()
 
-  if(CPACK_PACKAGE_RELOCATABLE OR CPACK_RPM_PACKAGE_RELOCATABLE)
-    if(CPACK_RPM_PACKAGE_DEBUG)
-      message("CPackRPM:Debug: Trying to build a relocatable package")
+  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()
-    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)
+  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()
 
   # Check if additional fields for RPM spec header are given
@@ -1524,13 +1836,13 @@ function(cpack_rpm_generate_package)
       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)
-      set(_PACKAGE_HEADER_NAME "${_PACKAGE_HEADER_NAME}${_PACKAGE_HEADER_TAIL}")
+      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}")
-        set(_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}")
@@ -1683,17 +1995,17 @@ function(cpack_rpm_generate_package)
 
     set(CPACK_RPM_USER_INSTALL_FILES "")
     foreach(F IN LISTS CPACK_RPM_USER_FILELIST_INTERNAL)
-      string(REGEX REPLACE "%[A-Za-z0-9\(\),-]* " "" F_PATH ${F})
-      string(REGEX MATCH "%[A-Za-z0-9\(\),-]*" F_PREFIX ${F})
+      string(REGEX REPLACE "%[A-Za-z]+(\\([^()]*\\))? " "" F_PATH ${F})
+      string(REGEX MATCH "%[A-Za-z]+(\\([^()]*\\))?" F_PREFIX ${F})
 
       if(CPACK_RPM_PACKAGE_DEBUG)
         message("CPackRPM:Debug: F_PREFIX=<${F_PREFIX}>, F_PATH=<${F_PATH}>")
       endif()
       if(F_PREFIX)
-        set(F_PREFIX "${F_PREFIX} ")
+        string(APPEND F_PREFIX " ")
       endif()
       # Rebuild the user list file
-      set(CPACK_RPM_USER_INSTALL_FILES "${CPACK_RPM_USER_INSTALL_FILES}${F_PREFIX}\"${F_PATH}\"\n")
+      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})
@@ -1706,7 +2018,7 @@ function(cpack_rpm_generate_package)
     # Rebuild CPACK_RPM_INSTALL_FILES
     set(CPACK_RPM_INSTALL_FILES "")
     foreach(F IN LISTS CPACK_RPM_INSTALL_FILES_LIST)
-      set(CPACK_RPM_INSTALL_FILES "${CPACK_RPM_INSTALL_FILES}\"${F}\"\n")
+      string(APPEND CPACK_RPM_INSTALL_FILES "\"${F}\"\n")
     endforeach()
   else()
     set(CPACK_RPM_USER_INSTALL_FILES "")
@@ -1727,12 +2039,12 @@ function(cpack_rpm_generate_package)
     # Rebuild INSTALL_FILES
     set(CPACK_RPM_INSTALL_FILES "")
     foreach(F IN LISTS CPACK_RPM_INSTALL_FILES_LIST)
-      set(CPACK_RPM_INSTALL_FILES "${CPACK_RPM_INSTALL_FILES}\"${F}\"\n")
+      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)
-      set(CPACK_RPM_ABSOLUTE_INSTALL_FILES "${CPACK_RPM_ABSOLUTE_INSTALL_FILES}%config \"${F}\"\n")
+      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}")
@@ -1743,6 +2055,41 @@ function(cpack_rpm_generate_package)
     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)
+    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()
+    cpack_rpm_debugsymbol_check("${CPACK_RPM_INSTALL_FILES}" "${WDIR}")
+
+    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
+")
+  endif()
+
   # Prepare install files
   cpack_rpm_prepare_install_files(
       "${CPACK_RPM_INSTALL_FILES}"
@@ -1822,16 +2169,112 @@ function(cpack_rpm_generate_package)
     # else example:
     #set(CPACK_RPM_FILE_NAME "${CPACK_RPM_PACKAGE_NAME}-${CPACK_RPM_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}-${CPACK_RPM_PACKAGE_ARCHITECTURE}.rpm")
 
-    set(FILE_NAME_DEFINE "%define _rpmfilename ${CPACK_RPM_FILE_NAME}")
+    if(NOT CPACK_RPM_DEBUGINFO_PACKAGE)
+      set(FILE_NAME_DEFINE "%define _rpmfilename ${CPACK_RPM_FILE_NAME}")
+    endif()
   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
-  if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE OR NOT CPACK_RPM_USER_BINARY_SPECFILE)
+  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 controll 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 ${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
       "# -*- rpm-spec -*-
-BuildRoot:      \@CPACK_RPM_DIRECTORY\@/\@CPACK_PACKAGE_FILE_NAME\@\@CPACK_RPM_PACKAGE_COMPONENT_PART_PATH\@
+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\@
+"
+    )
+  else()  # binary rpm
+
+    # 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
+    if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE OR NOT CPACK_RPM_USER_BINARY_SPECFILE)
+      set(RPMBUILD_FLAGS "-bb")
+
+      file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
+        "# -*- 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\@
@@ -1839,6 +2282,7 @@ 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\@
@@ -1854,10 +2298,12 @@ Vendor:         \@CPACK_RPM_PACKAGE_VENDOR\@
 \@TMP_RPM_BUILDARCH\@
 \@TMP_RPM_PREFIXES\@
 
-%define _rpmdir \@CPACK_RPM_DIRECTORY\@
+\@TMP_RPM_DEBUGINFO\@
+
+%define _rpmdir %_topdir/RPMS
+%define _srcrpmdir %_topdir/SRPMS
 \@FILE_NAME_DEFINE\@
 %define _unpackaged_files_terminate_build 0
-%define _topdir \@CPACK_RPM_DIRECTORY\@
 \@TMP_RPM_SPEC_INSTALL_POST\@
 \@CPACK_RPM_SPEC_MORE_DEFINE\@
 \@CPACK_RPM_COMPRESSION_TYPE_TMP\@
@@ -1870,16 +2316,16 @@ Vendor:         \@CPACK_RPM_PACKAGE_VENDOR\@
 # We do only save CPack installed tree in _prepr
 # and then restore it in build.
 %prep
-mv $RPM_BUILD_ROOT \"\@CPACK_TOPLEVEL_DIRECTORY\@/tmpBBroot\"
-
-#p build
+mv $RPM_BUILD_ROOT %_topdir/tmpBBroot
 
 %install
 if [ -e $RPM_BUILD_ROOT ];
 then
   rm -rf $RPM_BUILD_ROOT
 fi
-mv \"\@CPACK_TOPLEVEL_DIRECTORY\@/tmpBBroot\" $RPM_BUILD_ROOT
+mv %_topdir/tmpBBroot $RPM_BUILD_ROOT
+
+\@TMP_RPM_DEBUGINFO_INSTALL\@
 
 %clean
 
@@ -1904,12 +2350,15 @@ mv \"\@CPACK_TOPLEVEL_DIRECTORY\@/tmpBBroot\" $RPM_BUILD_ROOT
 
 %changelog
 \@CPACK_RPM_SPEC_CHANGELOG\@
-")
+"
+      )
+    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 templare is: ${CPACK_RPM_BINARY_SPECFILE}.in")
+      message(FATAL_ERROR "CPackRPM: STOP here Generated USER binary spec file template is: ${CPACK_RPM_BINARY_SPECFILE}.in")
     endif()
   endif()
 
@@ -1930,9 +2379,9 @@ mv \"\@CPACK_TOPLEVEL_DIRECTORY\@/tmpBBroot\" $RPM_BUILD_ROOT
   if(RPMBUILD_EXECUTABLE)
     # Now call rpmbuild using the SPECFILE
     execute_process(
-      COMMAND "${RPMBUILD_EXECUTABLE}" -bb
+      COMMAND "${RPMBUILD_EXECUTABLE}" ${RPMBUILD_FLAGS}
               --define "_topdir ${CPACK_RPM_DIRECTORY}"
-              --buildroot "${CPACK_RPM_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
+              --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}"
@@ -1959,13 +2408,30 @@ mv \"\@CPACK_TOPLEVEL_DIRECTORY\@/tmpBBroot\" $RPM_BUILD_ROOT
     # Tell file(GLOB_RECURSE) not to follow directory symlinks
     # even if the project does not set this policy to NEW.
     cmake_policy(SET CMP0009 NEW)
-    file(GLOB_RECURSE GENERATED_FILES "${CPACK_RPM_DIRECTORY}/*.rpm")
+    file(GLOB_RECURSE GENERATED_FILES "${CPACK_RPM_DIRECTORY}/RPMS/*.rpm"
+      "${CPACK_RPM_DIRECTORY}/SRPMS/*.rpm")
   cmake_policy(POP)
 
   if(NOT GENERATED_FILES)
     message(FATAL_ERROR "RPM package was not generated! ${CPACK_RPM_DIRECTORY}")
   endif()
 
+  if(CPACK_RPM_DEBUGINFO_PACKAGE AND NOT CPACK_RPM_FILE_NAME STREQUAL "RPM-DEFAULT")
+    string(TOLOWER "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm" EXPECTED_FILENAME)
+
+    foreach(F IN LISTS GENERATED_FILES)
+      if(F MATCHES ".*/${EXPECTED_FILENAME}")
+        get_filename_component(FILE_PATH "${F}" DIRECTORY)
+        file(RENAME "${F}" "${FILE_PATH}/${CPACK_RPM_FILE_NAME}")
+        list(APPEND new_files_list_ "${FILE_PATH}/${CPACK_RPM_FILE_NAME}")
+      else()
+        list(APPEND new_files_list_ "${F}")
+      endif()
+    endforeach()
+
+    set(GENERATED_FILES "${new_files_list_}")
+  endif()
+
   set(GEN_CPACK_OUTPUT_FILES "${GENERATED_FILES}" PARENT_SCOPE)
 
   if(CPACK_RPM_PACKAGE_DEBUG)
diff --git a/Modules/CPackWIX.cmake b/Modules/CPackWIX.cmake
index 3c90561..0f2278f 100644
--- a/Modules/CPackWIX.cmake
+++ b/Modules/CPackWIX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CPackWIX
 # --------
@@ -147,7 +150,7 @@
 #     }
 #
 #  Currently fragments can be injected into most
-#  Component, File and Directory elements.
+#  Component, File, Directory and Feature elements.
 #
 #  The following additional special Ids can be used:
 #
@@ -237,19 +240,34 @@
 #  * ARPURLUPDATEINFO - Update information URL
 #  * ARPHELPTELEPHONE - Help and support telephone number
 #  * ARPSIZE - Size (in kilobytes) of the application
-
-#=============================================================================
-# Copyright 2014-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+#
+# .. 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 therefor 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.
+#
 
 if(NOT CPACK_WIX_ROOT)
   file(TO_CMAKE_PATH "$ENV{WIX}" CPACK_WIX_ROOT)
diff --git a/Modules/CPackZIP.cmake b/Modules/CPackZIP.cmake
index a36589b..376520c 100644
--- a/Modules/CPackZIP.cmake
+++ b/Modules/CPackZIP.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(CMAKE_BINARY_DIR)
   message(FATAL_ERROR "CPackZIP.cmake may only be used by CPack internally.")
diff --git a/Modules/CTest.cmake b/Modules/CTest.cmake
index a27eb4b..7aeb5be 100644
--- a/Modules/CTest.cmake
+++ b/Modules/CTest.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 CTest
 -----
@@ -48,19 +51,6 @@ the :variable:`CTEST_USE_LAUNCHERS` variable::
 in the ``CTestConfig.cmake`` file.
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 option(BUILD_TESTING "Build the testing tree." ON)
 
 # function to turn generator name into a version string
@@ -224,16 +214,16 @@ if(BUILD_TESTING)
       set(BUILD_NAME_SYSTEM_NAME "Win32")
     endif()
     if(UNIX OR BORLAND)
-      get_filename_component(DART_CXX_NAME
-        "${CMAKE_CXX_COMPILER}" ${DART_NAME_COMPONENT})
+      get_filename_component(DART_COMPILER_NAME
+        "${DART_COMPILER}" ${DART_NAME_COMPONENT})
     else()
-      get_filename_component(DART_CXX_NAME
+      get_filename_component(DART_COMPILER_NAME
         "${CMAKE_MAKE_PROGRAM}" ${DART_NAME_COMPONENT})
     endif()
-    if(DART_CXX_NAME MATCHES "devenv")
-      GET_VS_VERSION_STRING("${CMAKE_GENERATOR}" DART_CXX_NAME)
+    if(DART_COMPILER_NAME MATCHES "devenv")
+      GET_VS_VERSION_STRING("${CMAKE_GENERATOR}" DART_COMPILER_NAME)
     endif()
-    set(BUILDNAME "${BUILD_NAME_SYSTEM_NAME}-${DART_CXX_NAME}")
+    set(BUILDNAME "${BUILD_NAME_SYSTEM_NAME}-${DART_COMPILER_NAME}")
   endif()
 
   # the build command
diff --git a/Modules/CTestCoverageCollectGCOV.cmake b/Modules/CTestCoverageCollectGCOV.cmake
index a04d340..8451a6a 100644
--- a/Modules/CTestCoverageCollectGCOV.cmake
+++ b/Modules/CTestCoverageCollectGCOV.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CTestCoverageCollectGCOV
 # ------------------------
@@ -62,18 +65,6 @@
 #     Suppress non-error messages that otherwise would have been
 #     printed out by this function.
 
-#=============================================================================
-# Copyright 2014-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 include(CMakeParseArguments)
 function(ctest_coverage_collect_gcov)
   set(options QUIET GLOB DELETE)
diff --git a/Modules/CTestScriptMode.cmake b/Modules/CTestScriptMode.cmake
index b434724..5be78d5 100644
--- a/Modules/CTestScriptMode.cmake
+++ b/Modules/CTestScriptMode.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CTestScriptMode
 # ---------------
@@ -6,20 +9,6 @@
 #
 # This file is read by ctest in script mode (-S)
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Determine the current system, so this information can be used
 # in ctest scripts
 include(CMakeDetermineSystem)
diff --git a/Modules/CTestTargets.cmake b/Modules/CTestTargets.cmake
index 1157850..ff9aada 100644
--- a/Modules/CTestTargets.cmake
+++ b/Modules/CTestTargets.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(NOT RUN_FROM_CTEST_OR_DART)
   message(FATAL_ERROR "Do not incldue CTestTargets.cmake directly")
diff --git a/Modules/CTestUseLaunchers.cmake b/Modules/CTestUseLaunchers.cmake
index c79119f..1cf20eb 100644
--- a/Modules/CTestUseLaunchers.cmake
+++ b/Modules/CTestUseLaunchers.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CTestUseLaunchers
 # -----------------
@@ -23,19 +26,6 @@
 # variable initialization only occurs if CTEST_USE_LAUNCHERS is not
 # already defined.
 
-#=============================================================================
-# Copyright 2008-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT DEFINED CTEST_USE_LAUNCHERS AND DEFINED ENV{CTEST_USE_LAUNCHERS_DEFAULT})
   set(CTEST_USE_LAUNCHERS "$ENV{CTEST_USE_LAUNCHERS_DEFAULT}"
     CACHE INTERNAL "CTEST_USE_LAUNCHERS initial value from ENV")
@@ -59,7 +49,7 @@ if(CTEST_USE_LAUNCHERS)
     "${__launch_common_options} --output <OUTPUT>")
 
   if("${CMAKE_GENERATOR}" MATCHES "Ninja")
-    set(__launch_compile_options "${__launch_compile_options} --filter-prefix <CMAKE_CL_SHOWINCLUDES_PREFIX>")
+    string(APPEND __launch_compile_options " --filter-prefix <CMAKE_CL_SHOWINCLUDES_PREFIX>")
   endif()
 
   set(CTEST_LAUNCH_COMPILE
diff --git a/Modules/CheckCCompilerFlag.cmake b/Modules/CheckCCompilerFlag.cmake
index 53f3454..1ba67fc 100644
--- a/Modules/CheckCCompilerFlag.cmake
+++ b/Modules/CheckCCompilerFlag.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCCompilerFlag
 # ------------------
@@ -19,21 +22,6 @@
 # give an error message when it encounters the flag.  If the flag has
 # any effect or even a specific one is beyond the scope of this module.
 
-#=============================================================================
-# Copyright 2006-2011 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2011 Matthias Kretz <kretz at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckCSourceCompiles)
 include(CMakeCheckCompilerFlagCommonPatterns)
 
diff --git a/Modules/CheckCSourceCompiles.cmake b/Modules/CheckCSourceCompiles.cmake
index c2b1723..ac2c6c5 100644
--- a/Modules/CheckCSourceCompiles.cmake
+++ b/Modules/CheckCSourceCompiles.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCSourceCompiles
 # --------------------
@@ -24,21 +27,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_C_SOURCE_COMPILES SOURCE VAR)
   if(NOT DEFINED "${VAR}")
     set(_FAIL_REGEX)
diff --git a/Modules/CheckCSourceRuns.cmake b/Modules/CheckCSourceRuns.cmake
index 5afeab6..70aa9fd 100644
--- a/Modules/CheckCSourceRuns.cmake
+++ b/Modules/CheckCSourceRuns.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCSourceRuns
 # ----------------
@@ -24,21 +27,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_C_SOURCE_RUNS SOURCE VAR)
   if(NOT DEFINED "${VAR}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
diff --git a/Modules/CheckCXXCompilerFlag.cmake b/Modules/CheckCXXCompilerFlag.cmake
index fab3a05..afbb231 100644
--- a/Modules/CheckCXXCompilerFlag.cmake
+++ b/Modules/CheckCXXCompilerFlag.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCXXCompilerFlag
 # --------------------
@@ -18,21 +21,6 @@
 # give an error message when it encounters the flag.  If the flag has
 # any effect or even a specific one is beyond the scope of this module.
 
-#=============================================================================
-# Copyright 2006-2010 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2011 Matthias Kretz <kretz at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckCXXSourceCompiles)
 include(CMakeCheckCompilerFlagCommonPatterns)
 
diff --git a/Modules/CheckCXXSourceCompiles.cmake b/Modules/CheckCXXSourceCompiles.cmake
index f8736e2..e54d09e 100644
--- a/Modules/CheckCXXSourceCompiles.cmake
+++ b/Modules/CheckCXXSourceCompiles.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCXXSourceCompiles
 # ----------------------
@@ -24,21 +27,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_CXX_SOURCE_COMPILES SOURCE VAR)
   if(NOT DEFINED "${VAR}")
     set(_FAIL_REGEX)
diff --git a/Modules/CheckCXXSourceRuns.cmake b/Modules/CheckCXXSourceRuns.cmake
index 84b661d..e083659 100644
--- a/Modules/CheckCXXSourceRuns.cmake
+++ b/Modules/CheckCXXSourceRuns.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCXXSourceRuns
 # ------------------
@@ -24,21 +27,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_CXX_SOURCE_RUNS SOURCE VAR)
   if(NOT DEFINED "${VAR}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
diff --git a/Modules/CheckCXXSymbolExists.cmake b/Modules/CheckCXXSymbolExists.cmake
index 084fbb4..354eea3 100644
--- a/Modules/CheckCXXSymbolExists.cmake
+++ b/Modules/CheckCXXSymbolExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckCXXSymbolExists
 # --------------------
@@ -29,19 +32,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2003-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckSymbolExists)
 
 macro(CHECK_CXX_SYMBOL_EXISTS SYMBOL FILES VARIABLE)
diff --git a/Modules/CheckFortranCompilerFlag.cmake b/Modules/CheckFortranCompilerFlag.cmake
index 53fd8d6..8519fcc 100644
--- a/Modules/CheckFortranCompilerFlag.cmake
+++ b/Modules/CheckFortranCompilerFlag.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckFortranCompilerFlag
 # ------------------------
@@ -20,22 +23,6 @@
 # flag has any effect or even a specific one is beyond the scope of
 # this module.
 
-#=============================================================================
-# Copyright 2015 Nicolas Bock <nicolasbock at gmail.com>
-# Copyright 2006-2011 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2011 Matthias Kretz <kretz at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckFortranSourceCompiles)
 include(CMakeCheckCompilerFlagCommonPatterns)
 
diff --git a/Modules/CheckFortranFunctionExists.cmake b/Modules/CheckFortranFunctionExists.cmake
index bd52f61..5fc740a 100644
--- a/Modules/CheckFortranFunctionExists.cmake
+++ b/Modules/CheckFortranFunctionExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckFortranFunctionExists
 # --------------------------
@@ -21,21 +24,6 @@
 #
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_FORTRAN_FUNCTION_EXISTS FUNCTION VARIABLE)
   if(NOT DEFINED ${VARIABLE})
     message(STATUS "Looking for Fortran ${FUNCTION}")
diff --git a/Modules/CheckFortranSourceCompiles.cmake b/Modules/CheckFortranSourceCompiles.cmake
index 0bdcffa..c42254c 100644
--- a/Modules/CheckFortranSourceCompiles.cmake
+++ b/Modules/CheckFortranSourceCompiles.cmake
@@ -1,10 +1,14 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckFortranSourceCompiles
 # --------------------------
 #
 # Check if given Fortran source compiles and links into an executable::
 #
-#   CHECK_Fortran_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])
+#   CHECK_Fortran_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>]
+#                                 [SRC_EXT <ext>])
 #
 # The arguments are:
 #
@@ -13,8 +17,10 @@
 # ``<var>``
 #   Variable to store whether the source code compiled.
 #   Will be created as an internal cache variable.
-# ``<fail-regex>``
+# ``FAIL_REGEX <fail-regex>``
 #   Fail if test output matches this regex.
+# ``SRC_EXT <ext>``
+#   Use source extension ``.<ext>`` instead of the default ``.F``.
 #
 # The following variables may be set before calling this macro to modify
 # the way the check is run::
@@ -25,27 +31,13 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
   if(NOT DEFINED "${VAR}")
     set(_FAIL_REGEX)
+    set(_SRC_EXT)
     set(_key)
     foreach(arg ${ARGN})
-      if("${arg}" MATCHES "^(FAIL_REGEX)$")
+      if("${arg}" MATCHES "^(FAIL_REGEX|SRC_EXT)$")
         set(_key "${arg}")
       elseif(_key)
         list(APPEND _${_key} "${arg}")
@@ -53,6 +45,9 @@ macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
         message(FATAL_ERROR "Unknown argument:\n  ${arg}\n")
       endif()
     endforeach()
+    if(NOT _SRC_EXT)
+      set(_SRC_EXT F)
+    endif()
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
       "-D${VAR} ${CMAKE_REQUIRED_FLAGS}")
     if(CMAKE_REQUIRED_LIBRARIES)
@@ -67,7 +62,7 @@ macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
     else()
       set(CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES)
     endif()
-    file(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.F"
+    file(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.${_SRC_EXT}"
       "${SOURCE}\n")
 
     if(NOT CMAKE_REQUIRED_QUIET)
@@ -75,7 +70,7 @@ macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
     endif()
     try_compile(${VAR}
       ${CMAKE_BINARY_DIR}
-      ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.F
+      ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.${_SRC_EXT}
       COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
       ${CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES}
       CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
diff --git a/Modules/CheckFunctionExists.cmake b/Modules/CheckFunctionExists.cmake
index 5dd3751..5f049e7 100644
--- a/Modules/CheckFunctionExists.cmake
+++ b/Modules/CheckFunctionExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckFunctionExists
 # -------------------
@@ -23,21 +26,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2002-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_FUNCTION_EXISTS FUNCTION VARIABLE)
   if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
diff --git a/Modules/CheckIncludeFile.cmake b/Modules/CheckIncludeFile.cmake
index ef1e39d..c566e14 100644
--- a/Modules/CheckIncludeFile.cmake
+++ b/Modules/CheckIncludeFile.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckIncludeFile
 # ----------------
@@ -31,19 +34,6 @@
 # at once.  See the :module:`CheckIncludeFileCXX` module to check for headers
 # using the ``CXX`` language.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CHECK_INCLUDE_FILE INCLUDE VARIABLE)
   if(NOT DEFINED "${VARIABLE}")
     if(CMAKE_REQUIRED_INCLUDES)
@@ -60,7 +50,7 @@ macro(CHECK_INCLUDE_FILE INCLUDE VARIABLE)
     endif()
     if(${ARGC} EQUAL 3)
       set(CMAKE_C_FLAGS_SAVE ${CMAKE_C_FLAGS})
-      set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${ARGV2}")
+      string(APPEND CMAKE_C_FLAGS " ${ARGV2}")
     endif()
 
     try_compile(${VARIABLE}
diff --git a/Modules/CheckIncludeFileCXX.cmake b/Modules/CheckIncludeFileCXX.cmake
index 9a6df3b..19b1ef6 100644
--- a/Modules/CheckIncludeFileCXX.cmake
+++ b/Modules/CheckIncludeFileCXX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckIncludeFileCXX
 # -------------------
@@ -30,19 +33,6 @@
 # See modules :module:`CheckIncludeFile` and :module:`CheckIncludeFiles`
 # to check for one or more ``C`` headers.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CHECK_INCLUDE_FILE_CXX INCLUDE VARIABLE)
   if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
     if(CMAKE_REQUIRED_INCLUDES)
@@ -59,7 +49,7 @@ macro(CHECK_INCLUDE_FILE_CXX INCLUDE VARIABLE)
     endif()
     if(${ARGC} EQUAL 3)
       set(CMAKE_CXX_FLAGS_SAVE ${CMAKE_CXX_FLAGS})
-      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ARGV2}")
+      string(APPEND CMAKE_CXX_FLAGS " ${ARGV2}")
     endif()
 
     try_compile(${VARIABLE}
diff --git a/Modules/CheckIncludeFiles.cmake b/Modules/CheckIncludeFiles.cmake
index 843cd35..bef11a5 100644
--- a/Modules/CheckIncludeFiles.cmake
+++ b/Modules/CheckIncludeFiles.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckIncludeFiles
 # -----------------
@@ -31,19 +34,6 @@
 # See modules :module:`CheckIncludeFile` and :module:`CheckIncludeFileCXX`
 # to check for a single header file in ``C`` or ``CXX`` languages.
 
-#=============================================================================
-# Copyright 2003-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CHECK_INCLUDE_FILES INCLUDE VARIABLE)
   if(NOT DEFINED "${VARIABLE}")
     set(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
@@ -55,11 +45,11 @@ macro(CHECK_INCLUDE_FILES INCLUDE VARIABLE)
     set(CHECK_INCLUDE_FILES_CONTENT "/* */\n")
     set(MACRO_CHECK_INCLUDE_FILES_FLAGS ${CMAKE_REQUIRED_FLAGS})
     foreach(FILE ${INCLUDE})
-      set(CMAKE_CONFIGURABLE_FILE_CONTENT
-        "${CMAKE_CONFIGURABLE_FILE_CONTENT}#include <${FILE}>\n")
+      string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT
+        "#include <${FILE}>\n")
     endforeach()
-    set(CMAKE_CONFIGURABLE_FILE_CONTENT
-      "${CMAKE_CONFIGURABLE_FILE_CONTENT}\n\nint main(void){return 0;}\n")
+    string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT
+      "\n\nint main(void){return 0;}\n")
     configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
       "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFiles.c" @ONLY)
 
diff --git a/Modules/CheckLanguage.cmake b/Modules/CheckLanguage.cmake
index 99c809b..6b4a9e4 100644
--- a/Modules/CheckLanguage.cmake
+++ b/Modules/CheckLanguage.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckLanguage
 # -------------
@@ -28,19 +31,6 @@
 #     message(STATUS "No Fortran support")
 #   endif()
 
-#=============================================================================
-# Copyright 2009-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(check_language lang)
   if(NOT DEFINED CMAKE_${lang}_COMPILER)
     set(_desc "Looking for a ${lang} compiler")
diff --git a/Modules/CheckLibraryExists.cmake b/Modules/CheckLibraryExists.cmake
index 6b53823..528a450 100644
--- a/Modules/CheckLibraryExists.cmake
+++ b/Modules/CheckLibraryExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckLibraryExists
 # ------------------
@@ -26,21 +29,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_LIBRARY_EXISTS LIBRARY FUNCTION LOCATION VARIABLE)
   if(NOT DEFINED "${VARIABLE}")
     set(MACRO_CHECK_LIBRARY_EXISTS_DEFINITION
diff --git a/Modules/CheckPrototypeDefinition.cmake b/Modules/CheckPrototypeDefinition.cmake
index e203d4c..7859594 100644
--- a/Modules/CheckPrototypeDefinition.cmake
+++ b/Modules/CheckPrototypeDefinition.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckPrototypeDefinition
 # ------------------------
@@ -36,19 +39,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2010-2011 Andreas Schneider <asn at cryptomilk.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 #
 
 
@@ -75,8 +65,8 @@ function(CHECK_PROTOTYPE_DEFINITION _FUNCTION _PROTOTYPE _RETURN _HEADER _VARIAB
     endif()
 
     foreach(_FILE ${_HEADER})
-      set(CHECK_PROTOTYPE_DEFINITION_HEADER
-        "${CHECK_PROTOTYPE_DEFINITION_HEADER}#include <${_FILE}>\n")
+      string(APPEND CHECK_PROTOTYPE_DEFINITION_HEADER
+        "#include <${_FILE}>\n")
     endforeach()
 
     set(CHECK_PROTOTYPE_DEFINITION_SYMBOL ${_FUNCTION})
diff --git a/Modules/CheckSizeOf.cmake b/Modules/CheckSizeOf.cmake
index f0707df..bd439e1 100644
--- a/Modules/CheckSizeOf.cmake
+++ b/Modules/CheckSizeOf.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 message(SEND_ERROR
         "Modules/CheckSizeOf.cmake has been removed.  "
diff --git a/Modules/CheckStructHasMember.cmake b/Modules/CheckStructHasMember.cmake
index 6c15205..085b464 100644
--- a/Modules/CheckStructHasMember.cmake
+++ b/Modules/CheckStructHasMember.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckStructHasMember
 # --------------------
@@ -35,26 +38,13 @@
 # Example: CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h
 # HAVE_TIMEVAL_TV_SEC LANGUAGE C)
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckCSourceCompiles)
 include(CheckCXXSourceCompiles)
 
 macro (CHECK_STRUCT_HAS_MEMBER _STRUCT _MEMBER _HEADER _RESULT)
    set(_INCLUDE_FILES)
    foreach (it ${_HEADER})
-      set(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
+      string(APPEND _INCLUDE_FILES "#include <${it}>\n")
    endforeach ()
 
    if("x${ARGN}" STREQUAL "x")
diff --git a/Modules/CheckSymbolExists.cmake b/Modules/CheckSymbolExists.cmake
index c4dff3f..8fecc57 100644
--- a/Modules/CheckSymbolExists.cmake
+++ b/Modules/CheckSymbolExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckSymbolExists
 # -----------------
@@ -31,19 +34,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2003-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CHECK_SYMBOL_EXISTS SYMBOL FILES VARIABLE)
   if(CMAKE_C_COMPILER_LOADED)
     _CHECK_SYMBOL_EXISTS("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.c" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
@@ -71,11 +61,11 @@ macro(_CHECK_SYMBOL_EXISTS SOURCEFILE SYMBOL FILES VARIABLE)
       set(CMAKE_SYMBOL_EXISTS_INCLUDES)
     endif()
     foreach(FILE ${FILES})
-      set(CMAKE_CONFIGURABLE_FILE_CONTENT
-        "${CMAKE_CONFIGURABLE_FILE_CONTENT}#include <${FILE}>\n")
+      string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT
+        "#include <${FILE}>\n")
     endforeach()
-    set(CMAKE_CONFIGURABLE_FILE_CONTENT
-      "${CMAKE_CONFIGURABLE_FILE_CONTENT}\nint main(int argc, char** argv)\n{\n  (void)argv;\n#ifndef ${SYMBOL}\n  return ((int*)(&${SYMBOL}))[argc];\n#else\n  (void)argc;\n  return 0;\n#endif\n}\n")
+    string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT
+      "\nint main(int argc, char** argv)\n{\n  (void)argv;\n#ifndef ${SYMBOL}\n  return ((int*)(&${SYMBOL}))[argc];\n#else\n  (void)argc;\n  return 0;\n#endif\n}\n")
 
     configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
       "${SOURCEFILE}" @ONLY)
diff --git a/Modules/CheckTypeSize.cmake b/Modules/CheckTypeSize.cmake
index 5938d6c..4b3e223 100644
--- a/Modules/CheckTypeSize.cmake
+++ b/Modules/CheckTypeSize.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckTypeSize
 # -------------
@@ -65,19 +68,6 @@
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 #   CMAKE_EXTRA_INCLUDE_FILES = list of extra headers to include
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CheckIncludeFile)
 include(CheckIncludeFileCXX)
 
@@ -97,17 +87,17 @@ function(__check_type_size_impl type var map builtin language)
   set(headers)
   if(builtin)
     if(HAVE_SYS_TYPES_H)
-      set(headers "${headers}#include <sys/types.h>\n")
+      string(APPEND headers "#include <sys/types.h>\n")
     endif()
     if(HAVE_STDINT_H)
-      set(headers "${headers}#include <stdint.h>\n")
+      string(APPEND headers "#include <stdint.h>\n")
     endif()
     if(HAVE_STDDEF_H)
-      set(headers "${headers}#include <stddef.h>\n")
+      string(APPEND headers "#include <stddef.h>\n")
     endif()
   endif()
   foreach(h ${CMAKE_EXTRA_INCLUDE_FILES})
-    set(headers "${headers}#include \"${h}\"\n")
+    string(APPEND headers "#include \"${h}\"\n")
   endforeach()
 
   # Perform the check.
@@ -157,7 +147,7 @@ function(__check_type_size_impl type var map builtin language)
         string(REGEX MATCH   "${regex_key}"       key "${info}")
         string(REGEX REPLACE "${regex_key}" "\\1" key "${key}")
         if(key)
-          set(code "${code}\nset(${var}-${key} \"${size}\")")
+          string(APPEND code "\nset(${var}-${key} \"${size}\")")
           list(APPEND keys ${key})
         endif()
       endif()
diff --git a/Modules/CheckVariableExists.cmake b/Modules/CheckVariableExists.cmake
index f3e05e4..fd5c36c 100644
--- a/Modules/CheckVariableExists.cmake
+++ b/Modules/CheckVariableExists.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # CheckVariableExists
 # -------------------
@@ -29,21 +32,6 @@
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
-
 macro(CHECK_VARIABLE_EXISTS VAR VARIABLE)
   if(NOT DEFINED "${VARIABLE}")
     set(MACRO_CHECK_VARIABLE_DEFINITIONS
diff --git a/Modules/Compiler/ARMCC.cmake b/Modules/Compiler/ARMCC.cmake
index 3cf628c..2ec75c3 100644
--- a/Modules/Compiler/ARMCC.cmake
+++ b/Modules/Compiler/ARMCC.cmake
@@ -20,11 +20,11 @@ set(CMAKE_AR "${CMAKE_ARMCC_AR}" CACHE FILEPATH "The ARMCC archiver" FORCE)
 mark_as_advanced(CMAKE_ARMCC_AR)
 
 macro(__compiler_armcc lang)
-  set(CMAKE_${lang}_FLAGS_INIT "")
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-g")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-Ospace -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-Otime -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -Ospace -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -Otime -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -g")
 
   set(CMAKE_${lang}_OUTPUT_EXTENSION ".o")
   set(CMAKE_${lang}_OUTPUT_EXTENSION_REPLACE 1)
diff --git a/Modules/Compiler/Absoft-Fortran.cmake b/Modules/Compiler/Absoft-Fortran.cmake
index 2e1666f..da1fc80 100644
--- a/Modules/Compiler/Absoft-Fortran.cmake
+++ b/Modules/Compiler/Absoft-Fortran.cmake
@@ -1,8 +1,8 @@
-set(CMAKE_Fortran_FLAGS_INIT "")
-set(CMAKE_Fortran_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "")
-set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-O3")
-set(CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " ")
+string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " ")
+string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " -O3")
+string(APPEND CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT " -O2 -g")
 set(CMAKE_Fortran_MODDIR_FLAG "-YMOD_OUT_DIR=")
 set(CMAKE_Fortran_MODPATH_FLAG "-p")
 set(CMAKE_Fortran_VERBOSE_FLAG "-v")
diff --git a/Modules/Compiler/AppleClang-DetermineCompiler.cmake b/Modules/Compiler/AppleClang-DetermineCompiler.cmake
index 397f95c..83817f7 100644
--- a/Modules/Compiler/AppleClang-DetermineCompiler.cmake
+++ b/Modules/Compiler/AppleClang-DetermineCompiler.cmake
@@ -3,5 +3,5 @@ set(_compiler_id_pp_test "defined(__clang__) && defined(__apple_build_version__)
 
 include("${CMAKE_CURRENT_LIST_DIR}/Clang-DetermineCompilerInternal.cmake")
 
-set(_compiler_id_version_compute "${_compiler_id_version_compute}
+string(APPEND _compiler_id_version_compute "
 # define @PREFIX at COMPILER_VERSION_TWEAK @MACRO_DEC@(__apple_build_version__)")
diff --git a/Modules/Compiler/Bruce-C.cmake b/Modules/Compiler/Bruce-C.cmake
index 23676ec..cfabe65 100644
--- a/Modules/Compiler/Bruce-C.cmake
+++ b/Modules/Compiler/Bruce-C.cmake
@@ -1,7 +1,7 @@
 # Bruce C Compiler ignores "-g" flag and optimization cannot be
 # enabled here (it is implemented only for 8086 target).
-set (CMAKE_C_FLAGS_INIT "-D__CLASSIC_C__")
-set (CMAKE_C_FLAGS_DEBUG_INIT "-g")
-set (CMAKE_C_FLAGS_MINSIZEREL_INIT "-DNDEBUG")
-set (CMAKE_C_FLAGS_RELEASE_INIT "-DNDEBUG")
-set (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-g -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_INIT " -D__CLASSIC_C__")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -g -DNDEBUG")
diff --git a/Modules/Compiler/Clang.cmake b/Modules/Compiler/Clang.cmake
index 701089c..96263fc 100644
--- a/Modules/Compiler/Clang.cmake
+++ b/Modules/Compiler/Clang.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_CLANG)
diff --git a/Modules/Compiler/G95-Fortran.cmake b/Modules/Compiler/G95-Fortran.cmake
index fd84848..2c83fb8 100644
--- a/Modules/Compiler/G95-Fortran.cmake
+++ b/Modules/Compiler/G95-Fortran.cmake
@@ -1,8 +1,8 @@
-set(CMAKE_Fortran_FLAGS_INIT "")
-set(CMAKE_Fortran_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "-Os")
-set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-O3")
-set(CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " ")
+string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " -Os")
+string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " -O3")
+string(APPEND CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT " -O2 -g")
 set(CMAKE_Fortran_MODDIR_FLAG "-fmod=")
 set(CMAKE_Fortran_VERBOSE_FLAG "-v")
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-ffixed-form")
diff --git a/Modules/Compiler/GHS-C.cmake b/Modules/Compiler/GHS-C.cmake
index 3072715..c30bdec 100644
--- a/Modules/Compiler/GHS-C.cmake
+++ b/Modules/Compiler/GHS-C.cmake
@@ -3,11 +3,11 @@ include(Compiler/GHS)
 set(CMAKE_C_VERBOSE_FLAG "-v")
 set(CMAKE_C_OUTPUT_EXTENSION ".o")
 
-set(CMAKE_C_FLAGS_INIT "")
-set(CMAKE_C_FLAGS_DEBUG_INIT "-Odebug -g")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "-Ospace")
-set(CMAKE_C_FLAGS_RELEASE_INIT "-O")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O -g")
+string(APPEND CMAKE_C_FLAGS_INIT " ")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -Odebug -g")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -Ospace")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -O")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -O -g")
 
 set(CMAKE_C_GHS_KERNEL_FLAGS_DEBUG_INIT "-ldebug ${CMAKE_C_FLAGS_DEBUG_INIT}")
 set(CMAKE_C_GHS_KERNEL_FLAGS_MINSIZEREL_INIT "${CMAKE_C_FLAGS_MINSIZEREL_INIT}")
diff --git a/Modules/Compiler/GHS-CXX.cmake b/Modules/Compiler/GHS-CXX.cmake
index a51591b..b3018a7 100644
--- a/Modules/Compiler/GHS-CXX.cmake
+++ b/Modules/Compiler/GHS-CXX.cmake
@@ -3,11 +3,11 @@ include(Compiler/GHS)
 set(CMAKE_CXX_VERBOSE_FLAG "-v")
 set(CMAKE_CXX_OUTPUT_EXTENSION ".o")
 
-set(CMAKE_CXX_FLAGS_INIT "")
-set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Odebug -g")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Ospace")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "-O")
-set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O -g")
+string(APPEND CMAKE_CXX_FLAGS_INIT " ")
+string(APPEND CMAKE_CXX_FLAGS_DEBUG_INIT " -Odebug -g")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -Ospace")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -O")
+string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " -O -g")
 
 set(CMAKE_CXX_GHS_KERNEL_FLAGS_DEBUG_INIT
   "-ldebug ${CMAKE_CXX_FLAGS_DEBUG_INIT}")
diff --git a/Modules/Compiler/GNU-Fortran.cmake b/Modules/Compiler/GNU-Fortran.cmake
index e9c8a59..94dc275 100644
--- a/Modules/Compiler/GNU-Fortran.cmake
+++ b/Modules/Compiler/GNU-Fortran.cmake
@@ -1,12 +1,15 @@
 include(Compiler/GNU)
 __compiler_gnu(Fortran)
 
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+  "<CMAKE_Fortran_COMPILER> -cpp <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> -o <PREPROCESSED_SOURCE>")
+
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-ffixed-form")
 set(CMAKE_Fortran_FORMAT_FREE_FLAG "-ffree-form")
 
 # No -DNDEBUG for Fortran.
-set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "-Os")
-set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-O3")
+string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " -Os")
+string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " -O3")
 
 # No -isystem for Fortran because it will not find .mod files.
 unset(CMAKE_INCLUDE_SYSTEM_FLAG_Fortran)
diff --git a/Modules/Compiler/GNU.cmake b/Modules/Compiler/GNU.cmake
index c2d393d..b67002c 100644
--- a/Modules/Compiler/GNU.cmake
+++ b/Modules/Compiler/GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_GNU)
@@ -25,7 +15,7 @@ macro(__compiler_gnu lang)
   if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 3.4)
     set(CMAKE_${lang}_COMPILE_OPTIONS_PIE "-fPIE")
   endif()
-  if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 4.2)
+  if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 4.0)
     set(CMAKE_${lang}_COMPILE_OPTIONS_VISIBILITY "-fvisibility=")
   endif()
   set(CMAKE_SHARED_LIBRARY_${lang}_FLAGS "-fPIC")
@@ -45,11 +35,11 @@ macro(__compiler_gnu lang)
   endif()
 
   # Initial configuration flags.
-  set(CMAKE_${lang}_FLAGS_INIT "")
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-g")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-O2 -g -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -Os -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -O3 -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -g -DNDEBUG")
   set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
   set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")
   if(NOT APPLE OR NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 4) # work around #4462
diff --git a/Modules/Compiler/IAR.cmake b/Modules/Compiler/IAR.cmake
index 8c6c3f6..8c45276 100644
--- a/Modules/Compiler/IAR.cmake
+++ b/Modules/Compiler/IAR.cmake
@@ -1,6 +1,6 @@
 # This file is processed when the IAR compiler is used for a C or C++ file
 # Documentation can be downloaded here: http://www.iar.com/website1/1.0.1.0/675/1/
-# The initial feature request is here: https://cmake.org/Bug/view.php?id=10176
+# The initial feature request is here: https://gitlab.kitware.com/cmake/cmake/issues/10176
 # It also contains additional links and information.
 
 if(_IAR_CMAKE_LOADED)
@@ -39,7 +39,8 @@ endif()
 
 if(NOT IAR_TARGET_ARCHITECTURE)
   message(FATAL_ERROR "The IAR compiler for this architecture is not yet supported "
-          " by CMake. Please go to https://cmake.org/Bug and enter a feature request there.")
+          "by CMake. Please go to https://gitlab.kitware.com/cmake/cmake/issues "
+          "and enter a feature request there.")
 endif()
 
 set(CMAKE_LINKER "${CMAKE_IAR_LINKER}" CACHE FILEPATH "The IAR linker" FORCE)
diff --git a/Modules/Compiler/Intel-ASM.cmake b/Modules/Compiler/Intel-ASM.cmake
index 74ceb0a..c2bf465 100644
--- a/Modules/Compiler/Intel-ASM.cmake
+++ b/Modules/Compiler/Intel-ASM.cmake
@@ -1,10 +1,9 @@
-set(CMAKE_ASM_VERBOSE_FLAG "-v")
+include(Compiler/Intel)
+__compiler_intel(ASM)
 
-set(CMAKE_ASM_FLAGS_INIT "")
-set(CMAKE_ASM_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_ASM_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
-set(CMAKE_ASM_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
-set(CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT "-O2 -g -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -DNDEBUG")
 
 if(UNIX)
   set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s;S)
diff --git a/Modules/Compiler/Intel-C.cmake b/Modules/Compiler/Intel-C.cmake
index edca154..1d09bd5 100644
--- a/Modules/Compiler/Intel-C.cmake
+++ b/Modules/Compiler/Intel-C.cmake
@@ -1,10 +1,9 @@
-set(CMAKE_C_VERBOSE_FLAG "-v")
+include(Compiler/Intel)
+__compiler_intel(C)
 
-set(CMAKE_C_FLAGS_INIT "")
-set(CMAKE_C_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
-set(CMAKE_C_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -DNDEBUG")
 
 set(CMAKE_DEPFILE_FLAGS_C "-MD -MT <OBJECT> -MF <DEPFILE>")
 
diff --git a/Modules/Compiler/Intel-CXX.cmake b/Modules/Compiler/Intel-CXX.cmake
index 369e041..3cc4503 100644
--- a/Modules/Compiler/Intel-CXX.cmake
+++ b/Modules/Compiler/Intel-CXX.cmake
@@ -1,10 +1,9 @@
-set(CMAKE_CXX_VERBOSE_FLAG "-v")
+include(Compiler/Intel)
+__compiler_intel(CXX)
 
-set(CMAKE_CXX_FLAGS_INIT "")
-set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " -DNDEBUG")
 
 set(CMAKE_DEPFILE_FLAGS_CXX "-MD -MT <OBJECT> -MF <DEPFILE>")
 
diff --git a/Modules/Compiler/Intel-Fortran.cmake b/Modules/Compiler/Intel-Fortran.cmake
index 671d284..a132055 100644
--- a/Modules/Compiler/Intel-Fortran.cmake
+++ b/Modules/Compiler/Intel-Fortran.cmake
@@ -1,12 +1,12 @@
-set(CMAKE_Fortran_FLAGS_INIT "")
-set(CMAKE_Fortran_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "-Os")
-set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-O3")
-set(CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
+include(Compiler/Intel)
+__compiler_intel(Fortran)
+
 set(CMAKE_Fortran_MODDIR_FLAG "-module ")
-set(CMAKE_Fortran_VERBOSE_FLAG "-v")
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-fixed")
 set(CMAKE_Fortran_FORMAT_FREE_FLAG "-free")
 
 set(CMAKE_Fortran_CREATE_PREPROCESSED_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
 set(CMAKE_Fortran_CREATE_ASSEMBLY_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")
+
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+  "<CMAKE_Fortran_COMPILER> -fpp <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
diff --git a/Modules/Compiler/Intel.cmake b/Modules/Compiler/Intel.cmake
new file mode 100644
index 0000000..02968b4
--- /dev/null
+++ b/Modules/Compiler/Intel.cmake
@@ -0,0 +1,26 @@
+# 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_INTEL)
+  return()
+endif()
+set(__COMPILER_INTEL 1)
+
+if(CMAKE_HOST_WIN32)
+  # MSVC-like
+  macro(__compiler_intel lang)
+  endmacro()
+else()
+  # GNU-like
+  macro(__compiler_intel lang)
+    set(CMAKE_${lang}_VERBOSE_FLAG "-v")
+
+    string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+    string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g")
+    string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -Os")
+    string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -O3")
+    string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -g")
+  endmacro()
+endif()
diff --git a/Modules/Compiler/MSVC-CXX-FeatureTests.cmake b/Modules/Compiler/MSVC-CXX-FeatureTests.cmake
index 79d5962..5969586 100644
--- a/Modules/Compiler/MSVC-CXX-FeatureTests.cmake
+++ b/Modules/Compiler/MSVC-CXX-FeatureTests.cmake
@@ -9,6 +9,9 @@
 
 set(_cmake_oldestSupported "_MSC_VER >= 1600")
 
+# VS version 15 (not 2015) introduces support for aggregate initializers.
+set(_cmake_feature_test_cxx_aggregate_default_initializers "_MSC_FULL_VER >= 190024406")
+
 # VS 2015 Update 2 introduces support for variable templates.
 # https://www.visualstudio.com/en-us/news/vs2015-update2-vs.aspx
 set(_cmake_feature_test_cxx_variable_templates "_MSC_FULL_VER >= 190023918")
diff --git a/Modules/Compiler/NAG-Fortran.cmake b/Modules/Compiler/NAG-Fortran.cmake
index 18f141e..39aae18 100644
--- a/Modules/Compiler/NAG-Fortran.cmake
+++ b/Modules/Compiler/NAG-Fortran.cmake
@@ -33,3 +33,4 @@ set(CMAKE_SHARED_LIBRARY_Fortran_FLAGS "-PIC")
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-fixed")
 set(CMAKE_Fortran_FORMAT_FREE_FLAG "-free")
 set(CMAKE_Fortran_COMPILE_OPTIONS_PIC "-PIC")
+set(CMAKE_Fortran_COMPILE_OPTIONS_PIE "-PIC")
diff --git a/Modules/Compiler/PGI-C.cmake b/Modules/Compiler/PGI-C.cmake
index da88c01..85d6e7e 100644
--- a/Modules/Compiler/PGI-C.cmake
+++ b/Modules/Compiler/PGI-C.cmake
@@ -1,4 +1,4 @@
 include(Compiler/PGI)
 __compiler_pgi(C)
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "${CMAKE_C_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
-set(CMAKE_C_FLAGS_RELEASE_INIT "${CMAKE_C_FLAGS_RELEASE_INIT} -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
diff --git a/Modules/Compiler/PGI-CXX.cmake b/Modules/Compiler/PGI-CXX.cmake
index 97c9555..896e298 100644
--- a/Modules/Compiler/PGI-CXX.cmake
+++ b/Modules/Compiler/PGI-CXX.cmake
@@ -1,4 +1,4 @@
 include(Compiler/PGI)
 __compiler_pgi(CXX)
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "${CMAKE_CXX_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "${CMAKE_CXX_FLAGS_RELEASE_INIT} -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -DNDEBUG")
diff --git a/Modules/Compiler/PGI-Fortran.cmake b/Modules/Compiler/PGI-Fortran.cmake
index 2866254..3765079 100644
--- a/Modules/Compiler/PGI-Fortran.cmake
+++ b/Modules/Compiler/PGI-Fortran.cmake
@@ -4,7 +4,7 @@ __compiler_pgi(Fortran)
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-Mnofreeform")
 set(CMAKE_Fortran_FORMAT_FREE_FLAG "-Mfreeform")
 
-set(CMAKE_Fortran_FLAGS_INIT "${CMAKE_Fortran_FLAGS_INIT} -Mpreprocess -Kieee")
-set(CMAKE_Fortran_FLAGS_DEBUG_INIT "${CMAKE_Fortran_FLAGS_DEBUG_INIT} -Mbounds")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " -Mpreprocess -Kieee")
+string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -Mbounds")
 
 set(CMAKE_Fortran_MODDIR_FLAG "-module ")
diff --git a/Modules/Compiler/PGI.cmake b/Modules/Compiler/PGI.cmake
index 797945f..cc76deb 100644
--- a/Modules/Compiler/PGI.cmake
+++ b/Modules/Compiler/PGI.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_PGI)
@@ -23,11 +13,11 @@ macro(__compiler_pgi lang)
   set(CMAKE_${lang}_VERBOSE_FLAG "-v")
 
   # Initial configuration flags.
-  set(CMAKE_${lang}_FLAGS_INIT "")
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-g -O0")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-O2 -s")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-fast -O3 -Mipa=fast")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-O2 -gopt")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g -O0")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -O2 -s")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -fast -O3 -Mipa=fast")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -gopt")
 
   # Preprocessing and assembly rules.
   set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
diff --git a/Modules/Compiler/PathScale-C.cmake b/Modules/Compiler/PathScale-C.cmake
index 9db54af..94c7d08 100644
--- a/Modules/Compiler/PathScale-C.cmake
+++ b/Modules/Compiler/PathScale-C.cmake
@@ -1,4 +1,4 @@
 include(Compiler/PathScale)
 __compiler_pathscale(C)
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "${CMAKE_C_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
-set(CMAKE_C_FLAGS_RELEASE_INIT "${CMAKE_C_FLAGS_RELEASE_INIT} -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
diff --git a/Modules/Compiler/PathScale-CXX.cmake b/Modules/Compiler/PathScale-CXX.cmake
index 4dd7660..276b81b 100644
--- a/Modules/Compiler/PathScale-CXX.cmake
+++ b/Modules/Compiler/PathScale-CXX.cmake
@@ -1,4 +1,4 @@
 include(Compiler/PathScale)
 __compiler_pathscale(CXX)
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "${CMAKE_CXX_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "${CMAKE_CXX_FLAGS_RELEASE_INIT} -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -DNDEBUG")
diff --git a/Modules/Compiler/PathScale.cmake b/Modules/Compiler/PathScale.cmake
index 107f779..d5f8cb1 100644
--- a/Modules/Compiler/PathScale.cmake
+++ b/Modules/Compiler/PathScale.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_PATHSCALE)
@@ -23,9 +13,9 @@ macro(__compiler_pathscale lang)
   set(CMAKE_${lang}_VERBOSE_FLAG "-v")
 
   # Initial configuration flags.
-  set(CMAKE_${lang}_FLAGS_INIT "")
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-g -O0")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-Os")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-O3")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-g -O2")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g -O0")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -Os")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -O3")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -g -O2")
 endmacro()
diff --git a/Modules/Compiler/QCC.cmake b/Modules/Compiler/QCC.cmake
index f69c7bd..2d7e881 100644
--- a/Modules/Compiler/QCC.cmake
+++ b/Modules/Compiler/QCC.cmake
@@ -1,16 +1,7 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 
-#=============================================================================
-# Copyright 2002-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 include(Compiler/GNU)
 
 macro(__compiler_qcc lang)
diff --git a/Modules/Compiler/SCO.cmake b/Modules/Compiler/SCO.cmake
index f673c8f..c55a048 100644
--- a/Modules/Compiler/SCO.cmake
+++ b/Modules/Compiler/SCO.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_SCO)
diff --git a/Modules/Compiler/SunPro-ASM.cmake b/Modules/Compiler/SunPro-ASM.cmake
index 2fa8b99..0d67400 100644
--- a/Modules/Compiler/SunPro-ASM.cmake
+++ b/Modules/Compiler/SunPro-ASM.cmake
@@ -8,11 +8,11 @@ set(CMAKE_SHARED_LIBRARY_RUNTIME_ASM_FLAG "-R")
 set(CMAKE_SHARED_LIBRARY_RUNTIME_ASM_FLAG_SEP ":")
 set(CMAKE_SHARED_LIBRARY_SONAME_ASM_FLAG "-h")
 
-set(CMAKE_ASM_FLAGS_INIT "")
-set(CMAKE_ASM_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_ASM_FLAGS_MINSIZEREL_INIT "-xO2 -xspace -DNDEBUG")
-set(CMAKE_ASM_FLAGS_RELEASE_INIT "-xO3 -DNDEBUG")
-set(CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT "-g -xO2 -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_INIT " ")
+string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG")
 
 # Initialize ASM link type selection flags.  These flags are used when
 # building a shared library, shared module, or executable that links
diff --git a/Modules/Compiler/SunPro-C.cmake b/Modules/Compiler/SunPro-C.cmake
index c452983..503684a 100644
--- a/Modules/Compiler/SunPro-C.cmake
+++ b/Modules/Compiler/SunPro-C.cmake
@@ -7,11 +7,11 @@ set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "-R")
 set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP ":")
 set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-h")
 
-set(CMAKE_C_FLAGS_INIT "")
-set(CMAKE_C_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "-xO2 -xspace -DNDEBUG")
-set(CMAKE_C_FLAGS_RELEASE_INIT "-xO3 -DNDEBUG")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-g -xO2 -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_INIT " ")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG")
 
 # Initialize C link type selection flags.  These flags are used when
 # building a shared library, shared module, or executable that links
diff --git a/Modules/Compiler/SunPro-CXX.cmake b/Modules/Compiler/SunPro-CXX.cmake
index b4a5591..ce01cdd 100644
--- a/Modules/Compiler/SunPro-CXX.cmake
+++ b/Modules/Compiler/SunPro-CXX.cmake
@@ -7,11 +7,11 @@ set(CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG "-R")
 set(CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG_SEP ":")
 set(CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG "-h")
 
-set(CMAKE_CXX_FLAGS_INIT "")
-set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-xO2 -xspace -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "-xO3 -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-g -xO2 -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_INIT " ")
+string(APPEND CMAKE_CXX_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG")
 
 # Initialize C link type selection flags.  These flags are used when
 # building a shared library, shared module, or executable that links
diff --git a/Modules/Compiler/SunPro-Fortran.cmake b/Modules/Compiler/SunPro-Fortran.cmake
index 610e191..6607926 100644
--- a/Modules/Compiler/SunPro-Fortran.cmake
+++ b/Modules/Compiler/SunPro-Fortran.cmake
@@ -10,13 +10,16 @@ set(CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG_SEP ":")
 set(CMAKE_SHARED_LIBRARY_SONAME_Fortran_FLAG "-h")
 set(CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG "-R")
 
-set(CMAKE_Fortran_FLAGS_INIT "")
-set(CMAKE_Fortran_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "-xO2 -xspace -DNDEBUG")
-set(CMAKE_Fortran_FLAGS_RELEASE_INIT "-xO3 -DNDEBUG")
-set(CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "-g -xO2 -DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " ")
+string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG")
 set(CMAKE_Fortran_MODDIR_FLAG "-moddir=")
 set(CMAKE_Fortran_MODPATH_FLAG "-M")
 
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+  "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -F <SOURCE> -o <PREPROCESSED_SOURCE>")
+
 set(CMAKE_Fortran_CREATE_PREPROCESSED_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -F <SOURCE> -o <PREPROCESSED_SOURCE>")
 set(CMAKE_Fortran_CREATE_ASSEMBLY_SOURCE "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")
diff --git a/Modules/Compiler/TinyCC-C.cmake b/Modules/Compiler/TinyCC-C.cmake
index f7937ac..fbd2841 100644
--- a/Modules/Compiler/TinyCC-C.cmake
+++ b/Modules/Compiler/TinyCC-C.cmake
@@ -1,8 +1,8 @@
 set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-shared")
 
 # no optimization in tcc:
-set (CMAKE_C_FLAGS_INIT "")
-set (CMAKE_C_FLAGS_DEBUG_INIT "-g")
-set (CMAKE_C_FLAGS_MINSIZEREL_INIT "-DNDEBUG")
-set (CMAKE_C_FLAGS_RELEASE_INIT "-DNDEBUG")
-set (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-g -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_INIT " ")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -g -DNDEBUG")
diff --git a/Modules/Compiler/XL-ASM.cmake b/Modules/Compiler/XL-ASM.cmake
index 212179e..9177b39 100644
--- a/Modules/Compiler/XL-ASM.cmake
+++ b/Modules/Compiler/XL-ASM.cmake
@@ -2,11 +2,11 @@ set(CMAKE_ASM_VERBOSE_FLAG "-V")
 
 # -qthreaded     = Ensures that all optimizations will be thread-safe
 # -qhalt=e       = Halt on error messages (rather than just severe errors)
-set(CMAKE_ASM_FLAGS_INIT "-qthreaded -qhalt=e -qsourcetype=assembler")
+string(APPEND CMAKE_ASM_FLAGS_INIT " -qthreaded -qhalt=e -qsourcetype=assembler")
 
-set(CMAKE_ASM_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_ASM_FLAGS_RELEASE_INIT "-O -DNDEBUG")
-set(CMAKE_ASM_FLAGS_MINSIZEREL_INIT "-O -DNDEBUG")
-set(CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT "-g -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -O -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -O -DNDEBUG")
+string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -g -DNDEBUG")
 
 set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s )
diff --git a/Modules/Compiler/XL-C.cmake b/Modules/Compiler/XL-C.cmake
index 97dd017..f976c99 100644
--- a/Modules/Compiler/XL-C.cmake
+++ b/Modules/Compiler/XL-C.cmake
@@ -1,8 +1,8 @@
 include(Compiler/XL)
 __compiler_xl(C)
-set(CMAKE_C_FLAGS_RELEASE_INIT "${CMAKE_C_FLAGS_RELEASE_INIT} -DNDEBUG")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "${CMAKE_C_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
 
 # -qthreaded     = Ensures that all optimizations will be thread-safe
 # -qhalt=e       = Halt on error messages (rather than just severe errors)
-set(CMAKE_C_FLAGS_INIT "-qthreaded -qhalt=e")
+string(APPEND CMAKE_C_FLAGS_INIT " -qthreaded -qhalt=e")
diff --git a/Modules/Compiler/XL-CXX.cmake b/Modules/Compiler/XL-CXX.cmake
index 41372c1..545d657 100644
--- a/Modules/Compiler/XL-CXX.cmake
+++ b/Modules/Compiler/XL-CXX.cmake
@@ -1,11 +1,11 @@
 include(Compiler/XL)
 __compiler_xl(CXX)
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "${CMAKE_CXX_FLAGS_RELEASE_INIT} -DNDEBUG")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "${CMAKE_CXX_FLAGS_MINSIZEREL_INIT} -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
 
 # -qthreaded     = Ensures that all optimizations will be thread-safe
 # -qhalt=e       = Halt on error messages (rather than just severe errors)
-set(CMAKE_CXX_FLAGS_INIT "-qthreaded -qhalt=e")
+string(APPEND CMAKE_CXX_FLAGS_INIT " -qthreaded -qhalt=e")
 
 set(CMAKE_CXX_COMPILE_OBJECT
   "<CMAKE_CXX_COMPILER> -+ <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
diff --git a/Modules/Compiler/XL-Fortran.cmake b/Modules/Compiler/XL-Fortran.cmake
index ae9df4e..6bab6f6 100644
--- a/Modules/Compiler/XL-Fortran.cmake
+++ b/Modules/Compiler/XL-Fortran.cmake
@@ -10,7 +10,7 @@ set(CMAKE_Fortran_DEFINE_FLAG "-WF,-D")
 
 # -qthreaded     = Ensures that all optimizations will be thread-safe
 # -qhalt=e       = Halt on error messages (rather than just severe errors)
-set(CMAKE_Fortran_FLAGS_INIT "-qthreaded -qhalt=e")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " -qthreaded -qhalt=e")
 
 # xlf: 1501-214 (W) command option E reserved for future use - ignored
 set(CMAKE_Fortran_CREATE_PREPROCESSED_SOURCE)
diff --git a/Modules/Compiler/XL.cmake b/Modules/Compiler/XL.cmake
index bf4f554..55f71bd 100644
--- a/Modules/Compiler/XL.cmake
+++ b/Modules/Compiler/XL.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__COMPILER_XL)
@@ -29,10 +19,10 @@ macro(__compiler_xl lang)
   set(CMAKE_${lang}_VERBOSE_FLAG "-V")
   set(CMAKE_${lang}_COMPILE_OPTIONS_PIC "-qpic")
 
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-g")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-O")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-O")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-g")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -O")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -O")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -g")
   set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
   set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE     "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")
 
diff --git a/Modules/CompilerId/Xcode-3.pbxproj.in b/Modules/CompilerId/Xcode-3.pbxproj.in
index 20f3da3..22ad4f6 100644
--- a/Modules/CompilerId/Xcode-3.pbxproj.in
+++ b/Modules/CompilerId/Xcode-3.pbxproj.in
@@ -84,6 +84,7 @@
 				CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)";
 				SYMROOT = .;
 				@id_toolset@
+				@id_lang_version@
 				@id_deployment_target@
 				@id_sdkroot@
 			};
diff --git a/Modules/Dart.cmake b/Modules/Dart.cmake
index db487d8..e003cd5 100644
--- a/Modules/Dart.cmake
+++ b/Modules/Dart.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Dart
 # ----
@@ -29,19 +32,6 @@
 #
 #
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 option(BUILD_TESTING "Build the testing tree." ON)
 
 if(BUILD_TESTING)
@@ -119,7 +109,7 @@ if(BUILD_TESTING)
     # add testing targets
     set(DART_EXPERIMENTAL_NAME Experimental)
     if(DART_EXPERIMENTAL_USE_PROJECT_NAME)
-      set(DART_EXPERIMENTAL_NAME "${DART_EXPERIMENTAL_NAME}${PROJECT_NAME}")
+      string(APPEND DART_EXPERIMENTAL_NAME "${PROJECT_NAME}")
     endif()
   endif ()
 
diff --git a/Modules/DeployQt4.cmake b/Modules/DeployQt4.cmake
index de475e4..8ada451 100644
--- a/Modules/DeployQt4.cmake
+++ b/Modules/DeployQt4.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # DeployQt4
 # ---------
@@ -99,19 +102,6 @@
 # at install time.  <component> is the COMPONENT used for bundle fixup
 # and plugin installation.  See documentation of FIXUP_QT4_BUNDLE.
 
-#=============================================================================
-# Copyright 2011 Mike McQuaid <mike at mikemcquaid.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # The functions defined in this file depend on the fixup_bundle function
 # (and others) found in BundleUtilities.cmake
 
@@ -247,7 +237,7 @@ function(install_qt4_plugin_path plugin executable copy installed_plugin_path_va
                                 set(plugins_path ".")
                         endif()
                         if(plugins_dir)
-                                set(plugins_path "${plugins_path}/${plugins_dir}")
+                                string(APPEND plugins_path "/${plugins_dir}")
                         endif()
                 endif()
 
@@ -263,7 +253,7 @@ function(install_qt4_plugin_path plugin executable copy installed_plugin_path_va
                         get_filename_component(plugin_group "${plugin_path}" NAME)
                         set(${plugin_group_var} "${plugin_group}")
                 endif()
-                set(plugins_path "${plugins_path}/${plugin_group}")
+                string(APPEND plugins_path "/${plugin_group}")
 
                 if(${copy})
                         file(MAKE_DIRECTORY "${plugins_path}")
diff --git a/Modules/Documentation.cmake b/Modules/Documentation.cmake
index be6aaea..fc398e6 100644
--- a/Modules/Documentation.cmake
+++ b/Modules/Documentation.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Documentation
 # -------------
@@ -7,19 +10,6 @@
 # This file provides support for the VTK documentation framework.  It
 # relies on several tools (Doxygen, Perl, etc).
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # Build the documentation ?
 #
diff --git a/Modules/ExternalData.cmake b/Modules/ExternalData.cmake
index a3f460d..b00de14 100644
--- a/Modules/ExternalData.cmake
+++ b/Modules/ExternalData.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 ExternalData
 ------------
@@ -86,6 +89,10 @@ Module Functions
   in one of the paths specified in the ``ExternalData_OBJECT_STORES``
   variable.
 
+  Typically only one target is needed to manage all external data within
+  a project.  Call this function once at the end of configuration after
+  all data references have been processed.
+
 Module Variables
 ^^^^^^^^^^^^^^^^
 
@@ -312,19 +319,6 @@ file or set a variable:
 
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2010-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(ExternalData_add_test target)
   # Expand all arguments as a single string to preserve escaped semicolons.
   ExternalData_expand_arguments("${target}" testArgs "${ARGN}")
@@ -394,8 +388,14 @@ function(ExternalData_add_target target)
 
   set(files "")
 
-  # Set "_ExternalData_FILE_${file}" for each output file to avoid duplicate
-  # rules.  Use local data first to prefer real files over content links.
+  # Set a "_ExternalData_FILE_${file}" variable for each output file to avoid
+  # duplicate entries within this target.  Set a directory property of the same
+  # name to avoid repeating custom commands with the same output in this directory.
+  # Repeating custom commands with the same output across directories or across
+  # targets in the same directory may be a race, but this is likely okay because
+  # we use atomic replacement of output files.
+  #
+  # Use local data first to prefer real files over content links.
 
   # Custom commands to copy or link local data.
   get_property(data_local GLOBAL PROPERTY _ExternalData_${target}_LOCAL)
@@ -405,16 +405,20 @@ function(ExternalData_add_target target)
     list(GET tuple 1 name)
     if(NOT DEFINED "_ExternalData_FILE_${file}")
       set("_ExternalData_FILE_${file}" 1)
-      add_custom_command(
-        COMMENT "Generating ${file}"
-        OUTPUT "${file}"
-        COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
-                                 -Dfile=${file} -Dname=${name}
-                                 -DExternalData_ACTION=local
-                                 -DExternalData_CONFIG=${config}
-                                 -P ${_ExternalData_SELF}
-        MAIN_DEPENDENCY "${name}"
-        )
+      get_property(added DIRECTORY PROPERTY "_ExternalData_FILE_${file}")
+      if(NOT added)
+        set_property(DIRECTORY PROPERTY "_ExternalData_FILE_${file}" 1)
+        add_custom_command(
+          COMMENT "Generating ${file}"
+          OUTPUT "${file}"
+          COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
+                                   -Dfile=${file} -Dname=${name}
+                                   -DExternalData_ACTION=local
+                                   -DExternalData_CONFIG=${config}
+                                   -P ${_ExternalData_SELF}
+          MAIN_DEPENDENCY "${name}"
+          )
+      endif()
       list(APPEND files "${file}")
     endif()
   endforeach()
@@ -429,23 +433,27 @@ function(ExternalData_add_target target)
     set(stamp "${ext}-stamp")
     if(NOT DEFINED "_ExternalData_FILE_${file}")
       set("_ExternalData_FILE_${file}" 1)
-      add_custom_command(
-        # Users care about the data file, so hide the hash/timestamp file.
-        COMMENT "Generating ${file}"
-        # The hash/timestamp file is the output from the build perspective.
-        # List the real file as a second output in case it is a broken link.
-        # The files must be listed in this order so CMake can hide from the
-        # make tool that a symlink target may not be newer than the input.
-        OUTPUT "${file}${stamp}" "${file}"
-        # Run the data fetch/update script.
-        COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
-                                 -Dfile=${file} -Dname=${name} -Dext=${ext}
-                                 -DExternalData_ACTION=fetch
-                                 -DExternalData_CONFIG=${config}
-                                 -P ${_ExternalData_SELF}
-        # Update whenever the object hash changes.
-        MAIN_DEPENDENCY "${name}${ext}"
-        )
+      get_property(added DIRECTORY PROPERTY "_ExternalData_FILE_${file}")
+      if(NOT added)
+        set_property(DIRECTORY PROPERTY "_ExternalData_FILE_${file}" 1)
+        add_custom_command(
+          # Users care about the data file, so hide the hash/timestamp file.
+          COMMENT "Generating ${file}"
+          # The hash/timestamp file is the output from the build perspective.
+          # List the real file as a second output in case it is a broken link.
+          # The files must be listed in this order so CMake can hide from the
+          # make tool that a symlink target may not be newer than the input.
+          OUTPUT "${file}${stamp}" "${file}"
+          # Run the data fetch/update script.
+          COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
+                                   -Dfile=${file} -Dname=${name} -Dext=${ext}
+                                   -DExternalData_ACTION=fetch
+                                   -DExternalData_CONFIG=${config}
+                                   -P ${_ExternalData_SELF}
+          # Update whenever the object hash changes.
+          MAIN_DEPENDENCY "${name}${ext}"
+          )
+      endif()
       list(APPEND files "${file}${stamp}")
     endif()
   endforeach()
@@ -473,10 +481,10 @@ function(ExternalData_expand_arguments target outArgsVar)
         if("x${piece}" MATCHES "^x${data_regex}$")
           # Replace this DATA{}-piece with a file path.
           _ExternalData_arg("${target}" "${piece}" "${CMAKE_MATCH_1}" file)
-          set(outArg "${outArg}${file}")
+          string(APPEND outArg "${file}")
         else()
           # No replacement needed for this piece.
-          set(outArg "${outArg}${piece}")
+          string(APPEND outArg "${piece}")
         endif()
       endforeach()
     else()
@@ -696,12 +704,12 @@ macro(_ExternalData_arg_associated)
     get_filename_component(reldir "${reldata}" PATH)
   endif()
   if(reldir)
-    set(reldir "${reldir}/")
+    string(APPEND reldir "/")
   endif()
   _ExternalData_exact_regex(reldir_regex "${reldir}")
   if(recurse_option)
     set(glob GLOB_RECURSE)
-    set(reldir_regex "${reldir_regex}(.+/)?")
+    string(APPEND reldir_regex "(.+/)?")
   else()
     set(glob GLOB)
   endif()
@@ -717,7 +725,7 @@ macro(_ExternalData_arg_associated)
   set(all "")
   set(sep "")
   foreach(regex ${associated_regex})
-    set(all "${all}${sep}${reldir_regex}${regex}")
+    string(APPEND all "${sep}${reldir_regex}${regex}")
     set(sep "|")
   endforeach()
   _ExternalData_arg_find_files(${glob} "${reldir}" "${all}")
@@ -971,15 +979,16 @@ function(_ExternalData_download_object name hash algo var_obj)
         set(url "${lhs}${algo}${rhs}")
       endif()
     endif()
-    message(STATUS "Fetching \"${url}\"")
+    string(REGEX REPLACE "((https?|ftp)://)([^@]+@)?(.*)" "\\1\\4" secured_url "${url}")
+    message(STATUS "Fetching \"${secured_url}\"")
     if(url MATCHES "^ExternalDataCustomScript://([A-Za-z_][A-Za-z0-9_]*)/(.*)$")
       _ExternalData_custom_fetch("${CMAKE_MATCH_1}" "${CMAKE_MATCH_2}" "${tmp}" err errMsg)
     else()
       _ExternalData_download_file("${url}" "${tmp}" err errMsg)
     endif()
-    set(tried "${tried}\n  ${url}")
+    string(APPEND tried "\n  ${url}")
     if(err)
-      set(tried "${tried} (${errMsg})")
+      string(APPEND tried " (${errMsg})")
     else()
       # Verify downloaded object.
       _ExternalData_compute_hash(dl_hash "${algo}" "${tmp}")
@@ -987,7 +996,7 @@ function(_ExternalData_download_object name hash algo var_obj)
         set(found 1)
         break()
       else()
-        set(tried "${tried} (wrong hash ${algo}=${dl_hash})")
+        string(APPEND tried " (wrong hash ${algo}=${dl_hash})")
         if("$ENV{ExternalData_DEBUG_DOWNLOAD}" MATCHES ".")
           file(RENAME "${tmp}" "${store}/${algo}/${dl_hash}")
         endif()
diff --git a/Modules/ExternalProject-download.cmake.in b/Modules/ExternalProject-download.cmake.in
index 5b73cd8..7f92596 100644
--- a/Modules/ExternalProject-download.cmake.in
+++ b/Modules/ExternalProject-download.cmake.in
@@ -1,16 +1,5 @@
-#=============================================================================
-# Copyright 2008-2013 Kitware, Inc.
-# Copyright 2016 Ruslan Baratov
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# 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.5)
 
@@ -114,48 +103,58 @@ endif()
 
 set(retry_number 5)
 
+message(STATUS "Downloading...
+   dst='@LOCAL@'
+   timeout='@TIMEOUT_MSG@'"
+)
+
 foreach(i RANGE ${retry_number})
   sleep_before_download(${i})
 
-  message(STATUS "downloading...
-       src='@REMOTE@'
-       dst='@LOCAL@'
-       timeout='@TIMEOUT_MSG@'")
-
-  @TLS_VERIFY_CODE@
-  @TLS_CAINFO_CODE@
-
-  file(
-      DOWNLOAD
-      "@REMOTE@" "@LOCAL@"
-      @SHOW_PROGRESS@
-      @TIMEOUT_ARGS@
-      STATUS status
-      LOG log
-  )
-
-  list(GET status 0 status_code)
-  list(GET status 1 status_string)
-
-  if(status_code EQUAL 0)
-    check_file_hash(has_hash hash_is_good)
-    if(has_hash AND NOT hash_is_good)
-      message(STATUS "Hash mismatch, removing...")
-      file(REMOVE "@LOCAL@")
+  foreach(url @REMOTE@)
+    message(STATUS "Using src='${url}'")
+
+    @TLS_VERIFY_CODE@
+    @TLS_CAINFO_CODE@
+
+    file(
+        DOWNLOAD
+        "${url}" "@LOCAL@"
+        @SHOW_PROGRESS@
+        @TIMEOUT_ARGS@
+        STATUS status
+        LOG log
+        @USERPWD_ARGS@
+        @HTTP_HEADERS_ARGS@
+    )
+
+    list(GET status 0 status_code)
+    list(GET status 1 status_string)
+
+    if(status_code EQUAL 0)
+      check_file_hash(has_hash hash_is_good)
+      if(has_hash AND NOT hash_is_good)
+        message(STATUS "Hash mismatch, removing...")
+        file(REMOVE "@LOCAL@")
+      else()
+        message(STATUS "Downloading... done")
+        return()
+      endif()
     else()
-      message(STATUS "Downloading... done")
-      return()
+      string(APPEND logFailedURLs "error: downloading '${url}' failed
+       status_code: ${status_code}
+       status_string: ${status_string}
+       log:
+       --- LOG BEGIN ---
+       ${log}
+       --- LOG END ---
+       "
+      )
     endif()
-  else()
-    message("error: downloading '@REMOTE@' failed
-  status_code: ${status_code}
-  status_string: ${status_string}
-  log:
-  --- LOG BEGIN ---
-  ${log}
-  --- LOG END ---"
-    )
-  endif()
+  endforeach()
 endforeach()
 
-message(FATAL_ERROR "Downloading failed")
+message(FATAL_ERROR "Each download failed!
+  ${logFailedURLs}
+  "
+)
diff --git a/Modules/ExternalProject-verify.cmake.in b/Modules/ExternalProject-verify.cmake.in
index 1d8db96..c06da4e 100644
--- a/Modules/ExternalProject-verify.cmake.in
+++ b/Modules/ExternalProject-verify.cmake.in
@@ -1,16 +1,5 @@
-#=============================================================================
-# Copyright 2008-2013 Kitware, Inc.
-# Copyright 2016 Ruslan Baratov
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# 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.5)
 
diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake
index 2ff18fc..4551cc8 100644
--- a/Modules/ExternalProject.cmake
+++ b/Modules/ExternalProject.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 ExternalProject
 ---------------
@@ -69,12 +72,18 @@ Create custom targets to build projects in external trees
     URL of mercurial repo
   ``HG_TAG <tag>``
     Mercurial branch name, commit id or tag
-  ``URL /.../src.tgz``
-    Full path or URL of source
+  ``URL /.../src.tgz [/.../src.tgz]...``
+    Full path or URL(s) of source.  Multiple URLs are allowed as mirrors.
   ``URL_HASH ALGO=value``
     Hash of file at URL
   ``URL_MD5 md5``
     Equivalent to URL_HASH MD5=md5
+  ``HTTP_USERNAME <username>``
+    Username for download operation
+  ``HTTP_PASSWORD <username>``
+    Password for download operation
+  ``HTTP_HEADER <header>``
+    HTTP header for download operation. Suboption can be repeated several times.
   ``TLS_VERIFY <bool>``
     Should certificate for https be checked
   ``TLS_CAINFO <file>``
@@ -98,6 +107,8 @@ Create custom targets to build projects in external trees
 
   ``SOURCE_DIR <dir>``
     Source dir to be used for build
+  ``SOURCE_SUBDIR <dir>``
+    Path to source CMakeLists.txt relative to ``SOURCE_DIR``
   ``CONFIGURE_COMMAND <cmd>...``
     Build tree configuration command
   ``CMAKE_COMMAND /.../cmake``
@@ -236,6 +247,11 @@ Create custom targets to build projects in external trees
   interpreted with respect to the build directory corresponding to the
   source directory in which ``ExternalProject_Add`` is invoked.
 
+  If ``SOURCE_SUBDIR`` is set and no ``CONFIGURE_COMMAND`` is specified, the
+  configure command will run CMake using the ``CMakeLists.txt`` located in the
+  relative path specified by ``SOURCE_SUBDIR``, relative to the ``SOURCE_DIR``.
+  If no ``SOURCE_SUBDIR`` is given, ``SOURCE_DIR`` is used.
+
   If ``SOURCE_DIR`` is explicitly set to an existing directory the project
   will be built from it.  Otherwise a download step must be specified
   using one of the ``DOWNLOAD_COMMAND``, ``CVS_*``, ``SVN_*``, or ``URL``
@@ -287,8 +303,8 @@ Create custom targets to build projects in external trees
 
   The command line, comment, working directory, and byproducts of every
   standard and custom step are processed to replace tokens ``<SOURCE_DIR>``,
-  ``<BINARY_DIR>``, ``<INSTALL_DIR>``, and ``<TMP_DIR>`` with
-  corresponding property values.
+  ``<SOURCE_SUBDIR>``,  ``<BINARY_DIR>``, ``<INSTALL_DIR>``, and ``<TMP_DIR>``
+  with corresponding property values.
 
 Any builtin step that specifies a ``<step>_COMMAND cmd...`` or custom
 step that specifies a ``COMMAND cmd...`` may specify additional command
@@ -375,20 +391,6 @@ file::
   ``ExternalProject``.
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2008-2013 Kitware, Inc.
-# Copyright 2016 Ruslan Baratov
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Pre-compute a regex to match documented keywords for each command.
 math(EXPR _ep_documentation_line_count "${CMAKE_CURRENT_LIST_LINE} - 16")
 file(STRINGS "${CMAKE_CURRENT_LIST_FILE}" lines
@@ -851,7 +853,7 @@ endif()
 
 endfunction(_ep_write_gitupdate_script)
 
-function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_progress hash tls_verify tls_cainfo)
+function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_progress hash tls_verify tls_cainfo userpwd http_headers)
   if(timeout)
     set(TIMEOUT_ARGS TIMEOUT ${timeout})
     set(TIMEOUT_MSG "${timeout} seconds")
@@ -899,6 +901,22 @@ function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_p
     set(TLS_CAINFO_CODE "set(CMAKE_TLS_CAINFO \"${tls_cainfo}\")")
   endif()
 
+  if(userpwd STREQUAL ":")
+    set(USERPWD_ARGS)
+  else()
+    set(USERPWD_ARGS USERPWD "${userpwd}")
+  endif()
+
+  set(HTTP_HEADERS_ARGS "")
+  if(NOT http_headers STREQUAL "")
+    foreach(header ${http_headers})
+      set(
+          HTTP_HEADERS_ARGS
+          "HTTPHEADER \"${header}\"\n        ${HTTP_HEADERS_ARGS}"
+      )
+    endforeach()
+  endif()
+
   # Used variables:
   # * TLS_VERIFY_CODE
   # * TLS_CAINFO_CODE
@@ -909,6 +927,8 @@ function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_p
   # * SHOW_PROGRESS
   # * TIMEOUT_ARGS
   # * TIMEOUT_MSG
+  # * USERPWD_ARGS
+  # * HTTP_HEADERS_ARGS
   configure_file(
       "${_ExternalProject_SELF_DIR}/ExternalProject-download.cmake.in"
       "${script_filename}"
@@ -993,6 +1013,7 @@ endif()
 #
 message(STATUS \"extracting... [analysis]\")
 file(GLOB contents \"\${ut_dir}/*\")
+list(REMOVE_ITEM contents \"\${ut_dir}/.DS_Store\")
 list(LENGTH contents n)
 if(NOT n EQUAL 1 OR NOT IS_DIRECTORY \"\${contents}\")
   set(contents \"\${ut_dir}\")
@@ -1064,6 +1085,17 @@ function(_ep_set_directories name)
     endif()
     set_property(TARGET ${name} PROPERTY _EP_${VAR}_DIR "${${var}_dir}")
   endforeach()
+  get_property(source_subdir TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR)
+  if(NOT source_subdir)
+    set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "")
+  elseif(IS_ABSOLUTE "${source_subdir}")
+    message(FATAL_ERROR
+      "External project ${name} has non-relative SOURCE_SUBDIR!")
+  else()
+    # Prefix with a slash so that when appended to the source directory, it
+    # behaves as expected.
+    set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "/${source_subdir}")
+  endif()
   if(build_in_source)
     get_property(source_dir TARGET ${name} PROPERTY _EP_SOURCE_DIR)
     set_property(TARGET ${name} PROPERTY _EP_BINARY_DIR "${source_dir}")
@@ -1095,7 +1127,7 @@ macro(_ep_replace_location_tags target_name)
   set(vars ${ARGN})
   foreach(var ${vars})
     if(${var})
-      foreach(dir SOURCE_DIR BINARY_DIR INSTALL_DIR TMP_DIR DOWNLOADED_FILE)
+      foreach(dir SOURCE_DIR SOURCE_SUBDIR BINARY_DIR INSTALL_DIR TMP_DIR DOWNLOADED_FILE)
         get_property(val TARGET ${target_name} PROPERTY _EP_${dir})
         string(REPLACE "<${dir}>" "${val}" ${var} "${${var}}")
       endforeach()
@@ -1117,8 +1149,8 @@ function(_ep_command_line_to_initial_cache var args force)
       set(line "${CMAKE_MATCH_1}")
       if(setArg)
         # This is required to build up lists in variables, or complete an entry
-        set(setArg "${setArg}${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
-        set(script_initial_cache "${script_initial_cache}\n${setArg}")
+        string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
+        string(APPEND script_initial_cache "\n${setArg}")
         set(accumulator "")
         set(setArg "")
       endif()
@@ -1132,13 +1164,13 @@ function(_ep_command_line_to_initial_cache var args force)
       endif()
     else()
       # Assume this is a list to append to the last var
-      set(accumulator "${accumulator};${line}")
+      string(APPEND accumulator ";${line}")
     endif()
   endforeach()
   # Catch the final line of the args
   if(setArg)
-    set(setArg "${setArg}${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
-    set(script_initial_cache "${script_initial_cache}\n${setArg}")
+    string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
+    string(APPEND script_initial_cache "\n${setArg}")
   endif()
   set(${var} ${script_initial_cache} PARENT_SCOPE)
 endfunction()
@@ -1156,10 +1188,11 @@ endfunction()
 function(ExternalProject_Get_Property name)
   foreach(var ${ARGN})
     string(TOUPPER "${var}" VAR)
-    get_property(${var} TARGET ${name} PROPERTY _EP_${VAR})
-    if(NOT ${var})
+    get_property(is_set TARGET ${name} PROPERTY _EP_${VAR} SET)
+    if(NOT is_set)
       message(FATAL_ERROR "External project \"${name}\" has no ${var}")
     endif()
+    get_property(${var} TARGET ${name} PROPERTY _EP_${VAR})
     set(${var} "${${var}}" PARENT_SCOPE)
   endforeach()
 endfunction()
@@ -1332,16 +1365,16 @@ endif()
     foreach(arg IN LISTS command)
       if("x${arg}" STREQUAL "xCOMMAND")
         if(NOT "x${cmd}" STREQUAL "x")
-          set(code "${code}set(command \"${cmd}\")${code_execute_process}")
+          string(APPEND code "set(command \"${cmd}\")${code_execute_process}")
         endif()
         set(cmd "")
         set(sep "")
       else()
-        set(cmd "${cmd}${sep}${arg}")
+        string(APPEND cmd "${sep}${arg}")
         set(sep ";")
       endif()
     endforeach()
-    set(code "${code}set(command \"${cmd}\")${code_execute_process}")
+    string(APPEND code "set(command \"${cmd}\")${code_execute_process}")
     file(GENERATE OUTPUT "${stamp_dir}/${name}-${step}-$<CONFIG>-impl.cmake" CONTENT "${code}")
     set(command ${CMAKE_COMMAND} "-Dmake=\${make}" "-Dconfig=\${config}" -P ${stamp_dir}/${name}-${step}-$<CONFIG>-impl.cmake)
   endif()
@@ -1667,7 +1700,7 @@ function(_ep_add_download_command name)
   get_property(fname TARGET ${name} PROPERTY _EP_DOWNLOAD_NAME)
 
   # TODO: Perhaps file:// should be copied to download dir before extraction.
-  string(REGEX REPLACE "^file://" "" url "${url}")
+  string(REGEX REPLACE "file://" "" url "${url}")
 
   set(depends)
   set(comment)
@@ -1861,6 +1894,19 @@ function(_ep_add_download_command name)
       @ONLY
       )
     list(APPEND depends ${stamp_dir}/${name}-urlinfo.txt)
+
+    list(LENGTH url url_list_length)
+    if(NOT "${url_list_length}" STREQUAL "1")
+      foreach(entry ${url})
+        if(NOT "${entry}" MATCHES "^[a-z]+://")
+          message(FATAL_ERROR "At least one entry of URL is a path (invalid in a list)")
+        endif()
+      endforeach()
+      if("x${fname}" STREQUAL "x")
+        list(GET url 0 fname)
+      endif()
+    endif()
+
     if(IS_DIRECTORY "${url}")
       get_filename_component(abs_dir "${url}" ABSOLUTE)
       set(comment "Performing download step (DIR copy) for '${name}'")
@@ -1871,16 +1917,19 @@ function(_ep_add_download_command name)
       if("${url}" MATCHES "^[a-z]+://")
         # TODO: Should download and extraction be different steps?
         if("x${fname}" STREQUAL "x")
-          string(REGEX MATCH "[^/\\?]*$" fname "${url}")
+          set(fname "${url}")
         endif()
-        if(NOT "${fname}" MATCHES "(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
-          string(REGEX MATCH "([^/\\?]+(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip))/.*$" match_result "${url}")
+        if("${fname}" MATCHES [[([^/\?#]+(\.|=)(7z|tar|tar\.bz2|tar\.gz|tar\.xz|tbz2|tgz|txz|zip))([/?#].*)?$]])
           set(fname "${CMAKE_MATCH_1}")
-        endif()
-        if (no_extract)
-          get_filename_component(fname "${url}" NAME)
-        elseif(NOT "${fname}" MATCHES "(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
-          message(FATAL_ERROR "Could not extract tarball filename from url:\n  ${url}")
+        elseif(no_extract)
+          get_filename_component(fname "${fname}" NAME)
+        else()
+          # Fall back to a default file name.  The actual file name does not
+          # matter because it is used only internally and our extraction tool
+          # inspects the file content directly.  If it turns out the wrong URL
+          # was given that will be revealed during the build which is an easier
+          # place for users to diagnose than an error here anyway.
+          set(fname "archive.tar")
         endif()
         string(REPLACE ";" "-" fname "${fname}")
         set(file ${download_dir}/${fname})
@@ -1888,8 +1937,11 @@ function(_ep_add_download_command name)
         get_property(no_progress TARGET ${name} PROPERTY _EP_DOWNLOAD_NO_PROGRESS)
         get_property(tls_verify TARGET ${name} PROPERTY _EP_TLS_VERIFY)
         get_property(tls_cainfo TARGET ${name} PROPERTY _EP_TLS_CAINFO)
+        get_property(http_username TARGET ${name} PROPERTY _EP_HTTP_USERNAME)
+        get_property(http_password TARGET ${name} PROPERTY _EP_HTTP_PASSWORD)
+        get_property(http_headers TARGET ${name} PROPERTY _EP_HTTP_HEADER)
         set(download_script "${stamp_dir}/download-${name}.cmake")
-        _ep_write_downloadfile_script("${download_script}" "${url}" "${file}" "${timeout}" "${no_progress}" "${hash}" "${tls_verify}" "${tls_cainfo}")
+        _ep_write_downloadfile_script("${download_script}" "${url}" "${file}" "${timeout}" "${no_progress}" "${hash}" "${tls_verify}" "${tls_cainfo}" "${http_username}:${http_password}" "${http_headers}")
         set(cmd ${CMAKE_COMMAND} -P "${download_script}"
           COMMAND)
         if (no_extract)
@@ -2131,7 +2183,7 @@ endfunction()
 
 # TODO: Make sure external projects use the proper compiler
 function(_ep_add_configure_command name)
-  ExternalProject_Get_Property(${name} source_dir binary_dir tmp_dir)
+  ExternalProject_Get_Property(${name} source_dir source_subdir binary_dir tmp_dir)
 
   # Depend on other external projects (file-level).
   set(file_deps)
@@ -2209,12 +2261,12 @@ function(_ep_add_configure_command name)
       endif()
     endif()
 
-    list(APPEND cmd "${source_dir}")
+    list(APPEND cmd "${source_dir}${source_subdir}")
   endif()
 
   # If anything about the configure command changes, (command itself, cmake
   # used, cmake args or cmake generator) then re-run the configure step.
-  # Fixes issue http://public.kitware.com/Bug/view.php?id=10258
+  # Fixes issue https://gitlab.kitware.com/cmake/cmake/issues/10258
   #
   if(NOT EXISTS ${tmp_dir}/${name}-cfgcmd.txt.in)
     file(WRITE ${tmp_dir}/${name}-cfgcmd.txt.in "cmd='\@cmd\@'\n")
diff --git a/Modules/FLTKCompatibility.cmake b/Modules/FLTKCompatibility.cmake
index 58c52da..e91531f 100644
--- a/Modules/FLTKCompatibility.cmake
+++ b/Modules/FLTKCompatibility.cmake
@@ -1,15 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(CheckIncludeFile)
diff --git a/Modules/FeatureSummary.cmake b/Modules/FeatureSummary.cmake
index dc31086..88bc1c8 100644
--- a/Modules/FeatureSummary.cmake
+++ b/Modules/FeatureSummary.cmake
@@ -1,360 +1,32 @@
-#.rst:
-# FeatureSummary
-# --------------
-#
-# Macros for generating a summary of enabled/disabled features
-#
-#
-#
-# This module provides the macros feature_summary(),
-# set_package_properties() and add_feature_info().  For compatibility it
-# also still provides set_package_info(), set_feature_info(),
-# print_enabled_features() and print_disabled_features().
-#
-# These macros can be used to generate a summary of enabled and disabled
-# packages and/or feature for a build tree:
-#
-# ::
-#
-#     -- The following OPTIONAL packages have been found:
-#     LibXml2 (required version >= 2.4), XML processing lib, <http://xmlsoft.org>
-#        * Enables HTML-import in MyWordProcessor
-#        * Enables odt-export in MyWordProcessor
-#     PNG , A PNG image library. , <http://www.libpng.org/pub/png/>
-#        * Enables saving screenshots
-#     -- The following OPTIONAL packages have not been found:
-#     Lua51 , The Lua scripting language. , <http://www.lua.org>
-#        * Enables macros in MyWordProcessor
-#     Foo , Foo provides cool stuff.
-#
-#
-#
-#
-#
-# ::
-#
-#     FEATURE_SUMMARY( [FILENAME <file>]
-#                      [APPEND]
-#                      [VAR <variable_name>]
-#                      [INCLUDE_QUIET_PACKAGES]
-#                      [FATAL_ON_MISSING_REQUIRED_PACKAGES]
-#                      [DESCRIPTION "Found packages:"]
-#                      WHAT (ALL | PACKAGES_FOUND | PACKAGES_NOT_FOUND
-#                           | ENABLED_FEATURES | DISABLED_FEATURES)
-#                    )
-#
-#
-#
-# The FEATURE_SUMMARY() macro can be used to print information about
-# enabled or disabled packages or features of a project.  By default,
-# only the names of the features/packages will be printed and their
-# required version when one was specified.  Use SET_PACKAGE_PROPERTIES()
-# to add more useful information, like e.g.  a download URL for the
-# respective package or their purpose in the project.
-#
-# The WHAT option is the only mandatory option.  Here you specify what
-# information will be printed:
-#
-# ``ALL``
-#  print everything
-# ``ENABLED_FEATURES``
-#  the list of all features which are enabled
-# ``DISABLED_FEATURES``
-#  the list of all features which are disabled
-# ``PACKAGES_FOUND``
-#  the list of all packages which have been found
-# ``PACKAGES_NOT_FOUND``
-#  the list of all packages which have not been found
-# ``OPTIONAL_PACKAGES_FOUND``
-#  only those packages which have been found which have the type OPTIONAL
-# ``OPTIONAL_PACKAGES_NOT_FOUND``
-#  only those packages which have not been found which have the type OPTIONAL
-# ``RECOMMENDED_PACKAGES_FOUND``
-#  only those packages which have been found which have the type RECOMMENDED
-# ``RECOMMENDED_PACKAGES_NOT_FOUND``
-#  only those packages which have not been found which have the type RECOMMENDED
-# ``REQUIRED_PACKAGES_FOUND``
-#  only those packages which have been found which have the type REQUIRED
-# ``REQUIRED_PACKAGES_NOT_FOUND``
-#  only those packages which have not been found which have the type REQUIRED
-# ``RUNTIME_PACKAGES_FOUND``
-#  only those packages which have been found which have the type RUNTIME
-# ``RUNTIME_PACKAGES_NOT_FOUND``
-#  only those packages which have not been found which have the type RUNTIME
-#
-# With the exception of the ``ALL`` value, these values can be combined
-# in order to customize the output. For example:
-#
-# ::
-#
-#    feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES)
-#
-#
-#
-# If a FILENAME is given, the information is printed into this file.  If
-# APPEND is used, it is appended to this file, otherwise the file is
-# overwritten if it already existed.  If the VAR option is used, the
-# information is "printed" into the specified variable.  If FILENAME is
-# not used, the information is printed to the terminal.  Using the
-# DESCRIPTION option a description or headline can be set which will be
-# printed above the actual content.  If INCLUDE_QUIET_PACKAGES is given,
-# packages which have been searched with find_package(...  QUIET) will
-# also be listed.  By default they are skipped.  If
-# FATAL_ON_MISSING_REQUIRED_PACKAGES is given, CMake will abort if a
-# package which is marked as REQUIRED has not been found.
-#
-# Example 1, append everything to a file:
-#
-# ::
-#
-#    feature_summary(WHAT ALL
-#                    FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)
-#
-#
-#
-# Example 2, print the enabled features into the variable
-# enabledFeaturesText, including QUIET packages:
-#
-# ::
-#
-#    feature_summary(WHAT ENABLED_FEATURES
-#                    INCLUDE_QUIET_PACKAGES
-#                    DESCRIPTION "Enabled Features:"
-#                    VAR enabledFeaturesText)
-#    message(STATUS "${enabledFeaturesText}")
-#
-#
-#
-#
-#
-# ::
-#
-#     SET_PACKAGE_PROPERTIES(<name> PROPERTIES
-#                            [ URL <url> ]
-#                            [ DESCRIPTION <description> ]
-#                            [ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
-#                            [ PURPOSE <purpose> ]
-#                           )
-#
-#
-#
-# Use this macro to set up information about the named package, which
-# can then be displayed via FEATURE_SUMMARY().  This can be done either
-# directly in the Find-module or in the project which uses the module
-# after the find_package() call.  The features for which information can
-# be set are added automatically by the find_package() command.
-#
-# URL: this should be the homepage of the package, or something similar.
-# Ideally this is set already directly in the Find-module.
-#
-# DESCRIPTION: A short description what that package is, at most one
-# sentence.  Ideally this is set already directly in the Find-module.
-#
-# TYPE: What type of dependency has the using project on that package.
-# Default is OPTIONAL.  In this case it is a package which can be used
-# by the project when available at buildtime, but it also work without.
-# RECOMMENDED is similar to OPTIONAL, i.e.  the project will build if
-# the package is not present, but the functionality of the resulting
-# binaries will be severly limited.  If a REQUIRED package is not
-# available at buildtime, the project may not even build.  This can be
-# combined with the FATAL_ON_MISSING_REQUIRED_PACKAGES argument for
-# feature_summary().  Last, a RUNTIME package is a package which is
-# actually not used at all during the build, but which is required for
-# actually running the resulting binaries.  So if such a package is
-# missing, the project can still be built, but it may not work later on.
-# If set_package_properties() is called multiple times for the same
-# package with different TYPEs, the TYPE is only changed to higher TYPEs
-# ( RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED ), lower TYPEs are
-# ignored.  The TYPE property is project-specific, so it cannot be set
-# by the Find-module, but must be set in the project.
-#
-# PURPOSE: This describes which features this package enables in the
-# project, i.e.  it tells the user what functionality he gets in the
-# resulting binaries.  If set_package_properties() is called multiple
-# times for a package, all PURPOSE properties are appended to a list of
-# purposes of the package in the project.  As the TYPE property, also
-# the PURPOSE property is project-specific, so it cannot be set by the
-# Find-module, but must be set in the project.
-#
-#
-#
-# Example for setting the info for a package:
-#
-# ::
-#
-#    find_package(LibXml2)
-#    set_package_properties(LibXml2 PROPERTIES
-#                           DESCRIPTION "A XML processing library."
-#                           URL "http://xmlsoft.org/")
-#
-#
-#
-# ::
-#
-#    set_package_properties(LibXml2 PROPERTIES
-#                           TYPE RECOMMENDED
-#                           PURPOSE "Enables HTML-import in MyWordProcessor")
-#    ...
-#    set_package_properties(LibXml2 PROPERTIES
-#                           TYPE OPTIONAL
-#                           PURPOSE "Enables odt-export in MyWordProcessor")
-#
-#
-#
-# ::
-#
-#    find_package(DBUS)
-#    set_package_properties(DBUS PROPERTIES
-#      TYPE RUNTIME
-#      PURPOSE "Necessary to disable the screensaver during a presentation" )
-#
-#
-#
-# ::
-#
-#     ADD_FEATURE_INFO(<name> <enabled> <description>)
-#
-# Use this macro to add information about a feature with the given
-# <name>.  <enabled> contains whether this feature is enabled or not,
-# <description> is a text describing the feature.  The information can
-# be displayed using feature_summary() for ENABLED_FEATURES and
-# DISABLED_FEATURES respectively.
-#
-# Example for setting the info for a feature:
-#
-# ::
-#
-#    option(WITH_FOO "Help for foo" ON)
-#    add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")
-#
-#
-#
-#
-#
-# The following macros are provided for compatibility with previous
-# CMake versions:
-#
-# ::
-#
-#     SET_PACKAGE_INFO(<name> <description> [<url> [<purpose>] ] )
-#
-# Use this macro to set up information about the named package, which
-# can then be displayed via FEATURE_SUMMARY().  This can be done either
-# directly in the Find-module or in the project which uses the module
-# after the find_package() call.  The features for which information can
-# be set are added automatically by the find_package() command.
-#
-# ::
-#
-#     PRINT_ENABLED_FEATURES()
-#
-# Does the same as FEATURE_SUMMARY(WHAT ENABLED_FEATURES DESCRIPTION
-# "Enabled features:")
-#
-# ::
-#
-#     PRINT_DISABLED_FEATURES()
-#
-# Does the same as FEATURE_SUMMARY(WHAT DISABLED_FEATURES DESCRIPTION
-# "Disabled features:")
-#
-# ::
-#
-#     SET_FEATURE_INFO(<name> <description> [<url>] )
-#
-# Does the same as SET_PACKAGE_INFO(<name> <description> <url> )
-
-#=============================================================================
-# Copyright 2007-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-include("${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake")
-
-
-function(ADD_FEATURE_INFO _name _enabled _desc)
-  if (${_enabled})
-    set_property(GLOBAL APPEND PROPERTY ENABLED_FEATURES "${_name}")
-  else ()
-    set_property(GLOBAL APPEND PROPERTY DISABLED_FEATURES "${_name}")
-  endif ()
-
-  set_property(GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION "${_desc}" )
-endfunction()
-
-
-
-function(SET_PACKAGE_PROPERTIES _name _props)
-  if(NOT "${_props}" STREQUAL "PROPERTIES")
-    message(FATAL_ERROR "PROPERTIES keyword is missing in SET_PACKAGE_PROPERTIES() call.")
-  endif()
-
-  set(options ) # none
-  set(oneValueArgs DESCRIPTION URL TYPE PURPOSE )
-  set(multiValueArgs ) # none
+#[=======================================================================[.rst:
+FeatureSummary
+--------------
 
-  CMAKE_PARSE_ARGUMENTS(_SPP "${options}" "${oneValueArgs}" "${multiValueArgs}"  ${ARGN})
+Functions for generating a summary of enabled/disabled features.
 
-  if(_SPP_UNPARSED_ARGUMENTS)
-    message(FATAL_ERROR "Unknown keywords given to SET_PACKAGE_PROPERTIES(): \"${_SPP_UNPARSED_ARGUMENTS}\"")
-  endif()
+These functions can be used to generate a summary of enabled and disabled
+packages and/or feature for a build tree such as::
 
-  if(_SPP_DESCRIPTION)
-    get_property(_info  GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION)
-    if(_info AND NOT "${_info}" STREQUAL "${_SPP_DESCRIPTION}")
-      message(STATUS "Warning: Property DESCRIPTION for package ${_name} already set to \"${_info}\", overriding it with \"${_SPP_DESCRIPTION}\"")
-    endif()
-
-    set_property(GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION "${_SPP_DESCRIPTION}" )
-  endif()
+    -- The following OPTIONAL packages have been found:
+    LibXml2 (required version >= 2.4), XML processing lib, <http://xmlsoft.org>
+       * Enables HTML-import in MyWordProcessor
+       * Enables odt-export in MyWordProcessor
+    PNG , A PNG image library. , <http://www.libpng.org/pub/png/>
+       * Enables saving screenshots
+    -- The following OPTIONAL packages have not been found:
+    Lua51 , The Lua scripting language. , <http://www.lua.org>
+       * Enables macros in MyWordProcessor
+    Foo , Foo provides cool stuff.
 
+Functions
+^^^^^^^^^
 
-  if(_SPP_URL)
-    get_property(_info  GLOBAL PROPERTY _CMAKE_${_name}_URL)
-    if(_info AND NOT "${_info}" STREQUAL "${_SPP_URL}")
-      message(STATUS "Warning: Property URL already set to \"${_info}\", overriding it with \"${_SPP_URL}\"")
-    endif()
-
-    set_property(GLOBAL PROPERTY _CMAKE_${_name}_URL "${_SPP_URL}" )
-  endif()
-
-
-  # handle the PURPOSE: use APPEND, since there can be multiple purposes for one package inside a project
-  if(_SPP_PURPOSE)
-    set_property(GLOBAL APPEND PROPERTY _CMAKE_${_name}_PURPOSE "${_SPP_PURPOSE}" )
-  endif()
-
-  # handle the TYPE
-  if(NOT _SPP_TYPE)
-    set(_SPP_TYPE OPTIONAL)
-  endif()
-
-  # List the supported types, according to their priority
-  set(validTypes "RUNTIME" "OPTIONAL" "RECOMMENDED" "REQUIRED" )
-  list(FIND validTypes ${_SPP_TYPE} _typeIndexInList)
-  if("${_typeIndexInList}" STREQUAL "-1" )
-    message(FATAL_ERROR "Bad package property type ${_SPP_TYPE} used in SET_PACKAGE_PROPERTIES(). "
-                        "Valid types are OPTIONAL, RECOMMENDED, REQUIRED and RUNTIME." )
-  endif()
-
-  get_property(_previousType  GLOBAL PROPERTY _CMAKE_${_name}_TYPE)
-  list(FIND validTypes "${_previousType}" _prevTypeIndexInList)
-
-  # make sure a previously set TYPE is not overridden with a lower new TYPE:
-  if("${_typeIndexInList}" GREATER "${_prevTypeIndexInList}")
-    set_property(GLOBAL PROPERTY _CMAKE_${_name}_TYPE "${_SPP_TYPE}" )
-  endif()
-
-endfunction()
+#]=======================================================================]
 
+include("${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake")
 
 
 function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
@@ -411,23 +83,23 @@ function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
 
       if(includeThisOne)
 
-        set(_currentFeatureText "${_currentFeatureText}\n * ${_currentFeature}")
+        string(APPEND _currentFeatureText "\n * ${_currentFeature}")
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_REQUIRED_VERSION)
         if(_info)
-          set(_currentFeatureText "${_currentFeatureText} (required version ${_info})")
+          string(APPEND _currentFeatureText " (required version ${_info})")
         endif()
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_DESCRIPTION)
         if(_info)
-          set(_currentFeatureText "${_currentFeatureText} , ${_info}")
+          string(APPEND _currentFeatureText " , ${_info}")
         endif()
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_URL)
         if(_info)
-          set(_currentFeatureText "${_currentFeatureText} , <${_info}>")
+          string(APPEND _currentFeatureText " , <${_info}>")
         endif()
 
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_PURPOSE)
         foreach(_purpose ${_info})
-          set(_currentFeatureText "${_currentFeatureText}\n   ${_purpose}")
+          string(APPEND _currentFeatureText "\n   ${_purpose}")
         endforeach()
 
       endif()
@@ -439,6 +111,97 @@ function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
 endfunction()
 
 
+#[=======================================================================[.rst:
+.. command:: feature_summary
+
+  ::
+
+    feature_summary( [FILENAME <file>]
+                     [APPEND]
+                     [VAR <variable_name>]
+                     [INCLUDE_QUIET_PACKAGES]
+                     [FATAL_ON_MISSING_REQUIRED_PACKAGES]
+                     [DESCRIPTION "Found packages:"]
+                     WHAT (ALL | PACKAGES_FOUND | PACKAGES_NOT_FOUND
+                          | ENABLED_FEATURES | DISABLED_FEATURES)
+                   )
+
+  The ``feature_summary()`` macro can be used to print information about
+  enabled or disabled packages or features of a project.  By default,
+  only the names of the features/packages will be printed and their
+  required version when one was specified.  Use ``set_package_properties()``
+  to add more useful information, like e.g.  a download URL for the
+  respective package or their purpose in the project.
+
+  The ``WHAT`` option is the only mandatory option.  Here you specify what
+  information will be printed:
+
+  ``ALL``
+   print everything
+  ``ENABLED_FEATURES``
+   the list of all features which are enabled
+  ``DISABLED_FEATURES``
+   the list of all features which are disabled
+  ``PACKAGES_FOUND``
+   the list of all packages which have been found
+  ``PACKAGES_NOT_FOUND``
+   the list of all packages which have not been found
+  ``OPTIONAL_PACKAGES_FOUND``
+   only those packages which have been found which have the type OPTIONAL
+  ``OPTIONAL_PACKAGES_NOT_FOUND``
+   only those packages which have not been found which have the type OPTIONAL
+  ``RECOMMENDED_PACKAGES_FOUND``
+   only those packages which have been found which have the type RECOMMENDED
+  ``RECOMMENDED_PACKAGES_NOT_FOUND``
+   only those packages which have not been found which have the type RECOMMENDED
+  ``REQUIRED_PACKAGES_FOUND``
+   only those packages which have been found which have the type REQUIRED
+  ``REQUIRED_PACKAGES_NOT_FOUND``
+   only those packages which have not been found which have the type REQUIRED
+  ``RUNTIME_PACKAGES_FOUND``
+   only those packages which have been found which have the type RUNTIME
+  ``RUNTIME_PACKAGES_NOT_FOUND``
+   only those packages which have not been found which have the type RUNTIME
+
+  With the exception of the ``ALL`` value, these values can be combined
+  in order to customize the output. For example:
+
+  .. code-block:: cmake
+
+    feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES)
+
+  If a ``FILENAME`` is given, the information is printed into this file.  If
+  ``APPEND`` is used, it is appended to this file, otherwise the file is
+  overwritten if it already existed.  If the VAR option is used, the
+  information is "printed" into the specified variable.  If ``FILENAME`` is
+  not used, the information is printed to the terminal.  Using the
+  ``DESCRIPTION`` option a description or headline can be set which will be
+  printed above the actual content.  If ``INCLUDE_QUIET_PACKAGES`` is given,
+  packages which have been searched with ``find_package(... QUIET)`` will
+  also be listed.  By default they are skipped.  If
+  ``FATAL_ON_MISSING_REQUIRED_PACKAGES`` is given, CMake will abort if a
+  package which is marked as ``REQUIRED`` has not been found.
+
+  Example 1, append everything to a file:
+
+  .. code-block:: cmake
+
+   include(FeatureSummary)
+   feature_summary(WHAT ALL
+                   FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)
+
+  Example 2, print the enabled features into the variable
+  enabledFeaturesText, including QUIET packages:
+
+  .. code-block:: cmake
+
+   include(FeatureSummary)
+   feature_summary(WHAT ENABLED_FEATURES
+                   INCLUDE_QUIET_PACKAGES
+                   DESCRIPTION "Enabled Features:"
+                   VAR enabledFeaturesText)
+   message(STATUS "${enabledFeaturesText}")
+#]=======================================================================]
 
 function(FEATURE_SUMMARY)
 # CMAKE_PARSE_ARGUMENTS(<prefix> <options> <one_value_keywords> <multi_value_keywords> args...)
@@ -527,7 +290,7 @@ function(FEATURE_SUMMARY)
       set(_tmp)
       _FS_GET_FEATURE_SUMMARY( ${part} _tmp ${_FS_INCLUDE_QUIET_PACKAGES})
       if(_tmp)
-        set(_fullText "${_fullText}\n-- ${title_${part}}\n${_tmp}\n")
+        string(APPEND _fullText "\n-- ${title_${part}}\n${_tmp}\n")
         if("${part}" STREQUAL "REQUIRED_PACKAGES_NOT_FOUND")
           set(requiredPackagesNotFound TRUE)
         endif()
@@ -558,9 +321,198 @@ function(FEATURE_SUMMARY)
 
 endfunction()
 
+#[=======================================================================[.rst:
+.. command:: set_package_properties
+
+  ::
+
+    set_package_properties(<name> PROPERTIES
+                           [ URL <url> ]
+                           [ DESCRIPTION <description> ]
+                           [ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
+                           [ PURPOSE <purpose> ]
+                          )
+
+  Use this macro to set up information about the named package, which
+  can then be displayed via FEATURE_SUMMARY().  This can be done either
+  directly in the Find-module or in the project which uses the module
+  after the find_package() call.  The features for which information can
+  be set are added automatically by the find_package() command.
+
+  ``URL <url>``
+    This should be the homepage of the package, or something similar.
+    Ideally this is set already directly in the Find-module.
+
+  ``DESCRIPTION <description>``
+    A short description what that package is, at most one sentence.
+    Ideally this is set already directly in the Find-module.
+
+  ``TYPE <type>``
+    What type of dependency has the using project on that package.
+    Default is ``OPTIONAL``.  In this case it is a package which can be used
+    by the project when available at buildtime, but it also work without.
+    ``RECOMMENDED`` is similar to ``OPTIONAL``, i.e.  the project will build if
+    the package is not present, but the functionality of the resulting
+    binaries will be severly limited.  If a ``REQUIRED`` package is not
+    available at buildtime, the project may not even build.  This can be
+    combined with the ``FATAL_ON_MISSING_REQUIRED_PACKAGES`` argument for
+    ``feature_summary()``.  Last, a ``RUNTIME`` package is a package which is
+    actually not used at all during the build, but which is required for
+    actually running the resulting binaries.  So if such a package is
+    missing, the project can still be built, but it may not work later on.
+    If ``set_package_properties()`` is called multiple times for the same
+    package with different TYPEs, the ``TYPE`` is only changed to higher
+    TYPEs (``RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED``), lower TYPEs are
+    ignored.  The ``TYPE`` property is project-specific, so it cannot be set
+    by the Find-module, but must be set in the project.
+
+
+  ``PURPOSE <purpose>``
+    This describes which features this package enables in the
+    project, i.e.  it tells the user what functionality he gets in the
+    resulting binaries.  If set_package_properties() is called multiple
+    times for a package, all PURPOSE properties are appended to a list of
+    purposes of the package in the project.  As the TYPE property, also
+    the PURPOSE property is project-specific, so it cannot be set by the
+    Find-module, but must be set in the project.
+
+  Example for setting the info for a package:
+
+  .. code-block:: cmake
+
+    find_package(LibXml2)
+    set_package_properties(LibXml2 PROPERTIES
+                           DESCRIPTION "A XML processing library."
+                           URL "http://xmlsoft.org/")
+    # or
+    set_package_properties(LibXml2 PROPERTIES
+                           TYPE RECOMMENDED
+                           PURPOSE "Enables HTML-import in MyWordProcessor")
+    # or
+    set_package_properties(LibXml2 PROPERTIES
+                           TYPE OPTIONAL
+                           PURPOSE "Enables odt-export in MyWordProcessor")
+
+    find_package(DBUS)
+    set_package_properties(DBUS PROPERTIES
+      TYPE RUNTIME
+      PURPOSE "Necessary to disable the screensaver during a presentation")
+#]=======================================================================]
+function(SET_PACKAGE_PROPERTIES _name _props)
+  if(NOT "${_props}" STREQUAL "PROPERTIES")
+    message(FATAL_ERROR "PROPERTIES keyword is missing in SET_PACKAGE_PROPERTIES() call.")
+  endif()
+
+  set(options ) # none
+  set(oneValueArgs DESCRIPTION URL TYPE PURPOSE )
+  set(multiValueArgs ) # none
+
+  CMAKE_PARSE_ARGUMENTS(_SPP "${options}" "${oneValueArgs}" "${multiValueArgs}"  ${ARGN})
+
+  if(_SPP_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to SET_PACKAGE_PROPERTIES(): \"${_SPP_UNPARSED_ARGUMENTS}\"")
+  endif()
+
+  if(_SPP_DESCRIPTION)
+    get_property(_info  GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION)
+    if(_info AND NOT "${_info}" STREQUAL "${_SPP_DESCRIPTION}")
+      message(STATUS "Warning: Property DESCRIPTION for package ${_name} already set to \"${_info}\", overriding it with \"${_SPP_DESCRIPTION}\"")
+    endif()
+
+    set_property(GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION "${_SPP_DESCRIPTION}" )
+  endif()
+
+
+  if(_SPP_URL)
+    get_property(_info  GLOBAL PROPERTY _CMAKE_${_name}_URL)
+    if(_info AND NOT "${_info}" STREQUAL "${_SPP_URL}")
+      message(STATUS "Warning: Property URL already set to \"${_info}\", overriding it with \"${_SPP_URL}\"")
+    endif()
+
+    set_property(GLOBAL PROPERTY _CMAKE_${_name}_URL "${_SPP_URL}" )
+  endif()
+
+
+  # handle the PURPOSE: use APPEND, since there can be multiple purposes for one package inside a project
+  if(_SPP_PURPOSE)
+    set_property(GLOBAL APPEND PROPERTY _CMAKE_${_name}_PURPOSE "${_SPP_PURPOSE}" )
+  endif()
+
+  # handle the TYPE
+  if(NOT _SPP_TYPE)
+    set(_SPP_TYPE OPTIONAL)
+  endif()
+
+  # List the supported types, according to their priority
+  set(validTypes "RUNTIME" "OPTIONAL" "RECOMMENDED" "REQUIRED" )
+  list(FIND validTypes ${_SPP_TYPE} _typeIndexInList)
+  if("${_typeIndexInList}" STREQUAL "-1" )
+    message(FATAL_ERROR "Bad package property type ${_SPP_TYPE} used in SET_PACKAGE_PROPERTIES(). "
+                        "Valid types are OPTIONAL, RECOMMENDED, REQUIRED and RUNTIME." )
+  endif()
+
+  get_property(_previousType  GLOBAL PROPERTY _CMAKE_${_name}_TYPE)
+  list(FIND validTypes "${_previousType}" _prevTypeIndexInList)
+
+  # make sure a previously set TYPE is not overridden with a lower new TYPE:
+  if("${_typeIndexInList}" GREATER "${_prevTypeIndexInList}")
+    set_property(GLOBAL PROPERTY _CMAKE_${_name}_TYPE "${_SPP_TYPE}" )
+  endif()
+
+endfunction()
+
+#[=======================================================================[.rst:
+.. command:: add_feature_info
+
+  ::
+
+    add_feature_info(<name> <enabled> <description>)
+
+  Use this macro to add information about a feature with the given ``<name>``.
+  ``<enabled>`` contains whether this feature is enabled or not.
+  ``<description>`` is a text describing the feature.  The information can
+  be displayed using ``feature_summary()`` for ``ENABLED_FEATURES`` and
+  ``DISABLED_FEATURES`` respectively.
+
+  Example for setting the info for a feature:
+
+  .. code-block:: cmake
+
+     option(WITH_FOO "Help for foo" ON)
+     add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")
+#]=======================================================================]
+function(ADD_FEATURE_INFO _name _enabled _desc)
+  if (${_enabled})
+    set_property(GLOBAL APPEND PROPERTY ENABLED_FEATURES "${_name}")
+  else ()
+    set_property(GLOBAL APPEND PROPERTY DISABLED_FEATURES "${_name}")
+  endif ()
+
+  set_property(GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION "${_desc}" )
+endfunction()
+
 
 # The stuff below is only kept for compatibility
 
+#[=======================================================================[.rst:
+Legacy Macros
+^^^^^^^^^^^^^
+
+The following macros are provided for compatibility with previous
+CMake versions:
+
+.. command:: set_package_info
+
+  ::
+
+    set_package_info(<name> <description> [ <url> [<purpose>] ])
+
+  Use this macro to set up information about the named package, which
+  can then be displayed via ``feature_summary()``.  This can be done either
+  directly in the Find-module or in the project which uses the module
+  after the :command:`find_package` call.  The features for which information
+  can be set are added automatically by the ``find_package()`` command.
+#]=======================================================================]
 function(SET_PACKAGE_INFO _name _desc)
   unset(_url)
   unset(_purpose)
@@ -579,20 +531,51 @@ function(SET_PACKAGE_INFO _name _desc)
   endif()
 endfunction()
 
+#[=======================================================================[.rst:
+.. command:: set_feature_info
+
+  ::
 
+    set_feature_info(<name> <description> [<url>])
 
+  Does the same as::
+
+    set_package_info(<name> <description> <url>)
+#]=======================================================================]
 function(SET_FEATURE_INFO)
   SET_PACKAGE_INFO(${ARGN})
 endfunction()
 
+#[=======================================================================[.rst:
+.. command:: print_enabled_features
+
+  ::
 
+    print_enabled_features()
 
+  Does the same as
+
+  .. code-block:: cmake
+
+    feature_summary(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")
+#]=======================================================================]
 function(PRINT_ENABLED_FEATURES)
   FEATURE_SUMMARY(WHAT ENABLED_FEATURES  DESCRIPTION "Enabled features:")
 endfunction()
 
+#[=======================================================================[.rst:
+.. command:: print_disabled_features
+
+  ::
+
+    print_disabled_features()
+
+  Does the same as
 
+  .. code-block:: cmake
 
+    feature_summary(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")
+#]=======================================================================]
 function(PRINT_DISABLED_FEATURES)
   FEATURE_SUMMARY(WHAT DISABLED_FEATURES  DESCRIPTION "Disabled features:")
 endfunction()
diff --git a/Modules/FindALSA.cmake b/Modules/FindALSA.cmake
index 5c30eb9..d0ffa03 100644
--- a/Modules/FindALSA.cmake
+++ b/Modules/FindALSA.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindALSA
 # --------
@@ -21,20 +24,6 @@
 #      ALSA_LIBRARY     - the asound library
 #      ALSA_VERSION_STRING - the version of alsa found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2009-2011 Kitware, Inc.
-# Copyright 2009-2011 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(ALSA_INCLUDE_DIR NAMES alsa/asoundlib.h
           DOC "The ALSA (asound) include directory"
 )
diff --git a/Modules/FindASPELL.cmake b/Modules/FindASPELL.cmake
index 2a3f228..8f2b007 100644
--- a/Modules/FindASPELL.cmake
+++ b/Modules/FindASPELL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindASPELL
 # ----------
@@ -14,20 +17,6 @@
 #   ASPELL_LIBRARIES - The libraries needed to use ASPELL
 #   ASPELL_DEFINITIONS - Compiler switches required for using ASPELL
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(ASPELL_INCLUDE_DIR aspell.h )
 
 find_program(ASPELL_EXECUTABLE
diff --git a/Modules/FindAVIFile.cmake b/Modules/FindAVIFile.cmake
index 5661075..38701be 100644
--- a/Modules/FindAVIFile.cmake
+++ b/Modules/FindAVIFile.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindAVIFile
 # -----------
@@ -16,19 +19,6 @@
 #   AVIFILE_DEFINITIONS, definitions to use when compiling
 #   AVIFILE_FOUND, If false, don't try to use AVIFILE
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (UNIX)
 
   find_path(AVIFILE_INCLUDE_DIR avifile.h
diff --git a/Modules/FindArmadillo.cmake b/Modules/FindArmadillo.cmake
index 4549771..fab04c2 100644
--- a/Modules/FindArmadillo.cmake
+++ b/Modules/FindArmadillo.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindArmadillo
 # -------------
@@ -28,20 +31,6 @@
 #   ARMADILLO_VERSION_STRING - version number as a string (ex: "1.0.4")
 #   ARMADILLO_VERSION_NAME - name of the version (ex: "Antipodean Antileech")
 
-#=============================================================================
-# Copyright 2011 Clement Creusot <creusot at cs.york.ac.uk>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 # UNIX paths are standard, no need to write.
 find_library(ARMADILLO_LIBRARY
   NAMES armadillo
diff --git a/Modules/FindBISON.cmake b/Modules/FindBISON.cmake
index 69293f5..5de7a39 100644
--- a/Modules/FindBISON.cmake
+++ b/Modules/FindBISON.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBISON
 # ---------
@@ -23,7 +26,8 @@
 #   BISON_TARGET(<Name> <YaccInput> <CodeOutput>
 #                [COMPILE_FLAGS <flags>]
 #                [DEFINES_FILE <file>]
-#                [VERBOSE <file>]
+#                [VERBOSE [<file>]]
+#                [REPORT_FILE <file>]
 #                )
 #
 # which will create a custom rule to generate a parser.  ``<YaccInput>`` is
@@ -39,9 +43,14 @@
 # ``DEFINES_FILE <file>``
 #   Specify a non-default header ``<file>`` to be generated by ``bison``.
 #
-# ``VERBOSE <file>``
-#   Tell ``bison`` to write verbose descriptions of the grammar and
-#   parser to the given ``<file>``.
+# ``VERBOSE [<file>]``
+#   Tell ``bison`` to write a report file of the grammar and parser.
+#   If ``<file>`` is given, it specifies path the report file is copied to.
+#   ``[<file>]`` is left for backward compatibility of this module.
+#   Use ``VERBOSE REPORT_FILE <file>``.
+#
+# ``REPORT_FILE <file>``
+#   Specify a non-default report ``<file>``, if generated.
 #
 # The macro defines the following variables:
 #
@@ -58,7 +67,7 @@
 #   The header file generated by bison
 #
 # ``BISON_<Name>_OUTPUTS``
-#   The sources files generated by bison
+#   All files generated by bison including the source, the header and the report
 #
 # ``BISON_<Name>_COMPILE_FLAGS``
 #   Options used in the ``bison`` command line
@@ -72,20 +81,6 @@
 #                DEFINES_FILE ${CMAKE_CURRENT_BINARY_DIR}/parser.h)
 #   add_executable(Foo main.cpp ${BISON_MyParser_OUTPUTS})
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2006 Tristan Carel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(BISON_EXECUTABLE NAMES bison win_bison DOC "path to the bison executable")
 mark_as_advanced(BISON_EXECUTABLE)
 
@@ -120,35 +115,65 @@ if(BISON_EXECUTABLE)
   endif()
 
   # internal macro
-  macro(BISON_TARGET_option_verbose Name BisonOutput filename)
-    list(APPEND BISON_TARGET_cmdopt "--verbose")
-    get_filename_component(BISON_TARGET_output_path "${BisonOutput}" PATH)
-    get_filename_component(BISON_TARGET_output_name "${BisonOutput}" NAME_WE)
-    add_custom_command(OUTPUT ${filename}
-      COMMAND ${CMAKE_COMMAND} -E copy
-      "${BISON_TARGET_output_path}/${BISON_TARGET_output_name}.output"
-      "${filename}"
-      VERBATIM
-      DEPENDS
-      "${BISON_TARGET_output_path}/${BISON_TARGET_output_name}.output"
-      COMMENT "[BISON][${Name}] Copying bison verbose table to ${filename}"
-      WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
-    set(BISON_${Name}_VERBOSE_FILE ${filename})
-    list(APPEND BISON_TARGET_extraoutputs
-      "${BISON_TARGET_output_path}/${BISON_TARGET_output_name}.output")
-  endmacro()
-
-  # internal macro
+  # sets BISON_TARGET_cmdopt
   macro(BISON_TARGET_option_extraopts Options)
+    set(BISON_TARGET_cmdopt "")
     set(BISON_TARGET_extraopts "${Options}")
     separate_arguments(BISON_TARGET_extraopts)
     list(APPEND BISON_TARGET_cmdopt ${BISON_TARGET_extraopts})
   endmacro()
 
   # internal macro
-  macro(BISON_TARGET_option_defines Header)
-    set(BISON_TARGET_output_header "${Header}")
-    list(APPEND BISON_TARGET_cmdopt --defines=${BISON_TARGET_output_header})
+  # sets BISON_TARGET_output_header and BISON_TARGET_cmdopt
+  macro(BISON_TARGET_option_defines BisonOutput Header)
+    if("${Header}" STREQUAL "")
+      # default header path generated by bison (see option -d)
+      string(REGEX REPLACE "^(.*)(\\.[^.]*)$" "\\2" _fileext "${BisonOutput}")
+      string(REPLACE "c" "h" _fileext ${_fileext})
+      string(REGEX REPLACE "^(.*)(\\.[^.]*)$" "\\1${_fileext}"
+          BISON_TARGET_output_header "${BisonOutput}")
+      list(APPEND BISON_TARGET_cmdopt "-d")
+    else()
+      set(BISON_TARGET_output_header "${Header}")
+      list(APPEND BISON_TARGET_cmdopt "--defines=${BISON_TARGET_output_header}")
+    endif()
+  endmacro()
+
+  # internal macro
+  # sets BISON_TARGET_verbose_file and BISON_TARGET_cmdopt
+  macro(BISON_TARGET_option_report_file BisonOutput ReportFile)
+    if("${ReportFile}" STREQUAL "")
+      get_filename_component(BISON_TARGET_output_path "${BisonOutput}" PATH)
+      get_filename_component(BISON_TARGET_output_name "${BisonOutput}" NAME_WE)
+      set(BISON_TARGET_verbose_file
+        "${BISON_TARGET_output_path}/${BISON_TARGET_output_name}.output")
+    else()
+      set(BISON_TARGET_verbose_file "${ReportFile}")
+      list(APPEND BISON_TARGET_cmdopt "--report-file=${BISON_TARGET_verbose_file}")
+    endif()
+  endmacro()
+
+  # internal macro
+  # adds a custom command and sets
+  #   BISON_TARGET_cmdopt, BISON_TARGET_verbose_file, BISON_TARGET_extraoutputs
+  macro(BISON_TARGET_option_verbose Name BisonOutput filename)
+    list(APPEND BISON_TARGET_cmdopt "--verbose")
+    list(APPEND BISON_TARGET_extraoutputs
+      "${BISON_TARGET_verbose_file}")
+    if (NOT "${filename}" STREQUAL "")
+      add_custom_command(OUTPUT ${filename}
+        COMMAND ${CMAKE_COMMAND} -E copy
+        "${BISON_TARGET_verbose_file}"
+        "${filename}"
+        VERBATIM
+        DEPENDS
+        "${BISON_TARGET_verbose_file}"
+        COMMENT "[BISON][${Name}] Copying bison verbose table to ${filename}"
+        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
+      set(BISON_${Name}_VERBOSE_FILE ${filename})
+      list(APPEND BISON_TARGET_extraoutputs
+        "${filename}")
+    endif()
   endmacro()
 
   #============================================================
@@ -156,18 +181,20 @@ if(BISON_EXECUTABLE)
   #============================================================
   #
   macro(BISON_TARGET Name BisonInput BisonOutput)
-    set(BISON_TARGET_output_header "")
-    set(BISON_TARGET_cmdopt "")
     set(BISON_TARGET_outputs "${BisonOutput}")
+    set(BISON_TARGET_extraoutputs "")
 
     # Parsing parameters
-    set(BISON_TARGET_PARAM_OPTIONS)
+    set(BISON_TARGET_PARAM_OPTIONS
+      )
     set(BISON_TARGET_PARAM_ONE_VALUE_KEYWORDS
-      VERBOSE
       COMPILE_FLAGS
       DEFINES_FILE
+      REPORT_FILE
+      )
+    set(BISON_TARGET_PARAM_MULTI_VALUE_KEYWORDS
+      VERBOSE
       )
-    set(BISON_TARGET_PARAM_MULTI_VALUE_KEYWORDS)
     cmake_parse_arguments(
         BISON_TARGET_ARG
         "${BISON_TARGET_PARAM_OPTIONS}"
@@ -178,29 +205,30 @@ if(BISON_EXECUTABLE)
 
     if(NOT "${BISON_TARGET_ARG_UNPARSED_ARGUMENTS}" STREQUAL "")
       message(SEND_ERROR "Usage")
+    elseif("${BISON_TARGET_ARG_VERBOSE}" MATCHES ";")
+      # [VERBOSE [<file>] hack: <file> is non-multi value by usage
+      message(SEND_ERROR "Usage")
     else()
+
+      BISON_TARGET_option_extraopts("${BISON_TARGET_ARG_COMPILE_FLAGS}")
+      BISON_TARGET_option_defines("${BisonOutput}" "${BISON_TARGET_ARG_DEFINES_FILE}")
+      BISON_TARGET_option_report_file("${BisonOutput}" "${BISON_TARGET_ARG_REPORT_FILE}")
       if(NOT "${BISON_TARGET_ARG_VERBOSE}" STREQUAL "")
         BISON_TARGET_option_verbose(${Name} ${BisonOutput} "${BISON_TARGET_ARG_VERBOSE}")
-      endif()
-      if(NOT "${BISON_TARGET_ARG_COMPILE_FLAGS}" STREQUAL "")
-        BISON_TARGET_option_extraopts("${BISON_TARGET_ARG_COMPILE_FLAGS}")
-      endif()
-      if(NOT "${BISON_TARGET_ARG_DEFINES_FILE}" STREQUAL "")
-        BISON_TARGET_option_defines("${BISON_TARGET_ARG_DEFINES_FILE}")
+      else()
+        # [VERBOSE [<file>]] is used with no argument or is not used
+        set(BISON_TARGET_args "${ARGN}")
+        list(FIND BISON_TARGET_args "VERBOSE" BISON_TARGET_args_indexof_verbose)
+        if(${BISON_TARGET_args_indexof_verbose} GREATER -1)
+          # VERBOSE is used without <file>
+          BISON_TARGET_option_verbose(${Name} ${BisonOutput} "")
+        endif()
       endif()
 
-      if("${BISON_TARGET_output_header}" STREQUAL "")
-        # Header's name generated by bison (see option -d)
-        list(APPEND BISON_TARGET_cmdopt "-d")
-        string(REGEX REPLACE "^(.*)(\\.[^.]*)$" "\\2" _fileext "${BisonOutput}")
-        string(REPLACE "c" "h" _fileext ${_fileext})
-        string(REGEX REPLACE "^(.*)(\\.[^.]*)$" "\\1${_fileext}"
-            BISON_TARGET_output_header "${BisonOutput}")
-      endif()
       list(APPEND BISON_TARGET_outputs "${BISON_TARGET_output_header}")
 
       add_custom_command(OUTPUT ${BISON_TARGET_outputs}
-        ${BISON_TARGET_extraoutputs}
+        ${BISON_TARGET_verbose_file}
         COMMAND ${BISON_EXECUTABLE} ${BISON_TARGET_cmdopt} -o ${BisonOutput} ${BisonInput}
         VERBATIM
         DEPENDS ${BisonInput}
@@ -210,7 +238,7 @@ if(BISON_EXECUTABLE)
       # define target variables
       set(BISON_${Name}_DEFINED TRUE)
       set(BISON_${Name}_INPUT ${BisonInput})
-      set(BISON_${Name}_OUTPUTS ${BISON_TARGET_outputs})
+      set(BISON_${Name}_OUTPUTS ${BISON_TARGET_outputs} ${BISON_TARGET_extraoutputs})
       set(BISON_${Name}_COMPILE_FLAGS ${BISON_TARGET_cmdopt})
       set(BISON_${Name}_OUTPUT_SOURCE "${BisonOutput}")
       set(BISON_${Name}_OUTPUT_HEADER "${BISON_TARGET_output_header}")
diff --git a/Modules/FindBLAS.cmake b/Modules/FindBLAS.cmake
index 728494c..853a6b4 100644
--- a/Modules/FindBLAS.cmake
+++ b/Modules/FindBLAS.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBLAS
 # --------
@@ -37,19 +40,6 @@
 # and 64 bit), ACML,ACML_MP,ACML_GPU,Apple, NAS, Generic C/CXX should be
 # enabled to use Intel mkl
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CheckFunctionExists.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CheckFortranFunctionExists.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CMakePushCheckState.cmake)
diff --git a/Modules/FindBZip2.cmake b/Modules/FindBZip2.cmake
index 6af42dd..2d93eba 100644
--- a/Modules/FindBZip2.cmake
+++ b/Modules/FindBZip2.cmake
@@ -1,10 +1,22 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBZip2
 # ---------
 #
 # Try to find BZip2
 #
-# Once done this will define
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines :prop_tgt:`IMPORTED` target ``BZip2::BZip2``, if
+# BZip2 has been found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the following variables:
 #
 # ::
 #
@@ -14,21 +26,6 @@
 #   BZIP2_NEED_PREFIX - this is set if the functions are prefixed with BZ2_
 #   BZIP2_VERSION_STRING - the version of BZip2 found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2006-2012 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(_BZIP2_PATHS PATHS
   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\Bzip2;InstallPath]"
   )
@@ -37,7 +34,7 @@ find_path(BZIP2_INCLUDE_DIR bzlib.h ${_BZIP2_PATHS} PATH_SUFFIXES include)
 
 if (NOT BZIP2_LIBRARIES)
     find_library(BZIP2_LIBRARY_RELEASE NAMES bz2 bzip2 ${_BZIP2_PATHS} PATH_SUFFIXES lib)
-    find_library(BZIP2_LIBRARY_DEBUG NAMES bzip2d ${_BZIP2_PATHS} PATH_SUFFIXES lib)
+    find_library(BZIP2_LIBRARY_DEBUG NAMES bz2d bzip2d ${_BZIP2_PATHS} PATH_SUFFIXES lib)
 
     include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
     SELECT_LIBRARY_CONFIGURATIONS(BZIP2)
@@ -64,6 +61,31 @@ if (BZIP2_FOUND)
    set(CMAKE_REQUIRED_LIBRARIES ${BZIP2_LIBRARIES})
    CHECK_SYMBOL_EXISTS(BZ2_bzCompressInit "bzlib.h" BZIP2_NEED_PREFIX)
    cmake_pop_check_state()
+
+    if(NOT TARGET BZip2::BZip2)
+      add_library(BZip2::BZip2 UNKNOWN IMPORTED)
+      set_target_properties(BZip2::BZip2 PROPERTIES
+        INTERFACE_INCLUDE_DIRECTORIES "${BZIP2_INCLUDE_DIRS}")
+
+      if(BZIP2_LIBRARY_RELEASE)
+        set_property(TARGET BZip2::BZip2 APPEND PROPERTY
+          IMPORTED_CONFIGURATIONS RELEASE)
+        set_target_properties(BZip2::BZip2 PROPERTIES
+          IMPORTED_LOCATION_RELEASE "${BZIP2_LIBRARY_RELEASE}")
+      endif()
+
+      if(BZIP2_LIBRARY_DEBUG)
+        set_property(TARGET BZip2::BZip2 APPEND PROPERTY
+          IMPORTED_CONFIGURATIONS DEBUG)
+        set_target_properties(BZip2::BZip2 PROPERTIES
+          IMPORTED_LOCATION_DEBUG "${BZIP2_LIBRARY_DEBUG}")
+      endif()
+
+      if(NOT BZIP2_LIBRARY_RELEASE AND NOT BZIP2_LIBRARY_DEBUG)
+        set_property(TARGET BZip2::BZip2 APPEND PROPERTY
+          IMPORTED_LOCATION "${BZIP2_LIBRARY}")
+      endif()
+    endif()
 endif ()
 
 mark_as_advanced(BZIP2_INCLUDE_DIR)
diff --git a/Modules/FindBacktrace.cmake b/Modules/FindBacktrace.cmake
index cb4f60a..59ebdc2 100644
--- a/Modules/FindBacktrace.cmake
+++ b/Modules/FindBacktrace.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBacktrace
 # -------------
@@ -34,20 +37,6 @@
 #
 # And then reference that generated header file in actual source.
 
-#=============================================================================
-# Copyright 2013 Vadim Zhukov
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 include(CMakePushCheckState)
 include(CheckSymbolExists)
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake
index 67d71d0..184fb05 100644
--- a/Modules/FindBoost.cmake
+++ b/Modules/FindBoost.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBoost
 # ---------
@@ -202,25 +205,6 @@
 #
 # Set Boost_NO_BOOST_CMAKE to ON to disable the search for boost-cmake.
 
-#=============================================================================
-# Copyright 2006-2012 Kitware, Inc.
-# Copyright 2006-2008 Andreas Schneider <mail at cynapses.org>
-# Copyright 2007      Wengo
-# Copyright 2007      Mike Jackson
-# Copyright 2008      Andreas Pakulat <apaku at gmx.de>
-# Copyright 2008-2012 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 #-------------------------------------------------------------------------------
 # Before we go searching, check whether boost-cmake is available, unless the
 # user specifically asked NOT to search for boost-cmake.
@@ -442,24 +426,26 @@ function(_Boost_GUESS_COMPILER_PREFIX _ret)
     endif()
   elseif (GHSMULTI)
     set(_boost_COMPILER "-ghs")
-  elseif (MSVC14)
-    set(_boost_COMPILER "-vc140")
-  elseif (MSVC12)
-    set(_boost_COMPILER "-vc120")
-  elseif (MSVC11)
-    set(_boost_COMPILER "-vc110")
-  elseif (MSVC10)
-    set(_boost_COMPILER "-vc100")
-  elseif (MSVC90)
-    set(_boost_COMPILER "-vc90")
-  elseif (MSVC80)
-    set(_boost_COMPILER "-vc80")
-  elseif (MSVC71)
-    set(_boost_COMPILER "-vc71")
-  elseif (MSVC70) # Good luck!
-    set(_boost_COMPILER "-vc7") # yes, this is correct
-  elseif (MSVC60) # Good luck!
-    set(_boost_COMPILER "-vc6") # yes, this is correct
+  elseif("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC")
+    if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
+      set(_boost_COMPILER "-vc140")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18)
+      set(_boost_COMPILER "-vc120")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17)
+      set(_boost_COMPILER "-vc110")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)
+      set(_boost_COMPILER "-vc100")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15)
+      set(_boost_COMPILER "-vc90")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14)
+      set(_boost_COMPILER "-vc80")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.10)
+      set(_boost_COMPILER "-vc71")
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13) # Good luck!
+      set(_boost_COMPILER "-vc7") # yes, this is correct
+    else() # MSVC60 Good luck!
+      set(_boost_COMPILER "-vc6") # yes, this is correct
+    endif()
   elseif (BORLAND)
     set(_boost_COMPILER "-bcb")
   elseif(CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
@@ -739,6 +725,21 @@ function(_Boost_COMPONENT_DEPENDENCIES component _ret)
     set(_Boost_THREAD_DEPENDENCIES chrono system date_time atomic)
     set(_Boost_WAVE_DEPENDENCIES filesystem system serialization thread chrono date_time atomic)
     set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
+  elseif(NOT Boost_VERSION VERSION_LESS 106200 AND Boost_VERSION VERSION_LESS 106300)
+    set(_Boost_CHRONO_DEPENDENCIES system)
+    set(_Boost_CONTEXT_DEPENDENCIES thread chrono system date_time)
+    set(_Boost_COROUTINE_DEPENDENCIES context system)
+    set(_Boost_FIBER_DEPENDENCIES context thread chrono system date_time)
+    set(_Boost_FILESYSTEM_DEPENDENCIES system)
+    set(_Boost_IOSTREAMS_DEPENDENCIES regex)
+    set(_Boost_LOG_DEPENDENCIES date_time log_setup system filesystem thread regex chrono atomic)
+    set(_Boost_MATH_DEPENDENCIES math_c99 math_c99f math_c99l math_tr1 math_tr1f math_tr1l atomic)
+    set(_Boost_MPI_DEPENDENCIES serialization)
+    set(_Boost_MPI_PYTHON_DEPENDENCIES python mpi serialization)
+    set(_Boost_RANDOM_DEPENDENCIES system)
+    set(_Boost_THREAD_DEPENDENCIES chrono system date_time atomic)
+    set(_Boost_WAVE_DEPENDENCIES filesystem system serialization thread chrono date_time atomic)
+    set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
   else()
     message(WARNING "Imported targets not available for Boost version ${Boost_VERSION}")
     set(_Boost_IMPORTED_TARGETS FALSE)
@@ -774,6 +775,7 @@ function(_Boost_COMPONENT_HEADERS component _hdrs)
   set(_Boost_COROUTINE_HEADERS           "boost/coroutine/all.hpp")
   set(_Boost_EXCEPTION_HEADERS           "boost/exception/exception.hpp")
   set(_Boost_DATE_TIME_HEADERS           "boost/date_time/date.hpp")
+  set(_Boost_FIBER_HEADERS               "boost/fiber/all.hpp")
   set(_Boost_FILESYSTEM_HEADERS          "boost/filesystem/path.hpp")
   set(_Boost_GRAPH_HEADERS               "boost/graph/adjacency_list.hpp")
   set(_Boost_GRAPH_PARALLEL_HEADERS      "boost/graph/adjacency_list.hpp")
@@ -805,6 +807,10 @@ function(_Boost_COMPONENT_HEADERS component _hdrs)
   set(_Boost_UNIT_TEST_FRAMEWORK_HEADERS "boost/test/framework.hpp")
   set(_Boost_WAVE_HEADERS                "boost/wave.hpp")
   set(_Boost_WSERIALIZATION_HEADERS      "boost/archive/text_wiarchive.hpp")
+  if(WIN32)
+    set(_Boost_BZIP2_HEADERS             "boost/iostreams/filter/bzip2.hpp")
+    set(_Boost_ZLIB_HEADERS              "boost/iostreams/filter/zlib.hpp")
+  endif()
 
   string(TOUPPER ${component} uppercomponent)
   set(${_hdrs} ${_Boost_${uppercomponent}_HEADERS} PARENT_SCOPE)
@@ -862,6 +868,37 @@ function(_Boost_MISSING_DEPENDENCIES componentvar extravar)
 endfunction()
 
 #
+# Update library search directory hint variable with paths used by prebuilt boost binaries.
+#
+# Prebuilt windows binaries (https://sourceforge.net/projects/boost/files/boost-binaries/)
+# have library directories named using MSVC compiler version and architecture.
+# This function would append corresponding directories if MSVC is a current compiler,
+# so having `BOOST_ROOT` would be enough to specify to find everything.
+#
+macro(_Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS componentlibvar basedir)
+  if("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC")
+    if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+      set(_arch_suffix 64)
+    else()
+      set(_arch_suffix 32)
+    endif()
+    if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-14.0)
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-12.0)
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-11.0)
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-10.0)
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-9.0)
+    elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14)
+      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-8.0)
+    endif()
+  endif()
+endmacro()
+
+#
 # End functions/macros
 #
 #-------------------------------------------------------------------------------
@@ -907,7 +944,7 @@ else()
   # _Boost_COMPONENT_HEADERS.  See the instructions at the top of
   # _Boost_COMPONENT_DEPENDENCIES.
   set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS}
-    "1.61.0" "1.61" "1.60.0" "1.60"
+    "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60"
     "1.59.0" "1.59" "1.58.0" "1.58" "1.57.0" "1.57" "1.56.0" "1.56" "1.55.0" "1.55"
     "1.54.0" "1.54" "1.53.0" "1.53" "1.52.0" "1.52" "1.51.0" "1.51"
     "1.50.0" "1.50" "1.49.0" "1.49" "1.48.0" "1.48" "1.47.0" "1.47" "1.46.1"
@@ -1143,8 +1180,8 @@ if(Boost_INCLUDE_DIR)
   math(EXPR Boost_MINOR_VERSION "${Boost_VERSION} / 100 % 1000")
   math(EXPR Boost_SUBMINOR_VERSION "${Boost_VERSION} % 100")
 
-  set(Boost_ERROR_REASON
-    "${Boost_ERROR_REASON}Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}\nBoost include path: ${Boost_INCLUDE_DIR}")
+  string(APPEND Boost_ERROR_REASON
+    "Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}\nBoost include path: ${Boost_INCLUDE_DIR}")
   if(Boost_DEBUG)
     message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
                    "version.hpp reveals boost "
@@ -1166,16 +1203,16 @@ if(Boost_INCLUDE_DIR)
     endif()
     if(NOT Boost_FOUND)
       # State that we found a version of Boost that is too new or too old.
-      set(Boost_ERROR_REASON
-        "${Boost_ERROR_REASON}\nDetected version of Boost is too ${_Boost_VERSION_AGE}. Requested version was ${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}")
+      string(APPEND Boost_ERROR_REASON
+        "\nDetected version of Boost is too ${_Boost_VERSION_AGE}. Requested version was ${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}")
       if (Boost_FIND_VERSION_PATCH)
-        set(Boost_ERROR_REASON
-          "${Boost_ERROR_REASON}.${Boost_FIND_VERSION_PATCH}")
+        string(APPEND Boost_ERROR_REASON
+          ".${Boost_FIND_VERSION_PATCH}")
       endif ()
       if (NOT Boost_FIND_VERSION_EXACT)
-        set(Boost_ERROR_REASON "${Boost_ERROR_REASON} (or newer)")
+        string(APPEND Boost_ERROR_REASON " (or newer)")
       endif ()
-      set(Boost_ERROR_REASON "${Boost_ERROR_REASON}.")
+      string(APPEND Boost_ERROR_REASON ".")
     endif ()
   else()
     # Caller will accept any Boost version.
@@ -1183,8 +1220,8 @@ if(Boost_INCLUDE_DIR)
   endif()
 else()
   set(Boost_FOUND 0)
-  set(Boost_ERROR_REASON
-    "${Boost_ERROR_REASON}Unable to find the Boost header files. Please set BOOST_ROOT to the root directory containing Boost or BOOST_INCLUDEDIR to the directory containing Boost's headers.")
+  string(APPEND Boost_ERROR_REASON
+    "Unable to find the Boost header files. Please set BOOST_ROOT to the root directory containing Boost or BOOST_INCLUDEDIR to the directory containing Boost's headers.")
 endif()
 
 # ------------------------------------------------------------------------
@@ -1261,17 +1298,18 @@ endif()
 #  g        using debug versions of the standard and runtime
 #           support libraries
 if(WIN32 AND Boost_USE_DEBUG_RUNTIME)
-  if(MSVC OR "${CMAKE_CXX_COMPILER}" MATCHES "icl"
+  if("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC"
+          OR "${CMAKE_CXX_COMPILER}" MATCHES "icl"
           OR "${CMAKE_CXX_COMPILER}" MATCHES "icpc")
-    set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}g")
+    string(APPEND _boost_DEBUG_ABI_TAG "g")
   endif()
 endif()
 #  y        using special debug build of python
 if(Boost_USE_DEBUG_PYTHON)
-  set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}y")
+  string(APPEND _boost_DEBUG_ABI_TAG "y")
 endif()
 #  d        using a debug version of your code
-set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}d")
+string(APPEND _boost_DEBUG_ABI_TAG "d")
 #  p        using the STLport standard library rather than the
 #           default one supplied with your compiler
 if(Boost_USE_STLPORT)
@@ -1319,8 +1357,10 @@ foreach(c DEBUG RELEASE)
 
     if(BOOST_ROOT)
       list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${BOOST_ROOT}/lib ${BOOST_ROOT}/stage/lib)
+      _Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} BOOST_ROOT)
     elseif(_ENV_BOOST_ROOT)
       list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${_ENV_BOOST_ROOT}/lib ${_ENV_BOOST_ROOT}/stage/lib)
+      _Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} _ENV_BOOST_ROOT)
     endif()
 
     list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c}
@@ -1599,26 +1639,26 @@ if(Boost_FOUND)
     set(Boost_FOUND 0)
     # We were unable to find some libraries, so generate a sensible
     # error message that lists the libraries we were unable to find.
-    set(Boost_ERROR_REASON
-      "${Boost_ERROR_REASON}\nCould not find the following")
+    string(APPEND Boost_ERROR_REASON
+      "\nCould not find the following")
     if(Boost_USE_STATIC_LIBS)
-      set(Boost_ERROR_REASON "${Boost_ERROR_REASON} static")
+      string(APPEND Boost_ERROR_REASON " static")
     endif()
-    set(Boost_ERROR_REASON
-      "${Boost_ERROR_REASON} Boost libraries:\n")
+    string(APPEND Boost_ERROR_REASON
+      " Boost libraries:\n")
     foreach(COMPONENT ${_Boost_MISSING_COMPONENTS})
-      set(Boost_ERROR_REASON
-        "${Boost_ERROR_REASON}        ${Boost_NAMESPACE}_${COMPONENT}\n")
+      string(APPEND Boost_ERROR_REASON
+        "        ${Boost_NAMESPACE}_${COMPONENT}\n")
     endforeach()
 
     list(LENGTH Boost_FIND_COMPONENTS Boost_NUM_COMPONENTS_WANTED)
     list(LENGTH _Boost_MISSING_COMPONENTS Boost_NUM_MISSING_COMPONENTS)
     if (${Boost_NUM_COMPONENTS_WANTED} EQUAL ${Boost_NUM_MISSING_COMPONENTS})
-      set(Boost_ERROR_REASON
-        "${Boost_ERROR_REASON}No Boost libraries were found. You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
+      string(APPEND Boost_ERROR_REASON
+        "No Boost libraries were found. You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
     else ()
-      set(Boost_ERROR_REASON
-        "${Boost_ERROR_REASON}Some (but not all) of the required Boost libraries were found. You may need to install these additional Boost libraries. Alternatively, set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
+      string(APPEND Boost_ERROR_REASON
+        "Some (but not all) of the required Boost libraries were found. You may need to install these additional Boost libraries. Alternatively, set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
     endif ()
   endif ()
 
@@ -1697,13 +1737,6 @@ if(Boost_FOUND)
             IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
             IMPORTED_LOCATION "${Boost_${UPPERCOMPONENT}_LIBRARY}")
         endif()
-        if(EXISTS "${Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG}")
-          set_property(TARGET Boost::${COMPONENT} APPEND PROPERTY
-            IMPORTED_CONFIGURATIONS DEBUG)
-          set_target_properties(Boost::${COMPONENT} PROPERTIES
-            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
-            IMPORTED_LOCATION_DEBUG "${Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG}")
-        endif()
         if(EXISTS "${Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE}")
           set_property(TARGET Boost::${COMPONENT} APPEND PROPERTY
             IMPORTED_CONFIGURATIONS RELEASE)
@@ -1711,6 +1744,13 @@ if(Boost_FOUND)
             IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
             IMPORTED_LOCATION_RELEASE "${Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE}")
         endif()
+        if(EXISTS "${Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG}")
+          set_property(TARGET Boost::${COMPONENT} APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS DEBUG)
+          set_target_properties(Boost::${COMPONENT} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+            IMPORTED_LOCATION_DEBUG "${Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG}")
+        endif()
         if(_Boost_${UPPERCOMPONENT}_DEPENDENCIES)
           unset(_Boost_${UPPERCOMPONENT}_TARGET_DEPENDENCIES)
           foreach(dep ${_Boost_${UPPERCOMPONENT}_DEPENDENCIES})
diff --git a/Modules/FindBullet.cmake b/Modules/FindBullet.cmake
index fc848fa..d000f79 100644
--- a/Modules/FindBullet.cmake
+++ b/Modules/FindBullet.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindBullet
 # ----------
@@ -32,20 +35,6 @@
 #
 #   BULLET_ROOT - Can be set to bullet install path or Windows build path
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(_FIND_BULLET_LIBRARY _var)
   find_library(${_var}
      NAMES
diff --git a/Modules/FindCABLE.cmake b/Modules/FindCABLE.cmake
index 5cea109..450e322 100644
--- a/Modules/FindCABLE.cmake
+++ b/Modules/FindCABLE.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCABLE
 # ---------
@@ -20,19 +23,6 @@
 # ${CABLE_TCL_LIBRARY}.  You should also add ${CABLE_INCLUDE_DIR} as an
 # include directory.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT CABLE)
   find_path(CABLE_BUILD_DIR cableVersion.h)
 endif()
diff --git a/Modules/FindCUDA.cmake b/Modules/FindCUDA.cmake
index 48bb554..6b76c25 100644
--- a/Modules/FindCUDA.cmake
+++ b/Modules/FindCUDA.cmake
@@ -188,10 +188,8 @@
 #      files.
 #
 #
-#
 #   CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS( output_file_var cuda_target
 #                                            nvcc_flags object_files)
-#
 #   -- Generates the link object required by separable compilation from the given
 #      object files.  This is called automatically for CUDA_ADD_EXECUTABLE and
 #      CUDA_ADD_LIBRARY, but can be called manually when using CUDA_WRAP_SRCS
@@ -201,6 +199,24 @@
 #      specified by CUDA_64_BIT_DEVICE_CODE.  Note that this is a function
 #      instead of a macro.
 #
+#   CUDA_SELECT_NVCC_ARCH_FLAGS(out_variable [target_CUDA_architectures])
+#   -- Selects GPU arch flags for nvcc based on target_CUDA_architectures
+#      target_CUDA_architectures : Auto | Common | All | LIST(ARCH_AND_PTX ...)
+#       - "Auto" detects local machine GPU compute arch at runtime.
+#       - "Common" and "All" cover common and entire subsets of architectures
+#      ARCH_AND_PTX : NAME | NUM.NUM | NUM.NUM(NUM.NUM) | NUM.NUM+PTX
+#      NAME: Fermi Kepler Maxwell Kepler+Tegra Kepler+Tesla Maxwell+Tegra Pascal
+#      NUM: Any number. Only those pairs are currently accepted by NVCC though:
+#            2.0 2.1 3.0 3.2 3.5 3.7 5.0 5.2 5.3 6.0 6.2
+#      Returns LIST of flags to be added to CUDA_NVCC_FLAGS in ${out_variable}
+#      Additionally, sets ${out_variable}_readable to the resulting numeric list
+#      Example:
+#       CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS 3.0 3.5+PTX 5.2(5.0) Maxwell)
+#        LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})
+#
+#      More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA
+#      Note that this is a function instead of a macro.
+#
 #   CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
 #                    [STATIC | SHARED | MODULE] [OPTIONS ...] )
 #   -- This is where all the magic happens.  CUDA_ADD_EXECUTABLE,
@@ -283,10 +299,12 @@
 #                            implementation (alternative to:
 #                            CUDA_ADD_CUFFT_TO_TARGET macro)
 #   CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
-#                            implementation (alterative to:
+#                            implementation (alternative to:
 #                            CUDA_ADD_CUBLAS_TO_TARGET macro).
 #   CUDA_cudart_static_LIBRARY -- Statically linkable cuda runtime library.
 #                                 Only available for CUDA version 5.5+
+#   CUDA_cudadevrt_LIBRARY -- Device runtime library.
+#                             Required for separable compilation.
 #   CUDA_cupti_LIBRARY    -- CUDA Profiling Tools Interface library.
 #                            Only available for CUDA version 4.0+.
 #   CUDA_curand_LIBRARY   -- CUDA Random Number Generation library.
@@ -548,6 +566,7 @@ macro(cuda_unset_include_and_libraries)
     unset(CUDA_CUDARTEMU_LIBRARY CACHE)
   endif()
   unset(CUDA_cudart_static_LIBRARY CACHE)
+  unset(CUDA_cudadevrt_LIBRARY CACHE)
   unset(CUDA_cublas_LIBRARY CACHE)
   unset(CUDA_cublas_device_LIBRARY CACHE)
   unset(CUDA_cublasemu_LIBRARY CACHE)
@@ -563,8 +582,8 @@ macro(cuda_unset_include_and_libraries)
   unset(CUDA_npps_LIBRARY CACHE)
   unset(CUDA_nvcuvenc_LIBRARY CACHE)
   unset(CUDA_nvcuvid_LIBRARY CACHE)
-
   unset(CUDA_USE_STATIC_CUDA_RUNTIME CACHE)
+  unset(CUDA_GPU_DETECT_OUTPUT CACHE)
 endmacro()
 
 # Check to see if the CUDA_TOOLKIT_ROOT_DIR and CUDA_SDK_ROOT_DIR have changed,
@@ -580,31 +599,33 @@ if(NOT "${CUDA_TOOLKIT_TARGET_DIR}" STREQUAL "${CUDA_TOOLKIT_TARGET_DIR_INTERNAL
   cuda_unset_include_and_libraries()
 endif()
 
-if(NOT "${CUDA_SDK_ROOT_DIR}" STREQUAL "${CUDA_SDK_ROOT_DIR_INTERNAL}")
-  # No specific variables to catch.  Use this kind of code before calling
-  # find_package(CUDA) to clean up any variables that may depend on this path.
+#
+#  End of unset()
+#
 
-  #   unset(MY_SPECIAL_CUDA_SDK_INCLUDE_DIR CACHE)
-  #   unset(MY_SPECIAL_CUDA_SDK_LIBRARY CACHE)
-endif()
+#
+#  Start looking for things
+#
 
 # Search for the cuda distribution.
-if(NOT CUDA_TOOLKIT_ROOT_DIR)
-
+if(NOT CUDA_TOOLKIT_ROOT_DIR AND NOT CMAKE_CROSSCOMPILING)
   # Search in the CUDA_BIN_PATH first.
   find_path(CUDA_TOOLKIT_ROOT_DIR
     NAMES nvcc nvcc.exe
     PATHS
+      ENV CUDA_TOOLKIT_ROOT
       ENV CUDA_PATH
       ENV CUDA_BIN_PATH
     PATH_SUFFIXES bin bin64
     DOC "Toolkit location."
     NO_DEFAULT_PATH
     )
+
   # Now search default paths
   find_path(CUDA_TOOLKIT_ROOT_DIR
     NAMES nvcc nvcc.exe
-    PATHS /usr/local/bin
+    PATHS /opt/cuda/bin
+          /usr/local/bin
           /usr/local/cuda/bin
     DOC "Toolkit location."
     )
@@ -613,7 +634,9 @@ if(NOT CUDA_TOOLKIT_ROOT_DIR)
     string(REGEX REPLACE "[/\\\\]?bin[64]*[/\\\\]?$" "" CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR})
     # We need to force this back into the cache.
     set(CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR} CACHE PATH "Toolkit location." FORCE)
+    set(CUDA_TOOLKIT_TARGET_DIR ${CUDA_TOOLKIT_ROOT_DIR})
   endif()
+
   if (NOT EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
     if(CUDA_FIND_REQUIRED)
       message(FATAL_ERROR "Specify CUDA_TOOLKIT_ROOT_DIR")
@@ -623,8 +646,45 @@ if(NOT CUDA_TOOLKIT_ROOT_DIR)
   endif ()
 endif ()
 
+if(CMAKE_CROSSCOMPILING)
+  SET (CUDA_TOOLKIT_ROOT $ENV{CUDA_TOOLKIT_ROOT})
+  if(CMAKE_SYSTEM_PROCESSOR STREQUAL "armv7-a")
+    # Support for NVPACK
+    set (CUDA_TOOLKIT_TARGET_NAME "armv7-linux-androideabi")
+  elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm")
+    # Support for arm cross compilation
+    set(CUDA_TOOLKIT_TARGET_NAME "armv7-linux-gnueabihf")
+  elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64")
+    # Support for aarch64 cross compilation
+    if (ANDROID_ARCH_NAME STREQUAL "arm64")
+      set(CUDA_TOOLKIT_TARGET_NAME "aarch64-linux-androideabi")
+    else()
+      set(CUDA_TOOLKIT_TARGET_NAME "aarch64-linux")
+    endif (ANDROID_ARCH_NAME STREQUAL "arm64")
+  endif()
+
+  if (EXISTS "${CUDA_TOOLKIT_ROOT}/targets/${CUDA_TOOLKIT_TARGET_NAME}")
+    set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT}/targets/${CUDA_TOOLKIT_TARGET_NAME}" CACHE PATH "CUDA Toolkit target location.")
+    SET (CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT})
+    mark_as_advanced(CUDA_TOOLKIT_TARGET_DIR)
+  endif()
+
+  # add known CUDA targetr root path to the set of directories we search for programs, libraries and headers
+  set( CMAKE_FIND_ROOT_PATH "${CUDA_TOOLKIT_TARGET_DIR};${CMAKE_FIND_ROOT_PATH}")
+  macro( cuda_find_host_program )
+    find_host_program( ${ARGN} )
+  endmacro()
+else()
+  # for non-cross-compile, find_host_program == find_program and CUDA_TOOLKIT_TARGET_DIR == CUDA_TOOLKIT_ROOT_DIR
+  macro( cuda_find_host_program )
+    find_program( ${ARGN} )
+  endmacro()
+  SET (CUDA_TOOLKIT_TARGET_DIR ${CUDA_TOOLKIT_ROOT_DIR})
+endif()
+
+
 # CUDA_NVCC_EXECUTABLE
-find_program(CUDA_NVCC_EXECUTABLE
+cuda_find_host_program(CUDA_NVCC_EXECUTABLE
   NAMES nvcc
   PATHS "${CUDA_TOOLKIT_ROOT_DIR}"
   ENV CUDA_PATH
@@ -633,7 +693,7 @@ find_program(CUDA_NVCC_EXECUTABLE
   NO_DEFAULT_PATH
   )
 # Search default search paths, after we search our own set of paths.
-find_program(CUDA_NVCC_EXECUTABLE nvcc)
+cuda_find_host_program(CUDA_NVCC_EXECUTABLE nvcc)
 mark_as_advanced(CUDA_NVCC_EXECUTABLE)
 
 if(CUDA_NVCC_EXECUTABLE AND NOT CUDA_VERSION)
@@ -649,33 +709,14 @@ else()
   string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR "${CUDA_VERSION}")
 endif()
 
+
 # Always set this convenience variable
 set(CUDA_VERSION_STRING "${CUDA_VERSION}")
 
-# Support for arm cross compilation with CUDA 5.5
-if(CUDA_VERSION VERSION_GREATER "5.0" AND CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm" AND EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-gnueabihf")
-  set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-gnueabihf" CACHE PATH "Toolkit target location.")
-# Support for aarch64 cross compilation with CUDA 7.0
-elseif(CUDA_VERSION VERSION_GREATER "6.5" AND CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64" AND EXISTS "${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux")
-  set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT_DIR}/targets/aarch64-linux" CACHE PATH "Toolkit target location.")
-else()
-  set(CUDA_TOOLKIT_TARGET_DIR "${CUDA_TOOLKIT_ROOT_DIR}" CACHE PATH "Toolkit target location.")
-endif()
-mark_as_advanced(CUDA_TOOLKIT_TARGET_DIR)
-
-# Target CPU architecture
-if(CUDA_VERSION VERSION_GREATER "5.0" AND CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm")
-  set(_cuda_target_cpu_arch_initial "ARM")
-else()
-  set(_cuda_target_cpu_arch_initial "")
-endif()
-set(CUDA_TARGET_CPU_ARCH ${_cuda_target_cpu_arch_initial} CACHE STRING "Specify the name of the class of CPU architecture for which the input files must be compiled.")
-mark_as_advanced(CUDA_TARGET_CPU_ARCH)
-
 # CUDA_TOOLKIT_INCLUDE
 find_path(CUDA_TOOLKIT_INCLUDE
   device_functions.h # Header included in toolkit
-  PATHS "${CUDA_TOOLKIT_TARGET_DIR}" "${CUDA_TOOLKIT_ROOT_DIR}"
+  PATHS ${CUDA_TOOLKIT_TARGET_DIR}
   ENV CUDA_PATH
   ENV CUDA_INC_PATH
   PATH_SUFFIXES include
@@ -692,7 +733,7 @@ else()
 endif()
 
 # Set the user list of include dir to nothing to initialize it.
-set (CUDA_NVCC_INCLUDE_ARGS_USER "")
+set (CUDA_NVCC_INCLUDE_DIRS_USER "")
 set (CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_INCLUDE})
 
 macro(cuda_find_library_local_first_with_path_ext _var _names _doc _path_ext )
@@ -705,19 +746,21 @@ macro(cuda_find_library_local_first_with_path_ext _var _names _doc _path_ext )
   # (lib/Win32) and the old path (lib).
   find_library(${_var}
     NAMES ${_names}
-    PATHS "${CUDA_TOOLKIT_TARGET_DIR}" "${CUDA_TOOLKIT_ROOT_DIR}"
+    PATHS "${CUDA_TOOLKIT_TARGET_DIR}"
     ENV CUDA_PATH
     ENV CUDA_LIB_PATH
     PATH_SUFFIXES ${_cuda_64bit_lib_dir} "${_path_ext}lib/Win32" "${_path_ext}lib" "${_path_ext}libWin32"
     DOC ${_doc}
     NO_DEFAULT_PATH
     )
-  # Search default search paths, after we search our own set of paths.
-  find_library(${_var}
-    NAMES ${_names}
-    PATHS "/usr/lib/nvidia-current"
-    DOC ${_doc}
-    )
+  if (NOT CMAKE_CROSSCOMPILING)
+    # Search default search paths, after we search our own set of paths.
+    find_library(${_var}
+      NAMES ${_names}
+      PATHS "/usr/lib/nvidia-current"
+      DOC ${_doc}
+      )
+  endif()
 endmacro()
 
 macro(cuda_find_library_local_first _var _names _doc)
@@ -738,15 +781,25 @@ if(CUDA_VERSION VERSION_EQUAL "3.0")
     CUDA_CUDARTEMU_LIBRARY
     )
 endif()
+
 if(NOT CUDA_VERSION VERSION_LESS "5.5")
   cuda_find_library_local_first(CUDA_cudart_static_LIBRARY cudart_static "static CUDA runtime library")
   mark_as_advanced(CUDA_cudart_static_LIBRARY)
 endif()
+
+
 if(CUDA_cudart_static_LIBRARY)
-  # Set whether to use the static cuda runtime.
+  # If static cudart available, use it by default, but provide a user-visible option to disable it.
   option(CUDA_USE_STATIC_CUDA_RUNTIME "Use the static version of the CUDA runtime library if available" ON)
+  set(CUDA_CUDART_LIBRARY_VAR CUDA_cudart_static_LIBRARY)
 else()
-  option(CUDA_USE_STATIC_CUDA_RUNTIME "Use the static version of the CUDA runtime library if available" OFF)
+  # If not available, silently disable the option.
+  set(CUDA_USE_STATIC_CUDA_RUNTIME OFF CACHE INTERNAL "")
+  set(CUDA_CUDART_LIBRARY_VAR CUDA_CUDART_LIBRARY)
+endif()
+if(NOT CUDA_VERSION VERSION_LESS "5.0")
+  cuda_find_library_local_first(CUDA_cudadevrt_LIBRARY cudadevrt "\"cudadevrt\" library")
+  mark_as_advanced(CUDA_cudadevrt_LIBRARY)
 endif()
 
 if(CUDA_USE_STATIC_CUDA_RUNTIME)
@@ -772,8 +825,9 @@ if(CUDA_USE_STATIC_CUDA_RUNTIME)
     else()
       unset(CMAKE_THREAD_PREFER_PTHREAD)
     endif()
-    if (NOT APPLE)
-      # Here is librt that has things such as, clock_gettime, shm_open, and shm_unlink.
+
+    if(NOT APPLE)
+      #On Linux, you must link against librt when using the static cuda runtime.
       find_library(CUDA_rt_LIBRARY rt)
       if (NOT CUDA_rt_LIBRARY)
         message(WARNING "Expecting to find librt for libcudart_static, but didn't find it.")
@@ -955,12 +1009,13 @@ set(CUDA_SDK_ROOT_DIR_INTERNAL "${CUDA_SDK_ROOT_DIR}" CACHE INTERNAL
   "This is the value of the last time CUDA_SDK_ROOT_DIR was set successfully." FORCE)
 
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+
 find_package_handle_standard_args(CUDA
   REQUIRED_VARS
     CUDA_TOOLKIT_ROOT_DIR
     CUDA_NVCC_EXECUTABLE
     CUDA_INCLUDE_DIRS
-    CUDA_CUDART_LIBRARY
+    ${CUDA_CUDART_LIBRARY_VAR}
   VERSION_VAR
     CUDA_VERSION
   )
@@ -977,7 +1032,7 @@ find_package_handle_standard_args(CUDA
 # Add include directories to pass to the nvcc command.
 macro(CUDA_INCLUDE_DIRECTORIES)
   foreach(dir ${ARGN})
-    list(APPEND CUDA_NVCC_INCLUDE_ARGS_USER -I${dir})
+    list(APPEND CUDA_NVCC_INCLUDE_DIRS_USER ${dir})
   endforeach()
 endmacro()
 
@@ -986,6 +1041,7 @@ endmacro()
 cuda_find_helper_file(parse_cubin cmake)
 cuda_find_helper_file(make2cmake cmake)
 cuda_find_helper_file(run_nvcc cmake)
+include("${CMAKE_CURRENT_LIST_DIR}/FindCUDA/select_compute_arch.cmake")
 
 ##############################################################################
 # Separate the OPTIONS out from the sources
@@ -1139,6 +1195,18 @@ endfunction()
 
 macro(CUDA_WRAP_SRCS cuda_target format generated_files)
 
+  # Put optional arguments in list.
+  set(_argn_list "${ARGN}")
+  # If one of the given optional arguments is "PHONY", make a note of it, then
+  # remove it from the list.
+  list(FIND _argn_list "PHONY" _phony_idx)
+  if("${_phony_idx}" GREATER "-1")
+    set(_target_is_phony true)
+    list(REMOVE_AT _argn_list ${_phony_idx})
+  else()
+    set(_target_is_phony false)
+  endif()
+
   # If CMake doesn't support separable compilation, complain
   if(CUDA_SEPARABLE_COMPILATION AND CMAKE_VERSION VERSION_LESS "2.8.10.1")
     message(SEND_ERROR "CUDA_SEPARABLE_COMPILATION isn't supported for CMake versions less than 2.8.10.1")
@@ -1200,18 +1268,27 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files)
   endif()
 
   # Initialize our list of includes with the user ones followed by the CUDA system ones.
-  set(CUDA_NVCC_INCLUDE_ARGS ${CUDA_NVCC_INCLUDE_ARGS_USER} "-I${CUDA_INCLUDE_DIRS}")
-  # Get the include directories for this directory and use them for our nvcc command.
-  # Remove duplicate entries which may be present since include_directories
-  # in CMake >= 2.8.8 does not remove them.
-  get_directory_property(CUDA_NVCC_INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES)
-  list(REMOVE_DUPLICATES CUDA_NVCC_INCLUDE_DIRECTORIES)
-  if(CUDA_NVCC_INCLUDE_DIRECTORIES)
-    foreach(dir ${CUDA_NVCC_INCLUDE_DIRECTORIES})
-      list(APPEND CUDA_NVCC_INCLUDE_ARGS -I${dir})
-    endforeach()
+  set(CUDA_NVCC_INCLUDE_DIRS ${CUDA_NVCC_INCLUDE_DIRS_USER} "${CUDA_INCLUDE_DIRS}")
+  if(_target_is_phony)
+    # If the passed in target name isn't a real target (i.e., this is from a call to one of the
+    # cuda_compile_* functions), need to query directory properties to get include directories
+    # and compile definitions.
+    get_directory_property(_dir_include_dirs INCLUDE_DIRECTORIES)
+    get_directory_property(_dir_compile_defs COMPILE_DEFINITIONS)
+
+    list(APPEND CUDA_NVCC_INCLUDE_DIRS "${_dir_include_dirs}")
+    set(CUDA_NVCC_COMPILE_DEFINITIONS "${_dir_compile_defs}")
+  else()
+    # Append the include directories for this target via generator expression, which is
+    # expanded by the FILE(GENERATE) call below.  This generator expression captures all
+    # include dirs set by the user, whether via directory properties or target properties
+    list(APPEND CUDA_NVCC_INCLUDE_DIRS "$<TARGET_PROPERTY:${cuda_target},INCLUDE_DIRECTORIES>")
+
+    # Do the same thing with compile definitions
+    set(CUDA_NVCC_COMPILE_DEFINITIONS "$<TARGET_PROPERTY:${cuda_target},COMPILE_DEFINITIONS>")
   endif()
 
+
   # Reset these variables
   set(CUDA_WRAP_OPTION_NVCC_FLAGS)
   foreach(config ${CUDA_configuration_types})
@@ -1219,7 +1296,7 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files)
     set(CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper})
   endforeach()
 
-  CUDA_GET_SOURCES_AND_OPTIONS(_cuda_wrap_sources _cuda_wrap_cmake_options _cuda_wrap_options ${ARGN})
+  CUDA_GET_SOURCES_AND_OPTIONS(_cuda_wrap_sources _cuda_wrap_cmake_options _cuda_wrap_options ${_argn_list})
   CUDA_PARSE_NVCC_OPTIONS(CUDA_WRAP_OPTION_NVCC_FLAGS ${_cuda_wrap_options})
 
   # Figure out if we are building a shared library.  BUILD_SHARED_LIBS is
@@ -1278,13 +1355,13 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files)
         set(_cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
       endif()
 
-      set(_cuda_host_flags "${_cuda_host_flags}\nset(CMAKE_HOST_FLAGS_${config_upper} ${_cuda_C_FLAGS})")
+      string(APPEND _cuda_host_flags "\nset(CMAKE_HOST_FLAGS_${config_upper} ${_cuda_C_FLAGS})")
     endif()
 
     # Note that if we ever want CUDA_NVCC_FLAGS_<CONFIG> to be string (instead of a list
     # like it is currently), we can remove the quotes around the
     # ${CUDA_NVCC_FLAGS_${config_upper}} variable like the CMAKE_HOST_FLAGS_<CONFIG> variable.
-    set(_cuda_nvcc_flags_config "${_cuda_nvcc_flags_config}\nset(CUDA_NVCC_FLAGS_${config_upper} ${CUDA_NVCC_FLAGS_${config_upper}} ;; ${CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper}})")
+    string(APPEND _cuda_nvcc_flags_config "\nset(CUDA_NVCC_FLAGS_${config_upper} ${CUDA_NVCC_FLAGS_${config_upper}} ;; ${CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper}})")
   endforeach()
 
   # Process the C++11 flag.  If the host sets the flag, we need to add it to nvcc and
@@ -1300,14 +1377,6 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files)
     string(REGEX REPLACE "[-]+std=c\\+\\+11" "" _cuda_host_flags "${_cuda_host_flags}")
   endif()
 
-  # Get the list of definitions from the directory property
-  get_directory_property(CUDA_NVCC_DEFINITIONS COMPILE_DEFINITIONS)
-  if(CUDA_NVCC_DEFINITIONS)
-    foreach(_definition ${CUDA_NVCC_DEFINITIONS})
-      list(APPEND nvcc_flags "-D${_definition}")
-    endforeach()
-  endif()
-
   if(_cuda_build_shared_libs)
     list(APPEND nvcc_flags "-D${cuda_target}_EXPORTS")
   endif()
@@ -1317,7 +1386,7 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files)
 
   # Iterate over the macro arguments and create custom
   # commands for all the .cu files.
-  foreach(file ${ARGN})
+  foreach(file ${_argn_list})
     # Ignore any file marked as a HEADER_FILE_ONLY
     get_source_file_property(_is_header ${file} HEADER_FILE_ONLY)
     # Allow per source file overrides of the format.  Also allows compiling non-.cu files.
@@ -1675,6 +1744,12 @@ macro(CUDA_ADD_LIBRARY cuda_target)
     ${CUDA_LIBRARIES}
     )
 
+  if(CUDA_SEPARABLE_COMPILATION)
+    target_link_libraries(${cuda_target}
+      ${CUDA_cudadevrt_LIBRARY}
+      )
+  endif()
+
   # We need to set the linker language based on what the expected generated file
   # would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
   set_target_properties(${cuda_target}
@@ -1735,12 +1810,23 @@ endmacro()
 ###############################################################################
 ###############################################################################
 macro(cuda_compile_base cuda_target format generated_files)
+  # Update a counter in this directory, to keep phony target names unique.
+  set(_cuda_target "${cuda_target}")
+  get_property(_counter DIRECTORY PROPERTY _cuda_internal_phony_counter)
+  if(_counter)
+    math(EXPR _counter "${_counter} + 1")
+  else()
+    set(_counter 1)
+  endif()
+  set(_cuda_target "${_cuda_target}_${_counter}")
+  set_property(DIRECTORY PROPERTY _cuda_internal_phony_counter ${_counter})
 
   # Separate the sources from the options
   CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
+
   # Create custom commands and targets for each file.
-  CUDA_WRAP_SRCS( ${cuda_target} ${format} _generated_files ${_sources} ${_cmake_options}
-    OPTIONS ${_options} )
+  CUDA_WRAP_SRCS( ${_cuda_target} ${format} _generated_files ${_sources}
+                  ${_cmake_options} OPTIONS ${_options} PHONY)
 
   set( ${generated_files} ${_generated_files})
 
diff --git a/Modules/FindCUDA/make2cmake.cmake b/Modules/FindCUDA/make2cmake.cmake
index 802f93a..7b5389e 100644
--- a/Modules/FindCUDA/make2cmake.cmake
+++ b/Modules/FindCUDA/make2cmake.cmake
@@ -100,7 +100,7 @@ list(REMOVE_DUPLICATES dependency_list)
 list(SORT dependency_list)
 
 foreach(file ${dependency_list})
-  set(cuda_nvcc_depend "${cuda_nvcc_depend} \"${file}\"\n")
+  string(APPEND cuda_nvcc_depend " \"${file}\"\n")
 endforeach()
 
 file(WRITE ${output_file} "# Generated by: make2cmake.cmake\nSET(CUDA_NVCC_DEPEND\n ${cuda_nvcc_depend})\n\n")
diff --git a/Modules/FindCUDA/run_nvcc.cmake b/Modules/FindCUDA/run_nvcc.cmake
index 12b83e0..28cc1e9 100644
--- a/Modules/FindCUDA/run_nvcc.cmake
+++ b/Modules/FindCUDA/run_nvcc.cmake
@@ -73,10 +73,25 @@ set(CUDA_NVCC_EXECUTABLE "@CUDA_NVCC_EXECUTABLE@") # path
 set(CUDA_NVCC_FLAGS @CUDA_NVCC_FLAGS@ ;; @CUDA_WRAP_OPTION_NVCC_FLAGS@) # list
 @CUDA_NVCC_FLAGS_CONFIG@
 set(nvcc_flags @nvcc_flags@) # list
-set(CUDA_NVCC_INCLUDE_ARGS "@CUDA_NVCC_INCLUDE_ARGS@") # list (needs to be in quotes to handle spaces properly).
+set(CUDA_NVCC_INCLUDE_DIRS "@CUDA_NVCC_INCLUDE_DIRS@") # list (needs to be in quotes to handle spaces properly).
+set(CUDA_NVCC_COMPILE_DEFINITIONS "@CUDA_NVCC_COMPILE_DEFINITIONS@") # list (needs to be in quotes to handle spaces properly).
 set(format_flag "@format_flag@") # string
 set(cuda_language_flag @cuda_language_flag@) # list
 
+# Clean up list of include directories and add -I flags
+list(REMOVE_DUPLICATES CUDA_NVCC_INCLUDE_DIRS)
+set(CUDA_NVCC_INCLUDE_ARGS)
+foreach(dir ${CUDA_NVCC_INCLUDE_DIRS})
+  # Extra quotes are added around each flag to help nvcc parse out flags with spaces.
+  list(APPEND CUDA_NVCC_INCLUDE_ARGS "-I${dir}")
+endforeach()
+
+# Clean up list of compile definitions, add -D flags, and append to nvcc_flags
+list(REMOVE_DUPLICATES CUDA_NVCC_COMPILE_DEFINITIONS)
+foreach(def ${CUDA_NVCC_COMPILE_DEFINITIONS})
+  list(APPEND nvcc_flags "-D${def}")
+endforeach()
+
 if(build_cubin AND NOT generated_cubin_file)
   message(FATAL_ERROR "You must specify generated_cubin_file on the command line")
 endif()
@@ -95,7 +110,7 @@ string(TOUPPER "${build_configuration}" build_configuration)
 #message("CUDA_NVCC_HOST_COMPILER_FLAGS = ${CUDA_NVCC_HOST_COMPILER_FLAGS}")
 foreach(flag ${CMAKE_HOST_FLAGS} ${CMAKE_HOST_FLAGS_${build_configuration}})
   # Extra quotes are added around each flag to help nvcc parse out flags with spaces.
-  set(nvcc_host_compiler_flags "${nvcc_host_compiler_flags},\"${flag}\"")
+  string(APPEND nvcc_host_compiler_flags ",\"${flag}\"")
 endforeach()
 if (nvcc_host_compiler_flags)
   set(nvcc_host_compiler_flags "-Xcompiler" ${nvcc_host_compiler_flags})
diff --git a/Modules/FindCUDA/select_compute_arch.cmake b/Modules/FindCUDA/select_compute_arch.cmake
new file mode 100644
index 0000000..5ce71a9
--- /dev/null
+++ b/Modules/FindCUDA/select_compute_arch.cmake
@@ -0,0 +1,195 @@
+# Synopsis:
+#   CUDA_SELECT_NVCC_ARCH_FLAGS(out_variable [target_CUDA_architectures])
+#   -- Selects GPU arch flags for nvcc based on target_CUDA_architectures
+#      target_CUDA_architectures : Auto | Common | All | LIST(ARCH_AND_PTX ...)
+#       - "Auto" detects local machine GPU compute arch at runtime.
+#       - "Common" and "All" cover common and entire subsets of architectures
+#      ARCH_AND_PTX : NAME | NUM.NUM | NUM.NUM(NUM.NUM) | NUM.NUM+PTX
+#      NAME: Fermi Kepler Maxwell Kepler+Tegra Kepler+Tesla Maxwell+Tegra Pascal
+#      NUM: Any number. Only those pairs are currently accepted by NVCC though:
+#            2.0 2.1 3.0 3.2 3.5 3.7 5.0 5.2 5.3 6.0 6.2
+#      Returns LIST of flags to be added to CUDA_NVCC_FLAGS in ${out_variable}
+#      Additionally, sets ${out_variable}_readable to the resulting numeric list
+#      Example:
+#       CUDA_SELECT_NVCC_ARCH_FLAGS(ARCH_FLAGS 3.0 3.5+PTX 5.2(5.0) Maxwell)
+#        LIST(APPEND CUDA_NVCC_FLAGS ${ARCH_FLAGS})
+#
+#      More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA
+#
+
+# This list will be used for CUDA_ARCH_NAME = All option
+set(CUDA_KNOWN_GPU_ARCHITECTURES  "Fermi" "Kepler" "Maxwell")
+
+# This list will be used for CUDA_ARCH_NAME = Common option (enabled by default)
+set(CUDA_COMMON_GPU_ARCHITECTURES "3.0" "3.5" "5.0")
+
+if (CUDA_VERSION VERSION_GREATER "6.5")
+  list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Kepler+Tegra" "Kepler+Tesla" "Maxwell+Tegra")
+  list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2")
+endif ()
+
+if (CUDA_VERSION VERSION_GREATER "7.5")
+  list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Pascal")
+  list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.0" "6.1" "6.1+PTX")
+else()
+  list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2+PTX")
+endif ()
+
+
+
+################################################################################################
+# A function for automatic detection of GPUs installed  (if autodetection is enabled)
+# Usage:
+#   CUDA_DETECT_INSTALLED_GPUS(OUT_VARIABLE)
+#
+function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE)
+  if(NOT CUDA_GPU_DETECT_OUTPUT)
+    set(cufile ${PROJECT_BINARY_DIR}/detect_cuda_archs.cu)
+
+    file(WRITE ${cufile} ""
+      "#include <cstdio>\n"
+      "int main()\n"
+      "{\n"
+      "  int count = 0;\n"
+      "  if (cudaSuccess != cudaGetDeviceCount(&count)) return -1;\n"
+      "  if (count == 0) return -1;\n"
+      "  for (int device = 0; device < count; ++device)\n"
+      "  {\n"
+      "    cudaDeviceProp prop;\n"
+      "    if (cudaSuccess == cudaGetDeviceProperties(&prop, device))\n"
+      "      std::printf(\"%d.%d \", prop.major, prop.minor);\n"
+      "  }\n"
+      "  return 0;\n"
+      "}\n")
+
+    execute_process(COMMAND "${CUDA_NVCC_EXECUTABLE}" "--run" "${cufile}"
+                    WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/CMakeFiles/"
+                    RESULT_VARIABLE nvcc_res OUTPUT_VARIABLE nvcc_out
+                    ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+    if(nvcc_res EQUAL 0)
+      string(REPLACE "2.1" "2.1(2.0)" nvcc_out "${nvcc_out}")
+      set(CUDA_GPU_DETECT_OUTPUT ${nvcc_out} CACHE INTERNAL "Returned GPU architetures from detect_gpus tool" FORCE)
+    endif()
+  endif()
+
+  if(NOT CUDA_GPU_DETECT_OUTPUT)
+    message(STATUS "Automatic GPU detection failed. Building for common architectures.")
+    set(${OUT_VARIABLE} ${CUDA_COMMON_GPU_ARCHITECTURES} PARENT_SCOPE)
+  else()
+    set(${OUT_VARIABLE} ${CUDA_GPU_DETECT_OUTPUT} PARENT_SCOPE)
+  endif()
+endfunction()
+
+
+################################################################################################
+# Function for selecting GPU arch flags for nvcc based on CUDA architectures from parameter list
+# Usage:
+#   SELECT_NVCC_ARCH_FLAGS(out_variable [list of CUDA compute archs])
+function(CUDA_SELECT_NVCC_ARCH_FLAGS out_variable)
+  set(CUDA_ARCH_LIST "${ARGN}")
+
+  if("X${CUDA_ARCH_LIST}" STREQUAL "X" )
+    set(CUDA_ARCH_LIST "Auto")
+  endif()
+
+  set(cuda_arch_bin)
+  set(cuda_arch_ptx)
+
+  if("${CUDA_ARCH_LIST}" STREQUAL "All")
+    set(CUDA_ARCH_LIST ${CUDA_KNOWN_GPU_ARCHITECTURES})
+  elseif("${CUDA_ARCH_LIST}" STREQUAL "Common")
+    set(CUDA_ARCH_LIST ${CUDA_COMMON_GPU_ARCHITECTURES})
+  elseif("${CUDA_ARCH_LIST}" STREQUAL "Auto")
+    CUDA_DETECT_INSTALLED_GPUS(CUDA_ARCH_LIST)
+    message(STATUS "Autodetected CUDA architecture(s): ${CUDA_ARCH_LIST}")
+  endif()
+
+  # Now process the list and look for names
+  string(REGEX REPLACE "[ \t]+" ";" CUDA_ARCH_LIST "${CUDA_ARCH_LIST}")
+  list(REMOVE_DUPLICATES CUDA_ARCH_LIST)
+  foreach(arch_name ${CUDA_ARCH_LIST})
+    set(arch_bin)
+    set(add_ptx FALSE)
+    # Check to see if we are compiling PTX
+    if(arch_name MATCHES "(.*)\\+PTX$")
+      set(add_ptx TRUE)
+      set(arch_name ${CMAKE_MATCH_1})
+    endif()
+    if(arch_name MATCHES "^([0-9]\\.[0-9](\\([0-9]\\.[0-9]\\))?)$")
+      set(arch_bin ${CMAKE_MATCH_1})
+      set(arch_ptx ${arch_bin})
+    else()
+      # Look for it in our list of known architectures
+      if(${arch_name} STREQUAL "Fermi")
+        set(arch_bin 2.0 "2.1(2.0)")
+      elseif(${arch_name} STREQUAL "Kepler+Tegra")
+        set(arch_bin 3.2)
+      elseif(${arch_name} STREQUAL "Kepler+Tesla")
+        set(arch_bin 3.7)
+      elseif(${arch_name} STREQUAL "Kepler")
+        set(arch_bin 3.0 3.5)
+        set(arch_ptx 3.5)
+      elseif(${arch_name} STREQUAL "Maxwell+Tegra")
+        set(arch_bin 5.3)
+      elseif(${arch_name} STREQUAL "Maxwell")
+        set(arch_bin 5.0 5.2)
+        set(arch_ptx 5.2)
+      elseif(${arch_name} STREQUAL "Pascal")
+        set(arch_bin 6.0 6.1)
+        set(arch_ptx 6.1)
+      else()
+        message(SEND_ERROR "Unknown CUDA Architecture Name ${arch_name} in CUDA_SELECT_NVCC_ARCH_FLAGS")
+      endif()
+    endif()
+    if(NOT arch_bin)
+      message(SEND_ERROR "arch_bin wasn't set for some reason")
+    endif()
+    list(APPEND cuda_arch_bin ${arch_bin})
+    if(add_ptx)
+      if (NOT arch_ptx)
+        set(arch_ptx ${arch_bin})
+      endif()
+      list(APPEND cuda_arch_ptx ${arch_ptx})
+    endif()
+  endforeach()
+
+  # remove dots and convert to lists
+  string(REGEX REPLACE "\\." "" cuda_arch_bin "${cuda_arch_bin}")
+  string(REGEX REPLACE "\\." "" cuda_arch_ptx "${cuda_arch_ptx}")
+  string(REGEX MATCHALL "[0-9()]+" cuda_arch_bin "${cuda_arch_bin}")
+  string(REGEX MATCHALL "[0-9]+"   cuda_arch_ptx "${cuda_arch_ptx}")
+
+  if(cuda_arch_bin)
+    list(REMOVE_DUPLICATES cuda_arch_bin)
+  endif()
+  if(cuda_arch_ptx)
+    list(REMOVE_DUPLICATES cuda_arch_ptx)
+  endif()
+
+  set(nvcc_flags "")
+  set(nvcc_archs_readable "")
+
+  # Tell NVCC to add binaries for the specified GPUs
+  foreach(arch ${cuda_arch_bin})
+    if(arch MATCHES "([0-9]+)\\(([0-9]+)\\)")
+      # User explicitly specified ARCH for the concrete CODE
+      list(APPEND nvcc_flags -gencode arch=compute_${CMAKE_MATCH_2},code=sm_${CMAKE_MATCH_1})
+      list(APPEND nvcc_archs_readable sm_${CMAKE_MATCH_1})
+    else()
+      # User didn't explicitly specify ARCH for the concrete CODE, we assume ARCH=CODE
+      list(APPEND nvcc_flags -gencode arch=compute_${arch},code=sm_${arch})
+      list(APPEND nvcc_archs_readable sm_${arch})
+    endif()
+  endforeach()
+
+  # Tell NVCC to add PTX intermediate code for the specified architectures
+  foreach(arch ${cuda_arch_ptx})
+    list(APPEND nvcc_flags -gencode arch=compute_${arch},code=compute_${arch})
+    list(APPEND nvcc_archs_readable compute_${arch})
+  endforeach()
+
+  string(REPLACE ";" " " nvcc_archs_readable "${nvcc_archs_readable}")
+  set(${out_variable}          ${nvcc_flags}          PARENT_SCOPE)
+  set(${out_variable}_readable ${nvcc_archs_readable} PARENT_SCOPE)
+endfunction()
diff --git a/Modules/FindCURL.cmake b/Modules/FindCURL.cmake
index 209fd87..200f8c3 100644
--- a/Modules/FindCURL.cmake
+++ b/Modules/FindCURL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCURL
 # --------
@@ -13,20 +16,6 @@
 #   CURL_FOUND          - True if curl found.
 #   CURL_VERSION_STRING - the version of curl found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Look for the header file.
 find_path(CURL_INCLUDE_DIR NAMES curl/curl.h)
 mark_as_advanced(CURL_INCLUDE_DIR)
diff --git a/Modules/FindCVS.cmake b/Modules/FindCVS.cmake
index 6f545df..d59dfb0 100644
--- a/Modules/FindCVS.cmake
+++ b/Modules/FindCVS.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCVS
 # -------
@@ -20,19 +23,6 @@
 #      message("CVS found: ${CVS_EXECUTABLE}")
 #    endif()
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # CVSNT
 
 get_filename_component(
diff --git a/Modules/FindCoin3D.cmake b/Modules/FindCoin3D.cmake
index f90860c..fea644d 100644
--- a/Modules/FindCoin3D.cmake
+++ b/Modules/FindCoin3D.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCoin3D
 # ----------
@@ -15,19 +18,6 @@
 #   COIN3D_INCLUDE_DIRS  - where the Inventor include directory can be found
 #   COIN3D_LIBRARIES     - Link to this to use Coin3D
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (WIN32)
   if (CYGWIN)
 
diff --git a/Modules/FindCups.cmake b/Modules/FindCups.cmake
index 51eb7c5..13d3b98 100644
--- a/Modules/FindCups.cmake
+++ b/Modules/FindCups.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCups
 # --------
@@ -15,21 +18,6 @@
 #   Set CUPS_REQUIRE_IPP_DELETE_ATTRIBUTE to TRUE if you need a version which
 #   features this function (i.e. at least 1.1.19)
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(CUPS_INCLUDE_DIR cups/cups.h )
 
 find_library(CUPS_LIBRARIES NAMES cups )
@@ -55,7 +43,7 @@ if (CUPS_INCLUDE_DIR AND EXISTS "${CUPS_INCLUDE_DIR}/cups/cups.h")
             if(VLINE MATCHES "^#[\t ]*define[\t ]+CUPS_VERSION_${VPART}[\t ]+([0-9]+)$")
                 set(CUPS_VERSION_PART "${CMAKE_MATCH_1}")
                 if(CUPS_VERSION_STRING)
-                    set(CUPS_VERSION_STRING "${CUPS_VERSION_STRING}.${CUPS_VERSION_PART}")
+                    string(APPEND CUPS_VERSION_STRING ".${CUPS_VERSION_PART}")
                 else()
                     set(CUPS_VERSION_STRING "${CUPS_VERSION_PART}")
                 endif()
diff --git a/Modules/FindCurses.cmake b/Modules/FindCurses.cmake
index e236c24..a0929ce 100644
--- a/Modules/FindCurses.cmake
+++ b/Modules/FindCurses.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCurses
 # ----------
@@ -37,19 +40,6 @@
 # ``CURSES_LIBRARY``
 #   Path to Curses library.  Use ``CURSES_LIBRARIES`` instead.
 
-#=============================================================================
-# Copyright 2001-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CheckLibraryExists.cmake)
 
 find_library(CURSES_CURSES_LIBRARY NAMES curses )
diff --git a/Modules/FindCxxTest.cmake b/Modules/FindCxxTest.cmake
index bc0dfbc..9ba1ff3 100644
--- a/Modules/FindCxxTest.cmake
+++ b/Modules/FindCxxTest.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCxxTest
 # -----------
@@ -55,7 +58,8 @@
 #        The test generator that is actually used (chosen using user preferences
 #        and interpreters found in the system)
 #    CXXTEST_TESTGEN_INTERPRETER (since CMake 2.8.3)
-#        The full path to the Perl or Python executable on the system
+#        The full path to the Perl or Python executable on the system, on
+#        platforms where the script cannot be executed using its shebang line.
 #
 #
 #
@@ -134,20 +138,6 @@
 #              }
 #           };
 
-#=============================================================================
-# Copyright 2008-2010 Kitware, Inc.
-# Copyright 2008-2010 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Version 1.4 (11/18/10) (CMake 2.8.4)
 #     Issue 11384: Added support to the CXX_ADD_TEST macro so header
 #                  files (containing the tests themselves) show up in
@@ -221,7 +211,13 @@ if(PYTHONINTERP_FOUND OR PERL_FOUND)
 
    if(PYTHONINTERP_FOUND AND (CXXTEST_USE_PYTHON OR NOT PERL_FOUND OR NOT DEFINED CXXTEST_USE_PYTHON))
       set(CXXTEST_TESTGEN_EXECUTABLE ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE})
-      set(CXXTEST_TESTGEN_INTERPRETER ${PYTHON_EXECUTABLE})
+      execute_process(COMMAND ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE} --version
+        OUTPUT_VARIABLE _CXXTEST_OUT ERROR_VARIABLE _CXXTEST_OUT RESULT_VARIABLE _CXXTEST_RESULT)
+      if(_CXXTEST_RESULT EQUAL 0)
+        set(CXXTEST_TESTGEN_INTERPRETER "")
+      else()
+        set(CXXTEST_TESTGEN_INTERPRETER ${PYTHON_EXECUTABLE})
+      endif()
       FIND_PACKAGE_HANDLE_STANDARD_ARGS(CxxTest DEFAULT_MSG
           CXXTEST_INCLUDE_DIR CXXTEST_PYTHON_TESTGEN_EXECUTABLE)
 
diff --git a/Modules/FindCygwin.cmake b/Modules/FindCygwin.cmake
index 5cb533b..90cbd52 100644
--- a/Modules/FindCygwin.cmake
+++ b/Modules/FindCygwin.cmake
@@ -1,22 +1,12 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindCygwin
 # ----------
 #
 # this module looks for Cygwin
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (WIN32)
   find_path(CYGWIN_INSTALL_PATH
     cygwin.bat
diff --git a/Modules/FindDCMTK.cmake b/Modules/FindDCMTK.cmake
index 63d253d..0d86e8e 100644
--- a/Modules/FindDCMTK.cmake
+++ b/Modules/FindDCMTK.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindDCMTK
 # ---------
@@ -75,21 +78,6 @@
 # Remove DCMTK entry from the CMake cache per :command:`find_package`
 # documentation.
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2009-2010 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-# Copyright 2010 Thomas Sondergaard <ts at medical-insight.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # Written for VXL by Amitha Perera.
 # Upgraded for GDCM by Mathieu Malaterre.
diff --git a/Modules/FindDart.cmake b/Modules/FindDart.cmake
index ea01fc2..37164e6 100644
--- a/Modules/FindDart.cmake
+++ b/Modules/FindDart.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindDart
 # --------
@@ -7,19 +10,6 @@
 # This module looks for the dart testing software and sets DART_ROOT to
 # point to where it found it.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(DART_ROOT README.INSTALL
     HINTS
       ENV DART_ROOT
diff --git a/Modules/FindDevIL.cmake b/Modules/FindDevIL.cmake
index 865d061..dc8e38a 100644
--- a/Modules/FindDevIL.cmake
+++ b/Modules/FindDevIL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindDevIL
 # ---------
@@ -28,20 +31,6 @@
 #                     library is found all the others are as well. That's the
 #                     way the DevIL developers release it.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-# Copyright 2008 Christopher Harvey
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # TODO: Add version support.
 # Tested under Linux and Windows (MSVC)
 
diff --git a/Modules/FindDoxygen.cmake b/Modules/FindDoxygen.cmake
index d34941a..8275ac8 100644
--- a/Modules/FindDoxygen.cmake
+++ b/Modules/FindDoxygen.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindDoxygen
 # -----------
@@ -41,19 +44,6 @@
 # perhaps the :command:`file(TO_NATIVE_PATH)` command to prepare
 # the path for a Doxygen configuration file.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # For backwards compatibility support
 if(Doxygen_FIND_QUIETLY)
   set(DOXYGEN_FIND_QUIETLY TRUE)
diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake
index 653094c..cc89203 100644
--- a/Modules/FindEXPAT.cmake
+++ b/Modules/FindEXPAT.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindEXPAT
 # ---------
@@ -12,24 +15,15 @@
 #   EXPAT_LIBRARIES    - List of libraries when using expat.
 #   EXPAT_FOUND        - True if expat found.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+find_package(PkgConfig QUIET)
+
+pkg_check_modules(PC_EXPAT QUIET expat)
 
 # Look for the header file.
-find_path(EXPAT_INCLUDE_DIR NAMES expat.h)
+find_path(EXPAT_INCLUDE_DIR NAMES expat.h HINTS ${PC_EXPAT_INCLUDE_DIRS})
 
 # Look for the library.
-find_library(EXPAT_LIBRARY NAMES expat libexpat)
+find_library(EXPAT_LIBRARY NAMES expat libexpat HINTS ${PC_EXPAT_LIBRARY_DIRS})
 
 if (EXPAT_INCLUDE_DIR AND EXISTS "${EXPAT_INCLUDE_DIR}/expat.h")
     file(STRINGS "${EXPAT_INCLUDE_DIR}/expat.h" expat_version_str
@@ -41,7 +35,7 @@ if (EXPAT_INCLUDE_DIR AND EXISTS "${EXPAT_INCLUDE_DIR}/expat.h")
             if(VLINE MATCHES "^#[\t ]*define[\t ]+XML_${VPART}_VERSION[\t ]+([0-9]+)$")
                 set(EXPAT_VERSION_PART "${CMAKE_MATCH_1}")
                 if(EXPAT_VERSION_STRING)
-                    set(EXPAT_VERSION_STRING "${EXPAT_VERSION_STRING}.${EXPAT_VERSION_PART}")
+                    string(APPEND EXPAT_VERSION_STRING ".${EXPAT_VERSION_PART}")
                 else()
                     set(EXPAT_VERSION_STRING "${EXPAT_VERSION_PART}")
                 endif()
diff --git a/Modules/FindFLEX.cmake b/Modules/FindFLEX.cmake
index b50c74a..69cf513 100644
--- a/Modules/FindFLEX.cmake
+++ b/Modules/FindFLEX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindFLEX
 # --------
@@ -93,20 +96,6 @@
 #    )
 #   ====================================================================
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2006 Tristan Carel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(FLEX_EXECUTABLE NAMES flex win_flex DOC "path to the flex executable")
 mark_as_advanced(FLEX_EXECUTABLE)
 
diff --git a/Modules/FindFLTK.cmake b/Modules/FindFLTK.cmake
index ad0bf98..e6bd3c9 100644
--- a/Modules/FindFLTK.cmake
+++ b/Modules/FindFLTK.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindFLTK
 # --------
@@ -54,19 +57,6 @@
 #      FLTK_FORMS_LIBRARY  = the full path to fltk_forms.lib
 #      FLTK_IMAGES_LIBRARY = the full path to fltk_images.lib
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT FLTK_SKIP_OPENGL)
   find_package(OpenGL)
 endif()
diff --git a/Modules/FindFLTK2.cmake b/Modules/FindFLTK2.cmake
index 154729f..a43e5ff 100644
--- a/Modules/FindFLTK2.cmake
+++ b/Modules/FindFLTK2.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindFLTK2
 # ---------
@@ -22,19 +25,6 @@
 #   FLTK2_GL_LIBRARY     = the full path to fltk2_gl.lib
 #   FLTK2_IMAGES_LIBRARY = the full path to fltk2_images.lib
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set (FLTK2_DIR $ENV{FLTK2_DIR} )
 
 #  Platform dependent libraries required by FLTK2
diff --git a/Modules/FindFreetype.cmake b/Modules/FindFreetype.cmake
index 7d46d15..21a5d89 100644
--- a/Modules/FindFreetype.cmake
+++ b/Modules/FindFreetype.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindFreetype
 # ------------
@@ -21,19 +24,6 @@
 # $FREETYPE_DIR is an environment variable that would correspond to the
 # ./configure --prefix=$FREETYPE_DIR used in building FREETYPE.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Created by Eric Wing.
 # Modifications by Alexander Neundorf.
 # This file has been renamed to "FindFreetype.cmake" instead of the correct
@@ -51,9 +41,8 @@
 # wants explicit full paths and this trickery doesn't work too well.
 # I'm going to attempt to cut out the middleman and hope
 # everything still works.
-find_path(
-  FREETYPE_INCLUDE_DIR_ft2build
-  ft2build.h
+
+set(FREETYPE_FIND_ARGS
   HINTS
     ENV FREETYPE_DIR
   PATHS
@@ -64,6 +53,12 @@ find_path(
     ENV GTKMM_BASEPATH
     [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path]
     [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path]
+)
+
+find_path(
+  FREETYPE_INCLUDE_DIR_ft2build
+  ft2build.h
+  ${FREETYPE_FIND_ARGS}
   PATH_SUFFIXES
     include/freetype2
     include
@@ -75,40 +70,37 @@ find_path(
   NAMES
     freetype/config/ftheader.h
     config/ftheader.h
-  HINTS
-    ENV FREETYPE_DIR
-  PATHS
-    /usr/X11R6
-    /usr/local/X11R6
-    /usr/local/X11
-    /usr/freeware
-    ENV GTKMM_BASEPATH
-    [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path]
-    [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path]
+  ${FREETYPE_FIND_ARGS}
   PATH_SUFFIXES
     include/freetype2
     include
     freetype2
 )
 
-find_library(FREETYPE_LIBRARY
-  NAMES
-    freetype
-    libfreetype
-    freetype219
-  HINTS
-    ENV FREETYPE_DIR
-  PATHS
-    /usr/X11R6
-    /usr/local/X11R6
-    /usr/local/X11
-    /usr/freeware
-    ENV GTKMM_BASEPATH
-    [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path]
-    [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path]
-  PATH_SUFFIXES
-    lib
-)
+if(NOT FREETYPE_LIBRARY)
+  find_library(FREETYPE_LIBRARY_RELEASE
+    NAMES
+      freetype
+      libfreetype
+      freetype219
+    ${FREETYPE_FIND_ARGS}
+    PATH_SUFFIXES
+      lib
+  )
+  find_library(FREETYPE_LIBRARY_DEBUG
+    NAMES
+      freetyped
+      libfreetyped
+      freetype219d
+    ${FREETYPE_FIND_ARGS}
+    PATH_SUFFIXES
+      lib
+  )
+  include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
+  select_library_configurations(FREETYPE)
+endif()
+
+unset(FREETYPE_FIND_ARGS)
 
 # set the user variables
 if(FREETYPE_INCLUDE_DIR_ft2build AND FREETYPE_INCLUDE_DIR_freetype2)
@@ -133,7 +125,7 @@ if(FREETYPE_INCLUDE_DIR_freetype2 AND FREETYPE_H)
       if(VLINE MATCHES "^#[\t ]*define[\t ]+FREETYPE_${VPART}[\t ]+([0-9]+)$")
         set(FREETYPE_VERSION_PART "${CMAKE_MATCH_1}")
         if(FREETYPE_VERSION_STRING)
-          set(FREETYPE_VERSION_STRING "${FREETYPE_VERSION_STRING}.${FREETYPE_VERSION_PART}")
+          string(APPEND FREETYPE_VERSION_STRING ".${FREETYPE_VERSION_PART}")
         else()
           set(FREETYPE_VERSION_STRING "${FREETYPE_VERSION_PART}")
         endif()
@@ -158,7 +150,6 @@ find_package_handle_standard_args(
 )
 
 mark_as_advanced(
-  FREETYPE_LIBRARY
   FREETYPE_INCLUDE_DIR_freetype2
   FREETYPE_INCLUDE_DIR_ft2build
 )
diff --git a/Modules/FindGCCXML.cmake b/Modules/FindGCCXML.cmake
index 48618e2..1f8d738 100644
--- a/Modules/FindGCCXML.cmake
+++ b/Modules/FindGCCXML.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGCCXML
 # ----------
@@ -12,19 +15,6 @@
 #
 #   GCCXML - the GCC-XML front-end executable.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(GCCXML
   NAMES gccxml
         ../GCC_XML/gccxml
diff --git a/Modules/FindGDAL.cmake b/Modules/FindGDAL.cmake
index bf374f9..0cce9cb 100644
--- a/Modules/FindGDAL.cmake
+++ b/Modules/FindGDAL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGDAL
 # --------
@@ -22,19 +25,6 @@
 #     GDAL_LIBRARY - A variable pointing to the GDAL library
 #     GDAL_INCLUDE_DIR - Where to find the headers
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # $GDALDIR is an environment variable that would
 # correspond to the ./configure --prefix=$GDAL_DIR
diff --git a/Modules/FindGIF.cmake b/Modules/FindGIF.cmake
index 7bbb8cf..88c4180 100644
--- a/Modules/FindGIF.cmake
+++ b/Modules/FindGIF.cmake
@@ -1,13 +1,22 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGIF
 # -------
 #
+# This finds the GIF library (giflib)
 #
+# The module defines the following variables:
 #
-# This module searches giflib and defines GIF_LIBRARIES - libraries to
-# link to in order to use GIF GIF_FOUND, if false, do not try to link
-# GIF_INCLUDE_DIR, where to find the headers GIF_VERSION, reports either
-# version 4 or 3 (for everything before version 4)
+# ``GIF_FOUND``
+#   True if giflib was found
+# ``GIF_LIBRARIES``
+#   Libraries to link to in order to use giflib
+# ``GIF_INCLUDE_DIR``
+#   where to find the headers
+# ``GIF_VERSION``
+#   3, 4 or a full version string (eg 5.1.4) for versions >= 4.1.6
 #
 # The minimum required version of giflib can be specified using the
 # standard syntax, e.g.  find_package(GIF 4)
@@ -15,21 +24,8 @@
 # $GIF_DIR is an environment variable that would correspond to the
 # ./configure --prefix=$GIF_DIR
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Created by Eric Wing.
-# Modifications by Alexander Neundorf
+# Modifications by Alexander Neundorf, Ben Campbell
 
 find_path(GIF_INCLUDE_DIR gif_lib.h
   HINTS
@@ -61,22 +57,40 @@ set(GIF_LIBRARIES ${GIF_LIBRARY})
 # to be always " Version 2.0, " in versions 3.x of giflib.
 # In version 4 the member UserData was added to GifFileType, so we check for this
 # one.
-# http://giflib.sourcearchive.com/documentation/4.1.4/files.html
+# Versions after 4.1.6 define GIFLIB_MAJOR, GIFLIB_MINOR, and GIFLIB_RELEASE
+# see http://giflib.sourceforge.net/gif_lib.html#compatibility
 if(GIF_INCLUDE_DIR)
   include(${CMAKE_CURRENT_LIST_DIR}/CMakePushCheckState.cmake)
   include(${CMAKE_CURRENT_LIST_DIR}/CheckStructHasMember.cmake)
   CMAKE_PUSH_CHECK_STATE()
   set(CMAKE_REQUIRED_QUIET ${GIF_FIND_QUIETLY})
-  set(GIF_VERSION 3)
   set(CMAKE_REQUIRED_INCLUDES "${GIF_INCLUDE_DIR}")
-  CHECK_STRUCT_HAS_MEMBER(GifFileType UserData gif_lib.h GIF_GifFileType_UserData )
-  if(GIF_GifFileType_UserData)
-    set(GIF_VERSION 4)
+
+  # Check for the specific version defines (>=4.1.6 only)
+  file(STRINGS ${GIF_INCLUDE_DIR}/gif_lib.h _GIF_DEFS REGEX "^[ \t]*#define[ \t]+GIFLIB_(MAJOR|MINOR|RELEASE)")
+  if(_GIF_DEFS)
+    # yay - got exact version info
+    string(REGEX REPLACE ".*GIFLIB_MAJOR ([0-9]+).*" "\\1" _GIF_MAJ "${_GIF_DEFS}")
+    string(REGEX REPLACE ".*GIFLIB_MINOR ([0-9]+).*" "\\1" _GIF_MIN "${_GIF_DEFS}")
+    string(REGEX REPLACE ".*GIFLIB_RELEASE ([0-9]+).*" "\\1" _GIF_REL "${_GIF_DEFS}")
+    set(GIF_VERSION "${_GIF_MAJ}.${_GIF_MIN}.${_GIF_REL}")
+  else()
+    # use UserData field to sniff version instead
+    CHECK_STRUCT_HAS_MEMBER(GifFileType UserData gif_lib.h GIF_GifFileType_UserData )
+    if(GIF_GifFileType_UserData)
+      set(GIF_VERSION 4)
+    else()
+      set(GIF_VERSION 3)
+    endif()
   endif()
+
+  unset(_GIF_MAJ)
+  unset(_GIF_MIN)
+  unset(_GIF_REL)
+  unset(_GIF_DEFS)
   CMAKE_POP_CHECK_STATE()
 endif()
 
-
 # handle the QUIETLY and REQUIRED arguments and set GIF_FOUND to TRUE if
 # all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
diff --git a/Modules/FindGLEW.cmake b/Modules/FindGLEW.cmake
index f42182f..d8609e6 100644
--- a/Modules/FindGLEW.cmake
+++ b/Modules/FindGLEW.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGLEW
 # --------
@@ -21,34 +24,46 @@
 #   GLEW_LIBRARIES - libraries to link against GLEW
 #   GLEW_FOUND - true if GLEW has been found and can be used
 
-#=============================================================================
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(GLEW_INCLUDE_DIR GL/glew.h)
-find_library(GLEW_LIBRARY NAMES GLEW glew32 glew glew32s PATH_SUFFIXES lib64)
 
-set(GLEW_INCLUDE_DIRS ${GLEW_INCLUDE_DIR})
-set(GLEW_LIBRARIES ${GLEW_LIBRARY})
+if(NOT GLEW_LIBRARY)
+  find_library(GLEW_LIBRARY_RELEASE NAMES GLEW glew32 glew glew32s PATH_SUFFIXES lib64)
+  find_library(GLEW_LIBRARY_DEBUG NAMES GLEWd glew32d glewd PATH_SUFFIXES lib64)
+
+  include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
+  select_library_configurations(GLEW)
+endif ()
 
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(GLEW
                                   REQUIRED_VARS GLEW_INCLUDE_DIR GLEW_LIBRARY)
 
-if(GLEW_FOUND AND NOT TARGET GLEW::GLEW)
-  add_library(GLEW::GLEW UNKNOWN IMPORTED)
-  set_target_properties(GLEW::GLEW PROPERTIES
-    IMPORTED_LOCATION "${GLEW_LIBRARY}"
-    INTERFACE_INCLUDE_DIRECTORIES "${GLEW_INCLUDE_DIRS}")
+if(GLEW_FOUND)
+  set(GLEW_INCLUDE_DIRS ${GLEW_INCLUDE_DIR})
+
+  if(NOT GLEW_LIBRARIES)
+    set(GLEW_LIBRARIES ${GLEW_LIBRARY})
+  endif()
+
+  if (NOT TARGET GLEW::GLEW)
+    add_library(GLEW::GLEW UNKNOWN IMPORTED)
+    set_target_properties(GLEW::GLEW PROPERTIES
+      INTERFACE_INCLUDE_DIRECTORIES "${GLEW_INCLUDE_DIRS}")
+
+    if(GLEW_LIBRARY_RELEASE)
+      set_property(TARGET GLEW::GLEW APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+      set_target_properties(GLEW::GLEW PROPERTIES IMPORTED_LOCATION_RELEASE "${GLEW_LIBRARY_RELEASE}")
+    endif()
+
+    if(GLEW_LIBRARY_DEBUG)
+      set_property(TARGET GLEW::GLEW APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(GLEW::GLEW PROPERTIES IMPORTED_LOCATION_DEBUG "${GLEW_LIBRARY_DEBUG}")
+    endif()
+
+    if(NOT GLEW_LIBRARY_RELEASE AND NOT GLEW_LIBRARY_DEBUG)
+      set_property(TARGET GLEW::GLEW APPEND PROPERTY IMPORTED_LOCATION "${GLEW_LIBRARY}")
+    endif()
+  endif()
 endif()
 
-mark_as_advanced(GLEW_INCLUDE_DIR GLEW_LIBRARY)
+mark_as_advanced(GLEW_INCLUDE_DIR)
diff --git a/Modules/FindGLU.cmake b/Modules/FindGLU.cmake
index 0d36fad..dbec6d1 100644
--- a/Modules/FindGLU.cmake
+++ b/Modules/FindGLU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Use of this file is deprecated, and is here for backwards compatibility with CMake 1.4
 # GLU library is now found by FindOpenGL.cmake
diff --git a/Modules/FindGLUT.cmake b/Modules/FindGLUT.cmake
index c9f7597..02e6df0 100644
--- a/Modules/FindGLUT.cmake
+++ b/Modules/FindGLUT.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGLUT
 # --------
@@ -31,19 +34,6 @@
 #   GLUT_Xmu_LIBRARY  = the full path to the Xmu library.
 #   GLUT_Xi_LIBRARY   = the full path to the Xi Library.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (WIN32)
   find_path( GLUT_INCLUDE_DIR NAMES GL/glut.h
     PATHS  ${GLUT_ROOT_PATH}/include )
diff --git a/Modules/FindGSL.cmake b/Modules/FindGSL.cmake
index 9318a7d..98377a2 100644
--- a/Modules/FindGSL.cmake
+++ b/Modules/FindGSL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGSL
 # --------
@@ -52,19 +55,6 @@
 #  GSL_LIBRARY_DEBUG       - Location of the debug GSL library (if any).
 #
 
-#=============================================================================
-# Copyright 2014 Kelly Thompson <kgt at lanl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Include these modules to handle the QUIETLY and REQUIRED arguments.
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
diff --git a/Modules/FindGTK.cmake b/Modules/FindGTK.cmake
index 01bca76..8a89cda 100644
--- a/Modules/FindGTK.cmake
+++ b/Modules/FindGTK.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGTK
 # -------
@@ -11,19 +14,6 @@
 #   GTK_FOUND         - GTK was found
 #   GTK_GL_FOUND      - GTK's GL features were found
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # don't even bother under WIN32
 if(UNIX)
 
diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake
index 6e4a7f2..78dc6ba 100644
--- a/Modules/FindGTK2.cmake
+++ b/Modules/FindGTK2.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGTK2
 # --------
@@ -95,20 +98,6 @@
 #       target_link_libraries(mygui ${GTK2_LIBRARIES})
 #    endif()
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2008-2012 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Version 1.6 (CMake 3.0)
 #   * Create targets for each library
 #   * Do not link libfreetype
diff --git a/Modules/FindGTest.cmake b/Modules/FindGTest.cmake
index a7ffcfe..76ab716 100644
--- a/Modules/FindGTest.cmake
+++ b/Modules/FindGTest.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGTest
 # ---------
@@ -90,20 +93,6 @@
 #      add_executable(FooTest FooUnitTest.cc)
 #      GTEST_ADD_TESTS(FooTest "${FooTestArgs}" AUTO)
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009 Philip Lowman <philip at yhbt.com>
-# Copyright 2009 Daniel Blezek <blezek at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 #
 # Thanks to Daniel Blezek <blezek at gmail.com> for the GTEST_ADD_TESTS code
 
@@ -226,13 +215,6 @@ if(GTEST_FOUND)
                 IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
                 IMPORTED_LOCATION "${GTEST_LIBRARY}")
         endif()
-        if(EXISTS "${GTEST_LIBRARY_DEBUG}")
-            set_property(TARGET GTest::GTest APPEND PROPERTY
-                IMPORTED_CONFIGURATIONS DEBUG)
-            set_target_properties(GTest::GTest PROPERTIES
-                IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
-                IMPORTED_LOCATION_DEBUG "${GTEST_LIBRARY_DEBUG}")
-        endif()
         if(EXISTS "${GTEST_LIBRARY_RELEASE}")
             set_property(TARGET GTest::GTest APPEND PROPERTY
                 IMPORTED_CONFIGURATIONS RELEASE)
@@ -240,6 +222,13 @@ if(GTEST_FOUND)
                 IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
                 IMPORTED_LOCATION_RELEASE "${GTEST_LIBRARY_RELEASE}")
         endif()
+        if(EXISTS "${GTEST_LIBRARY_DEBUG}")
+            set_property(TARGET GTest::GTest APPEND PROPERTY
+                IMPORTED_CONFIGURATIONS DEBUG)
+            set_target_properties(GTest::GTest PROPERTIES
+                IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+                IMPORTED_LOCATION_DEBUG "${GTEST_LIBRARY_DEBUG}")
+        endif()
       endif()
       if(NOT TARGET GTest::Main)
           add_library(GTest::Main UNKNOWN IMPORTED)
@@ -250,13 +239,6 @@ if(GTEST_FOUND)
                   IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
                   IMPORTED_LOCATION "${GTEST_MAIN_LIBRARY}")
           endif()
-          if(EXISTS "${GTEST_MAIN_LIBRARY_DEBUG}")
-            set_property(TARGET GTest::Main APPEND PROPERTY
-                IMPORTED_CONFIGURATIONS DEBUG)
-            set_target_properties(GTest::Main PROPERTIES
-                IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
-                IMPORTED_LOCATION_DEBUG "${GTEST_MAIN_LIBRARY_DEBUG}")
-          endif()
           if(EXISTS "${GTEST_MAIN_LIBRARY_RELEASE}")
             set_property(TARGET GTest::Main APPEND PROPERTY
                 IMPORTED_CONFIGURATIONS RELEASE)
@@ -264,5 +246,12 @@ if(GTEST_FOUND)
                 IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
                 IMPORTED_LOCATION_RELEASE "${GTEST_MAIN_LIBRARY_RELEASE}")
           endif()
+          if(EXISTS "${GTEST_MAIN_LIBRARY_DEBUG}")
+            set_property(TARGET GTest::Main APPEND PROPERTY
+                IMPORTED_CONFIGURATIONS DEBUG)
+            set_target_properties(GTest::Main PROPERTIES
+                IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+                IMPORTED_LOCATION_DEBUG "${GTEST_MAIN_LIBRARY_DEBUG}")
+          endif()
     endif()
 endif()
diff --git a/Modules/FindGettext.cmake b/Modules/FindGettext.cmake
index ac53c3f..7718468 100644
--- a/Modules/FindGettext.cmake
+++ b/Modules/FindGettext.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGettext
 # -----------
@@ -54,20 +57,6 @@
 # .. note::
 #   If you wish to use the Gettext library (libintl), use :module:`FindIntl`.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2007      Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(GETTEXT_MSGMERGE_EXECUTABLE msgmerge)
 
 find_program(GETTEXT_MSGFMT_EXECUTABLE msgfmt)
diff --git a/Modules/FindGit.cmake b/Modules/FindGit.cmake
index 95188ce..5d38193 100644
--- a/Modules/FindGit.cmake
+++ b/Modules/FindGit.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGit
 # -------
@@ -20,20 +23,6 @@
 #      message("Git found: ${GIT_EXECUTABLE}")
 #    endif()
 
-#=============================================================================
-# Copyright 2010-2016 Kitware, Inc.
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Look for 'git' or 'eg' (easy git)
 #
 set(git_names git eg)
diff --git a/Modules/FindGnuTLS.cmake b/Modules/FindGnuTLS.cmake
index 4d94ffc..a6ab092 100644
--- a/Modules/FindGnuTLS.cmake
+++ b/Modules/FindGnuTLS.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGnuTLS
 # ----------
@@ -15,22 +18,6 @@
 #   GNUTLS_LIBRARIES - The libraries needed to use gnutls
 #   GNUTLS_DEFINITIONS - Compiler switches required for using gnutls
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009 Philip Lowman <philip at yhbt.com>
-# Copyright 2009 Brad Hards <bradh at kde.org>
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Note that this doesn't try to find the gnutls-extra package.
 
 
diff --git a/Modules/FindGnuplot.cmake b/Modules/FindGnuplot.cmake
index 067604f..9ace651 100644
--- a/Modules/FindGnuplot.cmake
+++ b/Modules/FindGnuplot.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindGnuplot
 # -----------
@@ -18,19 +21,6 @@
 #
 # GNUPLOT_VERSION_STRING will not work for old versions like 3.7.1.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindCygwin.cmake)
 
 find_program(GNUPLOT_EXECUTABLE
diff --git a/Modules/FindHDF5.cmake b/Modules/FindHDF5.cmake
index ab046e3..1c2c443 100644
--- a/Modules/FindHDF5.cmake
+++ b/Modules/FindHDF5.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindHDF5
 # --------
@@ -88,20 +91,6 @@
 #
 # HDF5_ROOT
 
-#=============================================================================
-# Copyright 2015 Axel Huebl, Helmholtz-Zentrum Dresden - Rossendorf
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # This module is maintained by Will Dicharry <wdicharry at stellarscience.com>.
 
 include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
@@ -691,7 +680,7 @@ if( NOT HDF5_FOUND )
             if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
                 # According to bug 1643 on the CMake bug tracker, this is the
                 # preferred method for searching for a static library.
-                # See https://cmake.org/Bug/view.php?id=1643.  We search
+                # See https://gitlab.kitware.com/cmake/cmake/issues/1643.  We search
                 # first for the full static library name, but fall back to a
                 # generic search on the name if the static search fails.
                 set( THIS_LIBRARY_SEARCH_DEBUG
@@ -728,7 +717,7 @@ if( NOT HDF5_FOUND )
                 if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
                     # According to bug 1643 on the CMake bug tracker, this is the
                     # preferred method for searching for a static library.
-                    # See https://cmake.org/Bug/view.php?id=1643.  We search
+                    # See https://gitlab.kitware.com/cmake/cmake/issues/1643.  We search
                     # first for the full static library name, but fall back to a
                     # generic search on the name if the static search fails.
                     set( THIS_LIBRARY_SEARCH_DEBUG
diff --git a/Modules/FindHSPELL.cmake b/Modules/FindHSPELL.cmake
index 2316533..72d70ad 100644
--- a/Modules/FindHSPELL.cmake
+++ b/Modules/FindHSPELL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindHSPELL
 # ----------
@@ -21,20 +24,6 @@
 #   HSPELL_MAJOR_VERSION  - the major version of Hspell
 #   HSPELL_MINOR_VERSION  - The minor version of Hspell
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(HSPELL_INCLUDE_DIR hspell.h)
 
 find_library(HSPELL_LIBRARIES NAMES hspell)
diff --git a/Modules/FindHTMLHelp.cmake b/Modules/FindHTMLHelp.cmake
index 4e39a34..84e2458 100644
--- a/Modules/FindHTMLHelp.cmake
+++ b/Modules/FindHTMLHelp.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindHTMLHelp
 # ------------
@@ -12,19 +15,6 @@
 #    HTML_HELP_INCLUDE_PATH : include path to the API (htmlhelp.h)
 #    HTML_HELP_LIBRARY      : full path to the library (htmlhelp.lib)
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(WIN32)
 
   find_program(HTML_HELP_COMPILER
diff --git a/Modules/FindHg.cmake b/Modules/FindHg.cmake
index bdbb79b..ef85abc 100644
--- a/Modules/FindHg.cmake
+++ b/Modules/FindHg.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindHg
 # ------
@@ -38,21 +41,6 @@
 #      message("Current changeset is ${Project_WC_CHANGESET}")
 #    endif()
 
-#=============================================================================
-# Copyright 2010-2012 Kitware, Inc.
-# Copyright 2012      Rolf Eike Beer <eike at sf-mail.de>
-# Copyright 2014      Matthaeus G. Chajdas
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(HG_EXECUTABLE
   NAMES hg
   PATHS
diff --git a/Modules/FindICU.cmake b/Modules/FindICU.cmake
new file mode 100644
index 0000000..36dd67e
--- /dev/null
+++ b/Modules/FindICU.cmake
@@ -0,0 +1,349 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#.rst:
+# FindICU
+# -------
+#
+# Find the International Components for Unicode (ICU) libraries and
+# programs.
+#
+# This module supports multiple components.
+# Components can include any of: ``data``, ``i18n``, ``io``, ``le``,
+# ``lx``, ``test``, ``tu`` and ``uc``.
+#
+# Note that on Windows ``data`` is named ``dt`` and ``i18n`` is named
+# ``in``; any of the names may be used, and the appropriate
+# platform-specific library name will be automatically selected.
+#
+# This module reports information about the ICU installation in
+# several variables.  General variables::
+#
+#   ICU_VERSION - ICU release version
+#   ICU_FOUND - true if the main programs and libraries were found
+#   ICU_LIBRARIES - component libraries to be linked
+#   ICU_INCLUDE_DIRS - the directories containing the ICU headers
+#
+# Imported targets::
+#
+#   ICU::<C>
+#
+# Where ``<C>`` is the name of an ICU component, for example
+# ``ICU::i18n``.
+#
+# ICU programs are reported in::
+#
+#   ICU_GENCNVAL_EXECUTABLE - path to gencnval executable
+#   ICU_ICUINFO_EXECUTABLE - path to icuinfo executable
+#   ICU_GENBRK_EXECUTABLE - path to genbrk executable
+#   ICU_ICU-CONFIG_EXECUTABLE - path to icu-config executable
+#   ICU_GENRB_EXECUTABLE - path to genrb executable
+#   ICU_GENDICT_EXECUTABLE - path to gendict executable
+#   ICU_DERB_EXECUTABLE - path to derb executable
+#   ICU_PKGDATA_EXECUTABLE - path to pkgdata executable
+#   ICU_UCONV_EXECUTABLE - path to uconv executable
+#   ICU_GENCFU_EXECUTABLE - path to gencfu executable
+#   ICU_MAKECONV_EXECUTABLE - path to makeconv executable
+#   ICU_GENNORM2_EXECUTABLE - path to gennorm2 executable
+#   ICU_GENCCODE_EXECUTABLE - path to genccode executable
+#   ICU_GENSPREP_EXECUTABLE - path to gensprep executable
+#   ICU_ICUPKG_EXECUTABLE - path to icupkg executable
+#   ICU_GENCMN_EXECUTABLE - path to gencmn executable
+#
+# ICU component libraries are reported in::
+#
+#   ICU_<C>_FOUND - ON if component was found
+#   ICU_<C>_LIBRARIES - libraries for component
+#
+# Note that ``<C>`` is the uppercased name of the component.
+#
+# This module reads hints about search results from::
+#
+#   ICU_ROOT - the root of the ICU installation
+#
+# The environment variable ``ICU_ROOT`` may also be used; the
+# ICU_ROOT variable takes precedence.
+#
+# The following cache variables may also be set::
+#
+#   ICU_<P>_EXECUTABLE - the path to executable <P>
+#   ICU_INCLUDE_DIR - the directory containing the ICU headers
+#   ICU_<C>_LIBRARY - the library for component <C>
+#
+# .. note::
+#
+#   In most cases none of the above variables will require setting,
+#   unless multiple ICU versions are available and a specific version
+#   is required.
+#
+# Other variables one may set to control this module are::
+#
+#   ICU_DEBUG - Set to ON to enable debug output from FindICU.
+
+# Written by Roger Leigh <rleigh at codelibre.net>
+
+set(icu_programs
+  gencnval
+  icuinfo
+  genbrk
+  icu-config
+  genrb
+  gendict
+  derb
+  pkgdata
+  uconv
+  gencfu
+  makeconv
+  gennorm2
+  genccode
+  gensprep
+  icupkg
+  gencmn)
+
+# The ICU checks are contained in a function due to the large number
+# of temporary variables needed.
+function(_ICU_FIND)
+  # Set up search paths, taking compiler into account.  Search ICU_ROOT,
+  # with ICU_ROOT in the environment as a fallback if unset.
+  if(ICU_ROOT)
+    list(APPEND icu_roots "${ICU_ROOT}")
+  else()
+    if(NOT "$ENV{ICU_ROOT}" STREQUAL "")
+      file(TO_CMAKE_PATH "$ENV{ICU_ROOT}" NATIVE_PATH)
+      list(APPEND icu_roots "${NATIVE_PATH}")
+      set(ICU_ROOT "${NATIVE_PATH}"
+          CACHE PATH "Location of the ICU installation" FORCE)
+    endif()
+  endif()
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+    # 64-bit binary directory
+    set(_bin64 "bin64")
+    # 64-bit library directory
+    set(_lib64 "lib64")
+  endif()
+
+  # Generic 64-bit and 32-bit directories
+  list(APPEND icu_binary_suffixes "${_bin64}" "bin")
+  list(APPEND icu_library_suffixes "${_lib64}" "lib")
+
+  # Find all ICU programs
+  foreach(program ${icu_programs})
+    string(TOUPPER "${program}" program_upcase)
+    set(cache_var "ICU_${program_upcase}_EXECUTABLE")
+    set(program_var "ICU_${program_upcase}_EXECUTABLE")
+    find_program("${cache_var}" "${program}"
+      HINTS ${icu_roots}
+      PATH_SUFFIXES ${icu_binary_suffixes}
+      DOC "ICU ${program} executable")
+    mark_as_advanced(cache_var)
+    set("${program_var}" "${${cache_var}}" PARENT_SCOPE)
+  endforeach()
+
+  # Find include directory
+  find_path(ICU_INCLUDE_DIR
+            NAMES "unicode/utypes.h"
+            HINTS ${icu_roots}
+            PATH_SUFFIXES ${icu_include_suffixes}
+            DOC "ICU include directory")
+  set(ICU_INCLUDE_DIR "${ICU_INCLUDE_DIR}" PARENT_SCOPE)
+
+  # Get version
+  if(ICU_INCLUDE_DIR AND EXISTS "${ICU_INCLUDE_DIR}/unicode/uvernum.h")
+    file(STRINGS "${ICU_INCLUDE_DIR}/unicode/uvernum.h" icu_header_str
+      REGEX "^#define[\t ]+U_ICU_VERSION[\t ]+\".*\".*")
+
+    string(REGEX REPLACE "^#define[\t ]+U_ICU_VERSION[\t ]+\"([^ \\n]*)\".*"
+      "\\1" icu_version_string "${icu_header_str}")
+    set(ICU_VERSION "${icu_version_string}" PARENT_SCOPE)
+    unset(icu_header_str)
+    unset(icu_version_string)
+  endif()
+
+  # Find all ICU libraries
+  set(ICU_REQUIRED_LIBS_FOUND ON)
+  foreach(component ${ICU_FIND_COMPONENTS})
+    string(TOUPPER "${component}" component_upcase)
+    set(component_cache "ICU_${component_upcase}_LIBRARY")
+    set(component_cache_release "${component_cache}_RELEASE")
+    set(component_cache_debug "${component_cache}_DEBUG")
+    set(component_found "${component_upcase}_FOUND")
+    set(component_libnames "icu${component}")
+    set(component_debug_libnames "icu${component}d")
+
+    # Special case deliberate library naming mismatches between Unix
+    # and Windows builds
+    unset(component_libnames)
+    unset(component_debug_libnames)
+    list(APPEND component_libnames "icu${component}")
+    list(APPEND component_debug_libnames "icu${component}d")
+    if(component STREQUAL "data")
+      list(APPEND component_libnames "icudt")
+      # Note there is no debug variant at present
+      list(APPEND component_debug_libnames "icudtd")
+    endif()
+    if(component STREQUAL "dt")
+      list(APPEND component_libnames "icudata")
+      # Note there is no debug variant at present
+      list(APPEND component_debug_libnames "icudatad")
+    endif()
+    if(component STREQUAL "i18n")
+      list(APPEND component_libnames "icuin")
+      list(APPEND component_debug_libnames "icuind")
+    endif()
+    if(component STREQUAL "in")
+      list(APPEND component_libnames "icui18n")
+      list(APPEND component_debug_libnames "icui18nd")
+    endif()
+
+    find_library("${component_cache_release}" ${component_libnames}
+      HINTS ${icu_roots}
+      PATH_SUFFIXES ${icu_library_suffixes}
+      DOC "ICU ${component} library (release)")
+    find_library("${component_cache_debug}" ${component_debug_libnames}
+      HINTS ${icu_roots}
+      PATH_SUFFIXES ${icu_library_suffixes}
+      DOC "ICU ${component} library (debug)")
+    include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
+    select_library_configurations(ICU_${component_upcase})
+    mark_as_advanced("${component_cache_release}" "${component_cache_debug}")
+    if(${component_cache})
+      set("${component_found}" ON)
+      list(APPEND ICU_LIBRARY "${${component_cache}}")
+    endif()
+    mark_as_advanced("${component_found}")
+    set("${component_cache}" "${${component_cache}}" PARENT_SCOPE)
+    set("${component_found}" "${${component_found}}" PARENT_SCOPE)
+    if(${component_found})
+      if (ICU_FIND_REQUIRED_${component})
+        list(APPEND ICU_LIBS_FOUND "${component} (required)")
+      else()
+        list(APPEND ICU_LIBS_FOUND "${component} (optional)")
+      endif()
+    else()
+      if (ICU_FIND_REQUIRED_${component})
+        set(ICU_REQUIRED_LIBS_FOUND OFF)
+        list(APPEND ICU_LIBS_NOTFOUND "${component} (required)")
+      else()
+        list(APPEND ICU_LIBS_NOTFOUND "${component} (optional)")
+      endif()
+    endif()
+  endforeach()
+  set(_ICU_REQUIRED_LIBS_FOUND "${ICU_REQUIRED_LIBS_FOUND}" PARENT_SCOPE)
+  set(ICU_LIBRARY "${ICU_LIBRARY}" PARENT_SCOPE)
+
+  if(NOT ICU_FIND_QUIETLY)
+    if(ICU_LIBS_FOUND)
+      message(STATUS "Found the following ICU libraries:")
+      foreach(found ${ICU_LIBS_FOUND})
+        message(STATUS "  ${found}")
+      endforeach()
+    endif()
+    if(ICU_LIBS_NOTFOUND)
+      message(STATUS "The following ICU libraries were not found:")
+      foreach(notfound ${ICU_LIBS_NOTFOUND})
+        message(STATUS "  ${notfound}")
+      endforeach()
+    endif()
+  endif()
+
+  if(ICU_DEBUG)
+    message(STATUS "--------FindICU.cmake search debug--------")
+    message(STATUS "ICU binary path search order: ${icu_roots}")
+    message(STATUS "ICU include path search order: ${icu_roots}")
+    message(STATUS "ICU library path search order: ${icu_roots}")
+    message(STATUS "----------------")
+  endif()
+endfunction()
+
+_ICU_FIND()
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(ICU
+                                  FOUND_VAR ICU_FOUND
+                                  REQUIRED_VARS ICU_INCLUDE_DIR
+                                                ICU_LIBRARY
+                                                _ICU_REQUIRED_LIBS_FOUND
+                                  VERSION_VAR ICU_VERSION
+                                  FAIL_MESSAGE "Failed to find all ICU components")
+
+unset(_ICU_REQUIRED_LIBS_FOUND)
+
+if(ICU_FOUND)
+  set(ICU_INCLUDE_DIRS "${ICU_INCLUDE_DIR}")
+  set(ICU_LIBRARIES "${ICU_LIBRARY}")
+  foreach(_ICU_component ${ICU_FIND_COMPONENTS})
+    string(TOUPPER "${_ICU_component}" _ICU_component_upcase)
+    set(_ICU_component_cache "ICU_${_ICU_component_upcase}_LIBRARY")
+    set(_ICU_component_cache_release "ICU_${_ICU_component_upcase}_LIBRARY_RELEASE")
+    set(_ICU_component_cache_debug "ICU_${_ICU_component_upcase}_LIBRARY_DEBUG")
+    set(_ICU_component_lib "ICU_${_ICU_component_upcase}_LIBRARIES")
+    set(_ICU_component_found "${_ICU_component_upcase}_FOUND")
+    set(_ICU_imported_target "ICU::${_ICU_component}")
+    if(${_ICU_component_found})
+      set("${_ICU_component_lib}" "${${_ICU_component_cache}}")
+      if(NOT TARGET ${_ICU_imported_target})
+        add_library(${_ICU_imported_target} UNKNOWN IMPORTED)
+        if(ICU_INCLUDE_DIR)
+          set_target_properties(${_ICU_imported_target} PROPERTIES
+            INTERFACE_INCLUDE_DIRECTORIES "${ICU_INCLUDE_DIR}")
+        endif()
+        if(EXISTS "${${_ICU_component_cache}}")
+          set_target_properties(${_ICU_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
+            IMPORTED_LOCATION "${${_ICU_component_cache}}")
+        endif()
+        if(EXISTS "${${_ICU_component_cache_release}}")
+          set_property(TARGET ${_ICU_imported_target} APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS RELEASE)
+          set_target_properties(${_ICU_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
+            IMPORTED_LOCATION_RELEASE "${${_ICU_component_cache_release}}")
+        endif()
+        if(EXISTS "${${_ICU_component_cache_debug}}")
+          set_property(TARGET ${_ICU_imported_target} APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS DEBUG)
+          set_target_properties(${_ICU_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+            IMPORTED_LOCATION_DEBUG "${${_ICU_component_cache_debug}}")
+        endif()
+      endif()
+    endif()
+    unset(_ICU_component_upcase)
+    unset(_ICU_component_cache)
+    unset(_ICU_component_lib)
+    unset(_ICU_component_found)
+    unset(_ICU_imported_target)
+  endforeach()
+endif()
+
+if(ICU_DEBUG)
+  message(STATUS "--------FindICU.cmake results debug--------")
+  message(STATUS "ICU found: ${ICU_FOUND}")
+  message(STATUS "ICU_VERSION number: ${ICU_VERSION}")
+  message(STATUS "ICU_ROOT directory: ${ICU_ROOT}")
+  message(STATUS "ICU_INCLUDE_DIR directory: ${ICU_INCLUDE_DIR}")
+  message(STATUS "ICU_LIBRARIES: ${ICU_LIBRARIES}")
+
+  foreach(program IN LISTS icu_programs)
+    string(TOUPPER "${program}" program_upcase)
+    set(program_lib "ICU_${program_upcase}_EXECUTABLE")
+    message(STATUS "${program} program: ${${program_lib}}")
+    unset(program_upcase)
+    unset(program_lib)
+  endforeach()
+
+  foreach(component IN LISTS ICU_FIND_COMPONENTS)
+    string(TOUPPER "${component}" component_upcase)
+    set(component_lib "ICU_${component_upcase}_LIBRARIES")
+    set(component_found "${component_upcase}_FOUND")
+    message(STATUS "${component} library found: ${${component_found}}")
+    message(STATUS "${component} library: ${${component_lib}}")
+    unset(component_upcase)
+    unset(component_lib)
+    unset(component_found)
+  endforeach()
+  message(STATUS "----------------")
+endif()
+
+unset(icu_programs)
diff --git a/Modules/FindIce.cmake b/Modules/FindIce.cmake
index 3fa6cab..a61d4a8 100644
--- a/Modules/FindIce.cmake
+++ b/Modules/FindIce.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindIce
 # -------
@@ -121,19 +124,6 @@
 
 # Written by Roger Leigh <rleigh at codelibre.net>
 
-#=============================================================================
-# Copyright 2014-2015 University of Dundee
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # The Ice checks are contained in a function due to the large number
 # of temporary variables needed.
 function(_Ice_FIND)
@@ -141,6 +131,9 @@ function(_Ice_FIND)
   set(ice_versions
       3
       3.6
+      3.6.3
+      3.6.2
+      3.6.1
       3.6.0
       3.5
       3.5.1
@@ -360,12 +353,20 @@ function(_Ice_FIND)
   foreach(component ${Ice_FIND_COMPONENTS})
     string(TOUPPER "${component}" component_upcase)
     set(component_cache "Ice_${component_upcase}_LIBRARY")
+    set(component_cache_release "${component_cache}_RELEASE")
+    set(component_cache_debug "${component_cache}_DEBUG")
     set(component_found "${component_upcase}_FOUND")
-    find_library("${component_cache}" "${component}"
+    find_library("${component_cache_release}" "${component}"
+      HINTS ${ice_roots}
+      PATH_SUFFIXES ${ice_library_suffixes}
+      DOC "Ice ${component} library (release)")
+    find_library("${component_cache_debug}" "${component}d"
       HINTS ${ice_roots}
       PATH_SUFFIXES ${ice_library_suffixes}
-      DOC "Ice ${component} library")
-    mark_as_advanced("${component_cache}")
+      DOC "Ice ${component} library (debug)")
+    include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
+    select_library_configurations(Ice_${component_upcase})
+    mark_as_advanced("${component_cache_release}" "${component_cache_debug}")
     if(${component_cache})
       set("${component_found}" ON)
       list(APPEND Ice_LIBRARY "${${component_cache}}")
@@ -438,6 +439,8 @@ if(Ice_FOUND)
   foreach(_Ice_component ${Ice_FIND_COMPONENTS})
     string(TOUPPER "${_Ice_component}" _Ice_component_upcase)
     set(_Ice_component_cache "Ice_${_Ice_component_upcase}_LIBRARY")
+    set(_Ice_component_cache_release "Ice_${_Ice_component_upcase}_LIBRARY_RELEASE")
+    set(_Ice_component_cache_debug "Ice_${_Ice_component_upcase}_LIBRARY_DEBUG")
     set(_Ice_component_lib "Ice_${_Ice_component_upcase}_LIBRARIES")
     set(_Ice_component_found "${_Ice_component_upcase}_FOUND")
     set(_Ice_imported_target "Ice::${_Ice_component}")
@@ -445,9 +448,29 @@ if(Ice_FOUND)
       set("${_Ice_component_lib}" "${${_Ice_component_cache}}")
       if(NOT TARGET ${_Ice_imported_target})
         add_library(${_Ice_imported_target} UNKNOWN IMPORTED)
-        set_target_properties(${_Ice_imported_target} PROPERTIES
-          IMPORTED_LOCATION "${${_Ice_component_cache}}"
-          INTERFACE_INCLUDE_DIRECTORIES "${Ice_INCLUDE_DIR}")
+        if()
+          set_target_properties(${_Ice_imported_target} PROPERTIES
+            INTERFACE_INCLUDE_DIRECTORIES "${Ice_INCLUDE_DIR}")
+        endif()
+        if(EXISTS "${${_Ice_component_cache}}")
+          set_target_properties(${_Ice_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
+            IMPORTED_LOCATION "${${_Ice_component_cache}}")
+        endif()
+        if(EXISTS "${${_Ice_component_cache_release}}")
+          set_property(TARGET ${_Ice_imported_target} APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS RELEASE)
+          set_target_properties(${_Ice_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
+            IMPORTED_LOCATION_RELEASE "${${_Ice_component_cache_release}}")
+        endif()
+        if(EXISTS "${${_Ice_component_cache_debug}}")
+          set_property(TARGET ${_Ice_imported_target} APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS DEBUG)
+          set_target_properties(${_Ice_imported_target} PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+            IMPORTED_LOCATION_DEBUG "${${_Ice_component_cache_debug}}")
+        endif()
       endif()
     endif()
     unset(_Ice_component_upcase)
diff --git a/Modules/FindIcotool.cmake b/Modules/FindIcotool.cmake
index a7c5a64..bd3e327 100644
--- a/Modules/FindIcotool.cmake
+++ b/Modules/FindIcotool.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindIcotool
 # -----------
@@ -13,19 +16,6 @@
 #   ICOTOOL_FOUND: True if icotool has been found.
 #   ICOTOOL_VERSION_STRING: the version of icotool found.
 
-#=============================================================================
-# Copyright 2012 Aleksey Avdeev <solo at altlinux.ru>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(ICOTOOL_EXECUTABLE
   icotool
 )
diff --git a/Modules/FindImageMagick.cmake b/Modules/FindImageMagick.cmake
index 65458b7..0561a3d 100644
--- a/Modules/FindImageMagick.cmake
+++ b/Modules/FindImageMagick.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindImageMagick
 # ---------------
@@ -80,21 +83,6 @@
 # Note that the standard FIND_PACKAGE features are supported (i.e.,
 # QUIET, REQUIRED, etc.).
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2007-2008 Miguel A. Figueroa-Villanueva <miguelf at ieee dot org>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_package(PkgConfig QUIET)
 
 #---------------------------------------------------------------------
diff --git a/Modules/FindIntl.cmake b/Modules/FindIntl.cmake
index cd2ec63..f887721 100644
--- a/Modules/FindIntl.cmake
+++ b/Modules/FindIntl.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindIntl
 # --------
@@ -29,19 +32,6 @@
 
 # Written by Roger Leigh <rleigh at codelibre.net>
 
-#=============================================================================
-# Copyright 2014 Roger Leigh <rleigh at codelibre.net>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Find include directory
 find_path(Intl_INCLUDE_DIR
           NAMES "libintl.h"
diff --git a/Modules/FindJNI.cmake b/Modules/FindJNI.cmake
index 3ceab39..39e504f 100644
--- a/Modules/FindJNI.cmake
+++ b/Modules/FindJNI.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindJNI
 # -------
@@ -22,19 +25,6 @@
 #   JAVA_INCLUDE_PATH2    = the include path to jni_md.h
 #   JAVA_AWT_INCLUDE_PATH = the include path to jawt.h
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Expand {libarch} occurences to java_libarch subdirectory(-ies) and set ${_var}
 macro(java_append_library_directories _var)
     # Determine java arch-specific library subdir
@@ -53,7 +43,7 @@ macro(java_append_library_directories _var)
         set(_java_libarch "alpha")
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^arm")
         # Subdir is "arm" for both big-endian (arm) and little-endian (armel).
-        set(_java_libarch "arm")
+        set(_java_libarch "arm" "aarch32")
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^mips")
         # mips* machines are bi-endian mostly so processor does not tell
         # endianess of the underlying system.
@@ -312,8 +302,11 @@ else()
 endif()
 
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(JNI  DEFAULT_MSG  JAVA_AWT_LIBRARY JAVA_JVM_LIBRARY
-                                                    JAVA_INCLUDE_PATH  JAVA_INCLUDE_PATH2 JAVA_AWT_INCLUDE_PATH)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(JNI  DEFAULT_MSG  JAVA_AWT_LIBRARY
+                                                    JAVA_JVM_LIBRARY
+                                                    JAVA_INCLUDE_PATH
+                                                    JAVA_INCLUDE_PATH2
+                                                    JAVA_AWT_INCLUDE_PATH)
 
 mark_as_advanced(
   JAVA_AWT_LIBRARY
diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake
index 86bb6e5..b644181 100644
--- a/Modules/FindJPEG.cmake
+++ b/Modules/FindJPEG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindJPEG
 # --------
@@ -18,19 +21,6 @@
 #
 #   JPEG_LIBRARY, where to find the JPEG library.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(JPEG_INCLUDE_DIR jpeglib.h)
 
 set(JPEG_NAMES ${JPEG_NAMES} jpeg libjpeg)
diff --git a/Modules/FindJasper.cmake b/Modules/FindJasper.cmake
index 0f325f0..748510e 100644
--- a/Modules/FindJasper.cmake
+++ b/Modules/FindJasper.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindJasper
 # ----------
@@ -13,21 +16,6 @@
 #   JASPER_LIBRARIES - the libraries needed to use Jasper
 #   JASPER_VERSION_STRING - the version of Jasper found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(JASPER_INCLUDE_DIR jasper/jasper.h)
 
 if (NOT JASPER_LIBRARIES)
diff --git a/Modules/FindJava.cmake b/Modules/FindJava.cmake
index c643d9b..e30917d 100644
--- a/Modules/FindJava.cmake
+++ b/Modules/FindJava.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindJava
 # --------
@@ -8,6 +11,7 @@
 # include files and libraries are.  The caller may set variable JAVA_HOME
 # to specify a Java installation prefix explicitly.
 #
+# See also the :module:`FindJNI` module to find Java development tools.
 #
 # Specify one or more of the following components as you call this find module. See example below.
 #
@@ -54,8 +58,6 @@
 # ::
 #
 #   Java_FOUND                    - TRUE if all components are found.
-#   Java_INCLUDE_DIRS             - Full paths to all include dirs.
-#   Java_LIBRARIES                - Full paths to all libraries.
 #   Java_<component>_FOUND        - TRUE if <component> is found.
 #
 #
@@ -68,20 +70,6 @@
 #   find_package(Java COMPONENTS Runtime)
 #   find_package(Java COMPONENTS Development)
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-# Copyright 2009-2011 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeFindJavaCommon.cmake)
 
 # The HINTS option should only be used for values computed from the system.
diff --git a/Modules/FindKDE3.cmake b/Modules/FindKDE3.cmake
index dda4530..62e2a50 100644
--- a/Modules/FindKDE3.cmake
+++ b/Modules/FindKDE3.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindKDE3
 # --------
@@ -134,20 +137,6 @@
 #
 # Author: Alexander Neundorf <neundorf at kde.org>
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT UNIX AND KDE3_FIND_REQUIRED)
    message(FATAL_ERROR "Compiling KDE3 applications and libraries under Windows is not supported")
 endif()
diff --git a/Modules/FindKDE4.cmake b/Modules/FindKDE4.cmake
index 5530166..bb98e53 100644
--- a/Modules/FindKDE4.cmake
+++ b/Modules/FindKDE4.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindKDE4
 # --------
@@ -22,20 +25,6 @@
 #
 # Author: Alexander Neundorf <neundorf at kde.org>
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # If Qt3 has already been found, fail.
 if(QT_QT_LIBRARY)
   if(KDE4_FIND_REQUIRED)
diff --git a/Modules/FindLAPACK.cmake b/Modules/FindLAPACK.cmake
index a6bf89f..fe6af91 100644
--- a/Modules/FindLAPACK.cmake
+++ b/Modules/FindLAPACK.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLAPACK
 # ----------
@@ -33,19 +36,6 @@
 # ## List of vendors (BLA_VENDOR) valid in this module # Intel(mkl),
 # OpenBLAS, ACML,Apple, NAS, Generic
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(_lapack_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
 
 # Check the language being used
diff --git a/Modules/FindLATEX.cmake b/Modules/FindLATEX.cmake
index ae83733..1d8f6ce 100644
--- a/Modules/FindLATEX.cmake
+++ b/Modules/FindLATEX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLATEX
 # ---------
@@ -49,20 +52,6 @@
 #   find_package(LATEX COMPONENTS PDFLATEX)
 #   find_package(LATEX COMPONENTS BIBTEX PS2PDF)
 
-#=============================================================================
-# Copyright 2002-2015 Kitware, Inc.
-# Copyright 2014-2015 Christoph Grüninger <foss at grueninger.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (WIN32)
   # Try to find the MikTex binary path (look for its package manager).
   find_path(MIKTEX_BINARY_PATH mpm.exe
diff --git a/Modules/FindLTTngUST.cmake b/Modules/FindLTTngUST.cmake
index e3220ac..8781bae 100644
--- a/Modules/FindLTTngUST.cmake
+++ b/Modules/FindLTTngUST.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLTTngUST
 # ------------
@@ -30,20 +33,6 @@
 # ``LTTNGUST_HAS_TRACELOG``
 #   ``TRUE`` if the ``tracelog()`` API is available in the system's LTTng-UST
 
-#=============================================================================
-# Copyright 2016 Kitware, Inc.
-# Copyright 2016 Philippe Proulx <pproulx at efficios.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(LTTNGUST_INCLUDE_DIRS NAMES lttng/tracepoint.h)
 find_library(LTTNGUST_LIBRARIES NAMES lttng-ust)
 
diff --git a/Modules/FindLibArchive.cmake b/Modules/FindLibArchive.cmake
index dd93041..1a26bbb 100644
--- a/Modules/FindLibArchive.cmake
+++ b/Modules/FindLibArchive.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLibArchive
 # --------------
@@ -13,19 +16,6 @@
 #   LibArchive_LIBRARIES    - libraries to link
 #   LibArchive_VERSION      - libarchive 3-component version number
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(LibArchive_INCLUDE_DIR
   NAMES archive.h
   PATHS
diff --git a/Modules/FindLibLZMA.cmake b/Modules/FindLibLZMA.cmake
index 742b851..8009bcf 100644
--- a/Modules/FindLibLZMA.cmake
+++ b/Modules/FindLibLZMA.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLibLZMA
 # -----------
@@ -19,23 +22,6 @@
 #   LIBLZMA_VERSION_PATCH     - The patch version of lzma
 #   LIBLZMA_VERSION_STRING    - version number as a string (ex: "5.0.3")
 
-#=============================================================================
-# Copyright 2008 Per Øyvind Karlsen <peroyvind at mandriva.org>
-# Copyright 2009 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2009 Helio Chissini de Castro <helio at kde.org>
-# Copyright 2012 Mario Bensi <mbensi at ipsquad.net>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 find_path(LIBLZMA_INCLUDE_DIR lzma.h )
 find_library(LIBLZMA_LIBRARY lzma)
 
diff --git a/Modules/FindLibXml2.cmake b/Modules/FindLibXml2.cmake
index 7322428..9580981 100644
--- a/Modules/FindLibXml2.cmake
+++ b/Modules/FindLibXml2.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLibXml2
 # -----------
@@ -15,20 +18,6 @@
 #   LIBXML2_XMLLINT_EXECUTABLE - The XML checking tool xmllint coming with LibXml2
 #   LIBXML2_VERSION_STRING - the version of LibXml2 found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # use pkg-config to get the directories and then use these values
 # in the find_path() and find_library() calls
 find_package(PkgConfig QUIET)
diff --git a/Modules/FindLibXslt.cmake b/Modules/FindLibXslt.cmake
index 2416341..abd1963 100644
--- a/Modules/FindLibXslt.cmake
+++ b/Modules/FindLibXslt.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLibXslt
 # -----------
@@ -22,20 +25,6 @@
 # ``LIBXSLT_XSLTPROC_EXECUTABLE``
 #   Contains the full path to the xsltproc executable if found.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # use pkg-config to get the directories and then use these values
 # in the find_path() and find_library() calls
 find_package(PkgConfig QUIET)
diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake
index 4e00a92..5be0428 100644
--- a/Modules/FindLua.cmake
+++ b/Modules/FindLua.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLua
 # -------
@@ -33,50 +36,39 @@
 # This is because, the lua location is not standardized and may exist in
 # locations other than lua/
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2013 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 unset(_lua_include_subdirs)
 unset(_lua_library_names)
+unset(_lua_append_versions)
 
 # this is a function only to have all the variables inside go away automatically
-function(set_lua_version_vars)
+function(_lua_set_version_vars)
     set(LUA_VERSIONS5 5.3 5.2 5.1 5.0)
 
     if (Lua_FIND_VERSION_EXACT)
         if (Lua_FIND_VERSION_COUNT GREATER 1)
-            set(lua_append_versions ${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR})
+            set(_lua_append_versions ${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR})
         endif ()
     elseif (Lua_FIND_VERSION)
         # once there is a different major version supported this should become a loop
         if (NOT Lua_FIND_VERSION_MAJOR GREATER 5)
             if (Lua_FIND_VERSION_COUNT EQUAL 1)
-                set(lua_append_versions ${LUA_VERSIONS5})
+                set(_lua_append_versions ${LUA_VERSIONS5})
             else ()
                 foreach (subver IN LISTS LUA_VERSIONS5)
                     if (NOT subver VERSION_LESS ${Lua_FIND_VERSION})
-                        list(APPEND lua_append_versions ${subver})
+                        list(APPEND _lua_append_versions ${subver})
                     endif ()
                 endforeach ()
             endif ()
         endif ()
     else ()
         # once there is a different major version supported this should become a loop
-        set(lua_append_versions ${LUA_VERSIONS5})
+        set(_lua_append_versions ${LUA_VERSIONS5})
     endif ()
 
-    foreach (ver IN LISTS lua_append_versions)
+    list(APPEND _lua_include_subdirs "include/lua" "include")
+
+    foreach (ver IN LISTS _lua_append_versions)
         string(REGEX MATCH "^([0-9]+)\\.([0-9]+)$" _ver "${ver}")
         list(APPEND _lua_include_subdirs
              include/lua${CMAKE_MATCH_1}${CMAKE_MATCH_2}
@@ -93,23 +85,72 @@ function(set_lua_version_vars)
 
     set(_lua_include_subdirs "${_lua_include_subdirs}" PARENT_SCOPE)
     set(_lua_library_names "${_lua_library_names}" PARENT_SCOPE)
-endfunction(set_lua_version_vars)
+    set(_lua_append_versions "${_lua_append_versions}" PARENT_SCOPE)
+endfunction(_lua_set_version_vars)
 
-set_lua_version_vars()
+function(_lua_check_header_version _hdr_file)
+    # At least 5.[012] have different ways to express the version
+    # so all of them need to be tested. Lua 5.2 defines LUA_VERSION
+    # and LUA_RELEASE as joined by the C preprocessor, so avoid those.
+    file(STRINGS "${_hdr_file}" lua_version_strings
+         REGEX "^#define[ \t]+LUA_(RELEASE[ \t]+\"Lua [0-9]|VERSION([ \t]+\"Lua [0-9]|_[MR])).*")
 
-find_path(LUA_INCLUDE_DIR lua.h
-  HINTS
-    ENV LUA_DIR
-  PATH_SUFFIXES ${_lua_include_subdirs} include/lua include
-  PATHS
-  ~/Library/Frameworks
-  /Library/Frameworks
-  /sw # Fink
-  /opt/local # DarwinPorts
-  /opt/csw # Blastwave
-  /opt
-)
+    string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MAJOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_MAJOR ";${lua_version_strings};")
+    if (LUA_VERSION_MAJOR MATCHES "^[0-9]+$")
+        string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MINOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_MINOR ";${lua_version_strings};")
+        string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_RELEASE[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_PATCH ";${lua_version_strings};")
+        set(LUA_VERSION_STRING "${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}.${LUA_VERSION_PATCH}")
+    else ()
+        string(REGEX REPLACE ".*;#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" LUA_VERSION_STRING ";${lua_version_strings};")
+        if (NOT LUA_VERSION_STRING MATCHES "^[0-9.]+$")
+            string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" LUA_VERSION_STRING ";${lua_version_strings};")
+        endif ()
+        string(REGEX REPLACE "^([0-9]+)\\.[0-9.]*$" "\\1" LUA_VERSION_MAJOR "${LUA_VERSION_STRING}")
+        string(REGEX REPLACE "^[0-9]+\\.([0-9]+)[0-9.]*$" "\\1" LUA_VERSION_MINOR "${LUA_VERSION_STRING}")
+        string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]).*" "\\1" LUA_VERSION_PATCH "${LUA_VERSION_STRING}")
+    endif ()
+    foreach (ver IN LISTS _lua_append_versions)
+        if (ver STREQUAL "${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}")
+            set(LUA_VERSION_MAJOR ${LUA_VERSION_MAJOR} PARENT_SCOPE)
+            set(LUA_VERSION_MINOR ${LUA_VERSION_MINOR} PARENT_SCOPE)
+            set(LUA_VERSION_PATCH ${LUA_VERSION_PATCH} PARENT_SCOPE)
+            set(LUA_VERSION_STRING ${LUA_VERSION_STRING} PARENT_SCOPE)
+            return()
+        endif ()
+    endforeach ()
+endfunction(_lua_check_header_version)
+
+_lua_set_version_vars()
+
+if (LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h")
+    _lua_check_header_version("${LUA_INCLUDE_DIR}/lua.h")
+endif ()
+
+if (NOT LUA_VERSION_STRING)
+    foreach (subdir IN LISTS _lua_include_subdirs)
+        unset(LUA_INCLUDE_PREFIX CACHE)
+        find_path(LUA_INCLUDE_PREFIX ${subdir}/lua.h
+          HINTS
+            ENV LUA_DIR
+          PATHS
+          ~/Library/Frameworks
+          /Library/Frameworks
+          /sw # Fink
+          /opt/local # DarwinPorts
+          /opt/csw # Blastwave
+          /opt
+        )
+        if (LUA_INCLUDE_PREFIX)
+            _lua_check_header_version("${LUA_INCLUDE_PREFIX}/${subdir}/lua.h")
+            if (LUA_VERSION_STRING)
+                set(LUA_INCLUDE_DIR "${LUA_INCLUDE_PREFIX}/${subdir}")
+                break()
+            endif ()
+        endif ()
+    endforeach ()
+endif ()
 unset(_lua_include_subdirs)
+unset(_lua_append_versions)
 
 find_library(LUA_LIBRARY
   NAMES ${_lua_library_names} lua
@@ -137,31 +178,6 @@ if (LUA_LIBRARY)
     endif ()
 endif ()
 
-if (LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h")
-    # At least 5.[012] have different ways to express the version
-    # so all of them need to be tested. Lua 5.2 defines LUA_VERSION
-    # and LUA_RELEASE as joined by the C preprocessor, so avoid those.
-    file(STRINGS "${LUA_INCLUDE_DIR}/lua.h" lua_version_strings
-         REGEX "^#define[ \t]+LUA_(RELEASE[ \t]+\"Lua [0-9]|VERSION([ \t]+\"Lua [0-9]|_[MR])).*")
-
-    string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MAJOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_MAJOR ";${lua_version_strings};")
-    if (LUA_VERSION_MAJOR MATCHES "^[0-9]+$")
-        string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MINOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_MINOR ";${lua_version_strings};")
-        string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_RELEASE[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" LUA_VERSION_PATCH ";${lua_version_strings};")
-        set(LUA_VERSION_STRING "${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}.${LUA_VERSION_PATCH}")
-    else ()
-        string(REGEX REPLACE ".*;#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" LUA_VERSION_STRING ";${lua_version_strings};")
-        if (NOT LUA_VERSION_STRING MATCHES "^[0-9.]+$")
-            string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" LUA_VERSION_STRING ";${lua_version_strings};")
-        endif ()
-        string(REGEX REPLACE "^([0-9]+)\\.[0-9.]*$" "\\1" LUA_VERSION_MAJOR "${LUA_VERSION_STRING}")
-        string(REGEX REPLACE "^[0-9]+\\.([0-9]+)[0-9.]*$" "\\1" LUA_VERSION_MINOR "${LUA_VERSION_STRING}")
-        string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]).*" "\\1" LUA_VERSION_PATCH "${LUA_VERSION_STRING}")
-    endif ()
-
-    unset(lua_version_strings)
-endif()
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 # handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if
 # all listed variables are TRUE
diff --git a/Modules/FindLua50.cmake b/Modules/FindLua50.cmake
index 666d909..838ca6a 100644
--- a/Modules/FindLua50.cmake
+++ b/Modules/FindLua50.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLua50
 # ---------
@@ -29,19 +32,6 @@
 # This is because, the lua location is not standardized and may exist in
 # locations other than lua/
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(LUA_INCLUDE_DIR lua.h
   HINTS
     ENV LUA_DIR
diff --git a/Modules/FindLua51.cmake b/Modules/FindLua51.cmake
index 5b9ff91..f2b2322 100644
--- a/Modules/FindLua51.cmake
+++ b/Modules/FindLua51.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindLua51
 # ---------
@@ -30,19 +33,6 @@
 # This is because, the lua location is not standardized and may exist in
 # locations other than lua/
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(LUA_INCLUDE_DIR lua.h
   HINTS
     ENV LUA_DIR
diff --git a/Modules/FindMFC.cmake b/Modules/FindMFC.cmake
index 3547628..5c2dbbf 100644
--- a/Modules/FindMFC.cmake
+++ b/Modules/FindMFC.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMFC
 # -------
@@ -13,19 +16,6 @@
 #
 # You don't need to include anything or link anything to use it.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Assume no MFC support
 set(MFC_FOUND "NO")
 
diff --git a/Modules/FindMPEG.cmake b/Modules/FindMPEG.cmake
index 26ee8dd..aff464e 100644
--- a/Modules/FindMPEG.cmake
+++ b/Modules/FindMPEG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMPEG
 # --------
@@ -19,19 +22,6 @@
 #   MPEG_mpeg2_LIBRARY, where to find the MPEG library.
 #   MPEG_vo_LIBRARY, where to find the vo library.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(MPEG_INCLUDE_DIR mpeg2dec/include/video_out.h
   /usr/local/livid
 )
diff --git a/Modules/FindMPEG2.cmake b/Modules/FindMPEG2.cmake
index f2f2076..e28054d 100644
--- a/Modules/FindMPEG2.cmake
+++ b/Modules/FindMPEG2.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMPEG2
 # ---------
@@ -19,19 +22,6 @@
 #   MPEG2_mpeg2_LIBRARY, where to find the MPEG2 library.
 #   MPEG2_vo_LIBRARY, where to find the vo library.
 
-#=============================================================================
-# Copyright 2003-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(MPEG2_INCLUDE_DIR
   NAMES mpeg2.h mpeg2dec/mpeg2.h
   PATHS /usr/local/livid
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index fbc6795..676e1bc 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMPI
 # -------
@@ -88,21 +91,6 @@
 #
 # In new projects, please use the ``MPI_<lang>_XXX`` equivalents.
 
-#=============================================================================
-# Copyright 2001-2011 Kitware, Inc.
-# Copyright 2010-2011 Todd Gamblin tgamblin at llnl.gov
-# Copyright 2001-2009 Dave Partyka
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # include this to handle the QUIETLY and REQUIRED arguments
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
@@ -327,7 +315,7 @@ function (interrogate_mpi_compiler lang try_libs)
 
         foreach(FLAG ${MPI_ALL_COMPILE_FLAGS})
           if (MPI_COMPILE_FLAGS_WORK)
-            set(MPI_COMPILE_FLAGS_WORK "${MPI_COMPILE_FLAGS_WORK} ${FLAG}")
+            string(APPEND MPI_COMPILE_FLAGS_WORK " ${FLAG}")
           else()
             set(MPI_COMPILE_FLAGS_WORK ${FLAG})
           endif()
@@ -376,7 +364,7 @@ function (interrogate_mpi_compiler lang try_libs)
         set(MPI_LINK_FLAGS_WORK)
         foreach(FLAG ${MPI_ALL_LINK_FLAGS})
           if (MPI_LINK_FLAGS_WORK)
-            set(MPI_LINK_FLAGS_WORK "${MPI_LINK_FLAGS_WORK} ${FLAG}")
+            string(APPEND MPI_LINK_FLAGS_WORK " ${FLAG}")
           else()
             set(MPI_LINK_FLAGS_WORK ${FLAG})
           endif()
@@ -398,8 +386,8 @@ function (interrogate_mpi_compiler lang try_libs)
         # in the showme list that can only be found in the implicit
         # link directories of the compiler.
         if (DEFINED CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES)
-          set(MPI_LINK_PATH
-            "${MPI_LINK_PATH};${CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES}")
+          string(APPEND MPI_LINK_PATH
+            ";${CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES}")
         endif ()
 
         # Determine full path names for all of the libraries that one needs
diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake
index 956dad2..b7f2db5 100644
--- a/Modules/FindMatlab.cmake
+++ b/Modules/FindMatlab.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMatlab
 # ----------
@@ -15,9 +18,11 @@
 #
 # The module supports the following components:
 #
-# * ``MX_LIBRARY`` and ``ENG_LIBRARY`` respectively the MX and ENG libraries of
-#   Matlab
+# * ``MX_LIBRARY``, ``ENG_LIBRARY`` and ``MAT_LIBRARY``: respectively the MX,
+#   ENG and MAT libraries of Matlab
 # * ``MAIN_PROGRAM`` the Matlab binary program.
+# * ``MEX_COMPILER`` the MEX compiler.
+# * ``SIMULINK`` the Simulink environment.
 #
 # .. note::
 #
@@ -93,6 +98,9 @@
 # ``Matlab_ENG_LIBRARY``
 #   Matlab engine library. Available only if the component ``ENG_LIBRARY``
 #   is requested.
+# ``Matlab_MAT_LIBRARY``
+#   Matlab matrix library. Available only if the component ``MAT_LIBRARY``
+#   is requested.
 # ``Matlab_LIBRARIES``
 #   the whole set of libraries of Matlab
 # ``Matlab_MEX_COMPILER``
@@ -203,23 +211,11 @@
 #   Matlab are installed. The priority is set according to the ordering in
 #   this list.
 
-#=============================================================================
-# Copyright 2014-2015 Raffi Enficiaud, Max Planck Society
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(_FindMatlab_SELF_DIR "${CMAKE_CURRENT_LIST_DIR}")
 
 include(FindPackageHandleStandardArgs)
 include(CheckCXXCompilerFlag)
+include(CheckCCompilerFlag)
 
 
 # The currently supported versions. Other version can be added by the user by
@@ -632,7 +628,7 @@ function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_ve
     set(devnull INPUT_FILE NUL)
   endif()
 
-  # timeout set to 30 seconds, in case it does not start
+  # timeout set to 120 seconds, in case it does not start
   # note as said before OUTPUT_VARIABLE cannot be used in a platform
   # independent manner however, not setting it would flush the output of Matlab
   # in the current console (unix variant)
@@ -641,11 +637,18 @@ function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_ve
     OUTPUT_VARIABLE _matlab_version_from_cmd_dummy
     RESULT_VARIABLE _matlab_result_version_call
     ERROR_VARIABLE _matlab_result_version_call_error
-    TIMEOUT 30
+    TIMEOUT 120
     WORKING_DIRECTORY "${_matlab_temporary_folder}"
     ${devnull}
     )
 
+  if("${_matlab_result_version_call}" MATCHES "timeout")
+    if(MATLAB_FIND_DEBUG)
+      message(WARNING "[MATLAB] Unable to determine the version of Matlab."
+        " Matlab call timed out after 120 seconds.")
+    endif()
+    return()
+  endif()
 
   if(${_matlab_result_version_call})
     if(MATLAB_FIND_DEBUG)
@@ -695,7 +698,6 @@ function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_ve
 
 endfunction()
 
-
 #.rst:
 # .. command:: matlab_add_unit_test
 #
@@ -717,6 +719,7 @@ endfunction()
 #     matlab_add_unit_test(
 #         NAME <name>
 #         UNITTEST_FILE matlab_file_containing_unittest.m
+#         [CUSTOM_MATLAB_COMMAND matlab_command_to_run_as_test]
 #         [UNITTEST_PRECOMMAND matlab_command_to_run]
 #         [TIMEOUT timeout]
 #         [ADDITIONAL_PATH path1 [path2 ...]]
@@ -732,6 +735,11 @@ endfunction()
 #   ``UNITTEST_FILE``
 #     the matlab unittest file. Its path will be automatically
 #     added to the Matlab path.
+#   ``CUSTOM_MATLAB_COMMAND``
+#     Matlab script command to run as the test.
+#     If this is not set, then the following is run:
+#     ``runtests('matlab_file_name'), exit(max([ans(1,:).Failed]))``
+#     where ``matlab_file_name`` is the ``UNITTEST_FILE`` without the extension.
 #   ``UNITTEST_PRECOMMAND``
 #     Matlab script command to be ran before the file
 #     containing the test (eg. GPU device initialisation based on CMake
@@ -745,12 +753,18 @@ endfunction()
 #   ``MATLAB_ADDITIONAL_STARTUP_OPTIONS``
 #     a list of additional option in order
 #     to run Matlab from the command line.
+#     ``-nosplash -nodesktop -nodisplay`` are always added.
 #   ``TEST_ARGS``
 #     Additional options provided to the add_test command. These
 #     options are added to the default options (eg. "CONFIGURATIONS Release")
 #   ``NO_UNITTEST_FRAMEWORK``
 #     when set, indicates that the test should not
 #     use the unittest framework of Matlab (available for versions >= R2013a).
+#   ``WORKING_DIRECTORY``
+#     This will be the working directory for the test. If specified it will
+#     also be the output directory used for the log file of the test run.
+#     If not specifed the temporary directory ``${CMAKE_BINARY_DIR}/Matlab`` will
+#     be used as the working directory and the log location.
 #
 function(matlab_add_unit_test)
 
@@ -759,11 +773,12 @@ function(matlab_add_unit_test)
   endif()
 
   set(options NO_UNITTEST_FRAMEWORK)
-  set(oneValueArgs NAME UNITTEST_PRECOMMAND UNITTEST_FILE TIMEOUT)
+  set(oneValueArgs NAME UNITTEST_FILE TIMEOUT WORKING_DIRECTORY
+    UNITTEST_PRECOMMAND CUSTOM_TEST_COMMAND)
   set(multiValueArgs ADDITIONAL_PATH MATLAB_ADDITIONAL_STARTUP_OPTIONS TEST_ARGS)
 
   set(prefix _matlab_unittest_prefix)
-  cmake_parse_arguments(${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
+  cmake_parse_arguments(PARSE_ARGV 0 ${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" )
 
   if(NOT ${prefix}_NAME)
     message(FATAL_ERROR "[MATLAB] The Matlab test name cannot be empty")
@@ -771,15 +786,17 @@ function(matlab_add_unit_test)
 
   add_test(NAME ${${prefix}_NAME}
            COMMAND ${CMAKE_COMMAND}
-            -Dtest_name=${${prefix}_NAME}
-            -Dadditional_paths=${${prefix}_ADDITIONAL_PATH}
-            -Dtest_timeout=${${prefix}_TIMEOUT}
-            -Doutput_directory=${_matlab_temporary_folder}
-            -DMatlab_PROGRAM=${Matlab_MAIN_PROGRAM}
-            -Dno_unittest_framework=${${prefix}_NO_UNITTEST_FRAMEWORK}
-            -DMatlab_ADDITIONNAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}
-            -Dunittest_file_to_run=${${prefix}_UNITTEST_FILE}
-            -Dcmd_to_run_before_test=${${prefix}_UNITTEST_PRECOMMAND}
+            "-Dtest_name=${${prefix}_NAME}"
+            "-Dadditional_paths=${${prefix}_ADDITIONAL_PATH}"
+            "-Dtest_timeout=${${prefix}_TIMEOUT}"
+            "-Doutput_directory=${_matlab_temporary_folder}"
+            "-Dworking_directory=${${prefix}_WORKING_DIRECTORY}"
+            "-DMatlab_PROGRAM=${Matlab_MAIN_PROGRAM}"
+            "-Dno_unittest_framework=${${prefix}_NO_UNITTEST_FRAMEWORK}"
+            "-DMatlab_ADDITIONNAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}"
+            "-Dunittest_file_to_run=${${prefix}_UNITTEST_FILE}"
+            "-Dcustom_Matlab_test_command=${${prefix}_CUSTOM_TEST_COMMAND}"
+            "-Dcmd_to_run_before_test=${${prefix}_UNITTEST_PRECOMMAND}"
             -P ${_FindMatlab_SELF_DIR}/MatlabTestsRedirect.cmake
            ${${prefix}_TEST_ARGS}
            ${${prefix}_UNPARSED_ARGUMENTS}
@@ -795,12 +812,13 @@ endfunction()
 #   order to produce a MEX file. The final name of the produced output may be
 #   specified, as well as additional link libraries, and a documentation entry
 #   for the MEX file. Remaining arguments of the call are passed to the
-#   :command:`add_library` command.
+#   :command:`add_library` or :command:`add_executable` command.
 #
 #   ::
 #
 #      matlab_add_mex(
 #          NAME <name>
+#          [EXECUTABLE | MODULE | SHARED]
 #          SRC src1 [src2 ...]
 #          [OUTPUT_NAME output_name]
 #          [DOCUMENTATION file.txt]
@@ -811,7 +829,7 @@ endfunction()
 #   ``NAME``
 #     name of the target.
 #   ``SRC``
-#     list of tje source files.
+#     list of source files.
 #   ``LINK_TO``
 #     a list of additional link dependencies.  The target links to ``libmex``
 #     by default. If ``Matlab_MX_LIBRARY`` is defined, it also
@@ -826,6 +844,9 @@ endfunction()
 #     the same folder without any processing, with the same name as the final
 #     mex file, and with extension `.m`. In that case, typing ``help <name>``
 #     in Matlab prints the documentation contained in this file.
+#   ``MODULE`` or ``SHARED`` may be given to specify the type of library to be
+#     created. ``EXECUTABLE`` may be given to create an executable instead of
+#     a library. If no type is given explicitly, the type is ``SHARED``.
 #
 #   The documentation file is not processed and should be in the following
 #   format:
@@ -835,18 +856,23 @@ endfunction()
 #     % This is the documentation
 #     function ret = mex_target_output_name(input1)
 #
-function(matlab_add_mex )
+function(matlab_add_mex)
 
   if(NOT WIN32)
     # we do not need all this on Windows
     # pthread options
-    check_cxx_compiler_flag(-pthread                    HAS_MINUS_PTHREAD)
+    if(CMAKE_CXX_COMPILER_LOADED)
+      check_cxx_compiler_flag(-pthread HAS_MINUS_PTHREAD)
+    elseif(CMAKE_C_COMPILER_LOADED)
+      check_c_compiler_flag(-pthread HAS_MINUS_PTHREAD)
+    endif()
     # we should use try_compile instead, the link flags are discarded from
     # this compiler_flag function.
     #check_cxx_compiler_flag(-Wl,--exclude-libs,ALL HAS_SYMBOL_HIDING_CAPABILITY)
 
   endif()
 
+  set(options EXECUTABLE MODULE SHARED)
   set(oneValueArgs NAME DOCUMENTATION OUTPUT_NAME)
   set(multiValueArgs LINK_TO SRC)
 
@@ -861,11 +887,25 @@ function(matlab_add_mex )
     set(${prefix}_OUTPUT_NAME ${${prefix}_NAME})
   endif()
 
-  add_library(${${prefix}_NAME}
-    SHARED
+  if(${prefix}_EXECUTABLE)
+    add_executable(${${prefix}_NAME}
+      ${${prefix}_SRC}
+      ${${prefix}_DOCUMENTATION}
+      ${${prefix}_UNPARSED_ARGUMENTS})
+  else()
+    if(${prefix}_MODULE)
+      set(type MODULE)
+    else()
+      set(type SHARED)
+    endif()
+
+    add_library(${${prefix}_NAME}
+      ${type}
       ${${prefix}_SRC}
       ${${prefix}_DOCUMENTATION}
       ${${prefix}_UNPARSED_ARGUMENTS})
+  endif()
+
   target_include_directories(${${prefix}_NAME} PRIVATE ${Matlab_INCLUDE_DIRS})
 
   if(DEFINED Matlab_MX_LIBRARY)
@@ -1027,13 +1067,17 @@ function(_Matlab_get_version_from_root matlab_root matlab_known_version matlab_f
   set(matlab_list_of_all_versions)
   matlab_get_version_from_matlab_run("${Matlab_PROG_VERSION_STRING_AUTO_DETECT}" matlab_list_of_all_versions)
 
-  list(GET matlab_list_of_all_versions 0 _matlab_version_tmp)
+  list(LENGTH matlab_list_of_all_versions list_of_all_versions_length)
+  if(${list_of_all_versions_length} GREATER 0)
+    list(GET matlab_list_of_all_versions 0 _matlab_version_tmp)
+  else()
+    set(_matlab_version_tmp "unknown")
+  endif()
 
   # set the version into the cache
   set(Matlab_VERSION_STRING_INTERNAL ${_matlab_version_tmp} CACHE INTERNAL "Matlab version (automatically determined)" FORCE)
 
   # warning, just in case several versions found (should not happen)
-  list(LENGTH matlab_list_of_all_versions list_of_all_versions_length)
   if((${list_of_all_versions_length} GREATER 1) AND MATLAB_FIND_DEBUG)
     message(WARNING "[MATLAB] Found several versions, taking the first one (versions found ${matlab_list_of_all_versions})")
   endif()
@@ -1201,8 +1245,8 @@ if(_numbers_of_matlab_roots GREATER 0)
 endif()
 
 
-# check if the root changed against the previous defined one, if so
-# clear all the cached variables
+# check if the root changed wrt. the previous defined one, if so
+# clear all the cached variables for being able to reconfigure properly
 if(DEFINED Matlab_ROOT_DIR_LAST_CACHED)
 
   if(NOT Matlab_ROOT_DIR_LAST_CACHED STREQUAL Matlab_ROOT_DIR)
@@ -1213,7 +1257,9 @@ if(DEFINED Matlab_ROOT_DIR_LAST_CACHED)
         Matlab_MAIN_PROGRAM
         Matlab_MX_LIBRARY
         Matlab_ENG_LIBRARY
+        Matlab_MAT_LIBRARY
         Matlab_MEX_EXTENSION
+        Matlab_SIMULINK_INCLUDE_DIR
 
         # internal
         Matlab_MEXEXTENSIONS_PROG
@@ -1287,7 +1333,11 @@ set(Matlab_EXTERN_LIBRARY_DIR
     ${Matlab_ROOT_DIR}/extern/lib/${_matlab_bin_prefix}${_matlab_current_suffix})
 
 if(WIN32)
-  set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/microsoft)
+  if(MINGW)
+    set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/mingw64)
+  else()
+    set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/microsoft)
+  endif()
   set(_matlab_lib_prefix_for_search "lib")
 else()
   set(_matlab_lib_dir_for_search ${Matlab_BINARIES_DIR})
@@ -1342,7 +1392,6 @@ _Matlab_find_library(
   NO_DEFAULT_PATH
 )
 
-
 list(APPEND _matlab_required_variables Matlab_MEX_LIBRARY)
 
 # the MEX extension is required
@@ -1351,7 +1400,6 @@ list(APPEND _matlab_required_variables Matlab_MEX_EXTENSION)
 # the matlab root is required
 list(APPEND _matlab_required_variables Matlab_ROOT_DIR)
 
-
 # component Mex Compiler
 list(FIND Matlab_FIND_COMPONENTS MEX_COMPILER _matlab_find_mex_compiler)
 if(_matlab_find_mex_compiler GREATER -1)
@@ -1362,7 +1410,6 @@ if(_matlab_find_mex_compiler GREATER -1)
     DOC "Matlab MEX compiler"
     NO_DEFAULT_PATH
   )
-
   if(Matlab_MEX_COMPILER)
     set(Matlab_MEX_COMPILER_FOUND TRUE)
   endif()
@@ -1372,7 +1419,6 @@ unset(_matlab_find_mex_compiler)
 # component Matlab program
 list(FIND Matlab_FIND_COMPONENTS MAIN_PROGRAM _matlab_find_matlab_program)
 if(_matlab_find_matlab_program GREATER -1)
-
   find_program(
     Matlab_MAIN_PROGRAM
     matlab
@@ -1380,11 +1426,9 @@ if(_matlab_find_matlab_program GREATER -1)
     DOC "Matlab main program"
     NO_DEFAULT_PATH
   )
-
   if(Matlab_MAIN_PROGRAM)
     set(Matlab_MAIN_PROGRAM_FOUND TRUE)
   endif()
-
 endif()
 unset(_matlab_find_matlab_program)
 
@@ -1398,14 +1442,12 @@ if(_matlab_find_mx GREATER -1)
     PATHS ${_matlab_lib_dir_for_search}
     NO_DEFAULT_PATH
   )
-
   if(Matlab_MX_LIBRARY)
     set(Matlab_MX_LIBRARY_FOUND TRUE)
   endif()
 endif()
 unset(_matlab_find_mx)
 
-
 # Component ENG library
 list(FIND Matlab_FIND_COMPONENTS ENG_LIBRARY _matlab_find_eng)
 if(_matlab_find_eng GREATER -1)
@@ -1422,15 +1464,41 @@ if(_matlab_find_eng GREATER -1)
 endif()
 unset(_matlab_find_eng)
 
-
-
-
+# Component MAT library
+list(FIND Matlab_FIND_COMPONENTS MAT_LIBRARY _matlab_find_mat)
+if(_matlab_find_mat GREATER -1)
+  _Matlab_find_library(
+    ${_matlab_lib_prefix_for_search}
+    Matlab_MAT_LIBRARY
+    mat
+    PATHS ${_matlab_lib_dir_for_search}
+    NO_DEFAULT_PATH
+  )
+  if(Matlab_MAT_LIBRARY)
+    set(Matlab_MAT_LIBRARY_FOUND TRUE)
+  endif()
+endif()
+unset(_matlab_find_mat)
+
+# Component Simulink
+list(FIND Matlab_FIND_COMPONENTS SIMULINK _matlab_find_simulink)
+if(_matlab_find_simulink GREATER -1)
+  find_path(
+    Matlab_SIMULINK_INCLUDE_DIR
+    simstruc.h
+    PATHS "${Matlab_ROOT_DIR}/simulink/include"
+    NO_DEFAULT_PATH
+    )
+  if(Matlab_SIMULINK_INCLUDE_DIR)
+    set(Matlab_SIMULINK_FOUND TRUE)
+    list(APPEND Matlab_INCLUDE_DIRS "${Matlab_SIMULINK_INCLUDE_DIR}")
+  endif()
+endif()
+unset(_matlab_find_simulink)
 
 unset(_matlab_lib_dir_for_search)
 
-
-set(Matlab_LIBRARIES ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY} ${Matlab_ENG_LIBRARY})
-
+set(Matlab_LIBRARIES ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY} ${Matlab_ENG_LIBRARY} ${Matlab_MAT_LIBRARY})
 
 find_package_handle_standard_args(
   Matlab
@@ -1449,18 +1517,14 @@ unset(_matlab_lib_prefix_for_search)
 
 if(Matlab_INCLUDE_DIRS AND Matlab_LIBRARIES)
   mark_as_advanced(
-    #Matlab_LIBRARIES
     Matlab_MEX_LIBRARY
     Matlab_MX_LIBRARY
     Matlab_ENG_LIBRARY
+    Matlab_MAT_LIBRARY
     Matlab_INCLUDE_DIRS
     Matlab_FOUND
-    #Matlab_ROOT_DIR
-    #Matlab_VERSION_STRING
     Matlab_MAIN_PROGRAM
-    #Matlab_MEX_EXTENSION
     Matlab_MEXEXTENSIONS_PROG
     Matlab_MEX_EXTENSION
-    #Matlab_BINARIES_DIR
   )
 endif()
diff --git a/Modules/FindMotif.cmake b/Modules/FindMotif.cmake
index a08ece4..3923238 100644
--- a/Modules/FindMotif.cmake
+++ b/Modules/FindMotif.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindMotif
 # ---------
@@ -12,19 +15,6 @@
 #   MOTIF_INCLUDE_DIR  - include paths to use Motif
 #   MOTIF_LIBRARIES    - Link these to use Motif
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(MOTIF_FOUND 0)
 
 if(UNIX)
diff --git a/Modules/FindOpenAL.cmake b/Modules/FindOpenAL.cmake
index eb63cef..1abb0d6 100644
--- a/Modules/FindOpenAL.cmake
+++ b/Modules/FindOpenAL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenAL
 # ----------
@@ -14,19 +17,6 @@
 # Created by Eric Wing.  This was influenced by the FindSDL.cmake
 # module.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # This makes the presumption that you are include al.h like
 # #include "al.h"
 # and not
diff --git a/Modules/FindOpenCL.cmake b/Modules/FindOpenCL.cmake
index 4d3ed84..3eca5e1 100644
--- a/Modules/FindOpenCL.cmake
+++ b/Modules/FindOpenCL.cmake
@@ -1,10 +1,22 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenCL
 # ----------
 #
 # Try to find OpenCL
 #
-# Once done this will define::
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines :prop_tgt:`IMPORTED` target ``OpenCL::OpenCL``, if
+# OpenCL has been found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the following variables::
 #
 #   OpenCL_FOUND          - True if OpenCL was found
 #   OpenCL_INCLUDE_DIRS   - include directories for OpenCL
@@ -19,19 +31,6 @@
 #   OpenCL_LIBRARY        - the path to the OpenCL library
 #
 
-#=============================================================================
-# Copyright 2014 Matthaeus G. Chajdas
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(_FIND_OPENCL_VERSION)
   include(CheckSymbolExists)
   include(CMakePushCheckState)
@@ -44,7 +43,7 @@ function(_FIND_OPENCL_VERSION)
     if(APPLE)
       CHECK_SYMBOL_EXISTS(
         CL_VERSION_${VERSION}
-        "${OpenCL_INCLUDE_DIR}/OpenCL/cl.h"
+        "${OpenCL_INCLUDE_DIR}/Headers/cl.h"
         OPENCL_VERSION_${VERSION})
     else()
       CHECK_SYMBOL_EXISTS(
@@ -134,3 +133,17 @@ find_package_handle_standard_args(
 mark_as_advanced(
   OpenCL_INCLUDE_DIR
   OpenCL_LIBRARY)
+
+if(OpenCL_FOUND AND NOT TARGET OpenCL::OpenCL)
+  if(OpenCL_LIBRARY MATCHES "/([^/]+)\\.framework$")
+    add_library(OpenCL::OpenCL INTERFACE IMPORTED)
+    set_target_properties(OpenCL::OpenCL PROPERTIES
+      INTERFACE_LINK_LIBRARIES "${OpenCL_LIBRARY}")
+  else()
+    add_library(OpenCL::OpenCL UNKNOWN IMPORTED)
+    set_target_properties(OpenCL::OpenCL PROPERTIES
+      IMPORTED_LOCATION "${OpenCL_LIBRARY}")
+  endif()
+  set_target_properties(OpenCL::OpenCL PROPERTIES
+    INTERFACE_INCLUDE_DIRECTORIES "${OpenCL_INCLUDE_DIRS}")
+endif()
diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake
index 93e488b..e487726 100644
--- a/Modules/FindOpenGL.cmake
+++ b/Modules/FindOpenGL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenGL
 # ----------
@@ -35,19 +38,6 @@
 # OPENGL_gl_LIBRARY to use OpenGL with X11 on OSX.
 
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(_OpenGL_REQUIRED_VARS OPENGL_gl_LIBRARY)
 
 if (CYGWIN)
diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake
index ee4bdd6..2ee9439 100644
--- a/Modules/FindOpenMP.cmake
+++ b/Modules/FindOpenMP.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenMP
 # ----------
@@ -12,33 +15,27 @@
 #
 # The following variables are set:
 #
-# ::
-#
-#    OpenMP_C_FLAGS - flags to add to the C compiler for OpenMP support
-#    OpenMP_CXX_FLAGS - flags to add to the CXX compiler for OpenMP support
-#    OpenMP_Fortran_FLAGS - flags to add to the Fortran compiler for OpenMP support
-#    OPENMP_FOUND - true if openmp is detected
-#
-#
+# ``OpenMP_C_FLAGS``
+#   Flags to add to the C compiler for OpenMP support.
+# ``OpenMP_CXX_FLAGS``
+#   Flags to add to the CXX compiler for OpenMP support.
+# ``OpenMP_Fortran_FLAGS``
+#   Flags to add to the Fortran compiler for OpenMP support.
+# ``OPENMP_FOUND``
+#   True if openmp is detected.
 #
-# Supported compilers can be found at
-# http://openmp.org/wp/openmp-compilers/
-
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2008-2009 André Rigland Brodtkorb <Andre.Brodtkorb at ifi.uio.no>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-# Copyright 2014 Nicolas Bock <nicolasbock at gmail.com>
+# The following internal variables are set, if detected:
 #
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
+# ``OpenMP_C_SPEC_DATE``
+#   Specification date of OpenMP version of C compiler.
+# ``OpenMP_CXX_SPEC_DATE``
+#   Specification date of OpenMP version of CXX compiler.
+# ``OpenMP_Fortran_SPEC_DATE``
+#   Specification date of OpenMP version of Fortran compiler.
 #
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# The specification dates are formatted as integers of the form
+# ``CCYYMM`` where these represent the decimal digits of the century,
+# year, and month.
 
 set(_OPENMP_REQUIRED_VARS)
 set(CMAKE_REQUIRED_QUIET_SAVE ${CMAKE_REQUIRED_QUIET})
@@ -122,6 +119,75 @@ set(OpenMP_Fortran_TEST_SOURCE
   "
   )
 
+set(OpenMP_C_CXX_CHECK_VERSION_SOURCE
+"
+#include <stdio.h>
+#include <omp.h>
+const char ompver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'M',
+                            'P', '-', 'd', 'a', 't', 'e', '[',
+                            ('0' + ((_OPENMP/100000)%10)),
+                            ('0' + ((_OPENMP/10000)%10)),
+                            ('0' + ((_OPENMP/1000)%10)),
+                            ('0' + ((_OPENMP/100)%10)),
+                            ('0' + ((_OPENMP/10)%10)),
+                            ('0' + ((_OPENMP/1)%10)),
+                            ']', '\\0' };
+int main(int argc, char *argv[])
+{
+  printf(\"%s\\n\", ompver_str);
+  return 0;
+}
+")
+
+set(OpenMP_Fortran_CHECK_VERSION_SOURCE
+"
+      program omp_ver
+      use omp_lib
+      integer, parameter :: zero = ichar('0')
+      integer, parameter :: ompv = openmp_version
+      character, dimension(24), parameter :: ompver_str =&
+      (/ 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'M', 'P', '-',&
+         'd', 'a', 't', 'e', '[',&
+         char(zero + mod(ompv/100000, 10)),&
+         char(zero + mod(ompv/10000, 10)),&
+         char(zero + mod(ompv/1000, 10)),&
+         char(zero + mod(ompv/100, 10)),&
+         char(zero + mod(ompv/10, 10)),&
+         char(zero + mod(ompv/1, 10)), ']' /)
+      print *, ompver_str
+      end program omp_ver
+")
+
+function(_OPENMP_GET_SPEC_DATE LANG SPEC_DATE)
+  set(WORK_DIR ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindOpenMP)
+  if("${LANG}" STREQUAL "C")
+    set(SRC_FILE ${WORK_DIR}/ompver.c)
+    file(WRITE ${SRC_FILE} "${OpenMP_C_CXX_CHECK_VERSION_SOURCE}")
+  elseif("${LANG}" STREQUAL "CXX")
+    set(SRC_FILE ${WORK_DIR}/ompver.cpp)
+    file(WRITE ${SRC_FILE} "${OpenMP_C_CXX_CHECK_VERSION_SOURCE}")
+  else() # ("${LANG}" STREQUAL "Fortran")
+    set(SRC_FILE ${WORK_DIR}/ompver.f90)
+    file(WRITE ${SRC_FILE} "${OpenMP_Fortran_CHECK_VERSION_SOURCE}")
+  endif()
+
+  set(BIN_FILE ${WORK_DIR}/ompver_${LANG}.bin)
+  try_compile(OpenMP_TRY_COMPILE_RESULT ${CMAKE_BINARY_DIR} ${SRC_FILE}
+              CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${OpenMP_${LANG}_FLAGS}"
+              COPY_FILE ${BIN_FILE})
+
+  if(${OpenMP_TRY_COMPILE_RESULT})
+    file(STRINGS ${BIN_FILE} specstr LIMIT_COUNT 1 REGEX "INFO:OpenMP-date")
+    set(regex_spec_date ".*INFO:OpenMP-date\\[0*([^]]*)\\].*")
+    if("${specstr}" MATCHES "${regex_spec_date}")
+      set(${SPEC_DATE} "${CMAKE_MATCH_1}" PARENT_SCOPE)
+    endif()
+  endif()
+
+  unset(OpenMP_TRY_COMPILE_RESULT CACHE)
+endfunction()
+
+
 # check c compiler
 if(CMAKE_C_COMPILER_LOADED)
   # if these are set then do not try to find them again,
@@ -153,6 +219,12 @@ if(CMAKE_C_COMPILER_LOADED)
 
   list(APPEND _OPENMP_REQUIRED_VARS OpenMP_C_FLAGS)
   unset(OpenMP_C_FLAG_CANDIDATES)
+
+  if (NOT OpenMP_C_SPEC_DATE)
+    _OPENMP_GET_SPEC_DATE("C" OpenMP_C_SPEC_DATE_INTERNAL)
+    set(OpenMP_C_SPEC_DATE "${OpenMP_C_SPEC_DATE_INTERNAL}" CACHE
+      INTERNAL "C compiler's OpenMP specification date")
+  endif()
 endif()
 
 # check cxx compiler
@@ -189,7 +261,12 @@ if(CMAKE_CXX_COMPILER_LOADED)
 
   list(APPEND _OPENMP_REQUIRED_VARS OpenMP_CXX_FLAGS)
   unset(OpenMP_CXX_FLAG_CANDIDATES)
-  unset(OpenMP_CXX_TEST_SOURCE)
+
+  if (NOT OpenMP_CXX_SPEC_DATE)
+    _OPENMP_GET_SPEC_DATE("CXX" OpenMP_CXX_SPEC_DATE_INTERNAL)
+    set(OpenMP_CXX_SPEC_DATE "${OpenMP_CXX_SPEC_DATE_INTERNAL}" CACHE
+      INTERNAL "C++ compiler's OpenMP specification date")
+  endif()
 endif()
 
 # check Fortran compiler
@@ -223,7 +300,12 @@ if(CMAKE_Fortran_COMPILER_LOADED)
 
   list(APPEND _OPENMP_REQUIRED_VARS OpenMP_Fortran_FLAGS)
   unset(OpenMP_Fortran_FLAG_CANDIDATES)
-  unset(OpenMP_Fortran_TEST_SOURCE)
+
+  if (NOT OpenMP_Fortran_SPEC_DATE)
+    _OPENMP_GET_SPEC_DATE("Fortran" OpenMP_Fortran_SPEC_DATE_INTERNAL)
+    set(OpenMP_Fortran_SPEC_DATE "${OpenMP_Fortran_SPEC_DATE_INTERNAL}" CACHE
+      INTERNAL "Fortran compiler's OpenMP specification date")
+  endif()
 endif()
 
 set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
@@ -240,3 +322,9 @@ if(_OPENMP_REQUIRED_VARS)
 else()
   message(SEND_ERROR "FindOpenMP requires C or CXX language to be enabled")
 endif()
+
+unset(OpenMP_C_TEST_SOURCE)
+unset(OpenMP_CXX_TEST_SOURCE)
+unset(OpenMP_Fortran_TEST_SOURCE)
+unset(OpenMP_C_CXX_CHECK_VERSION_SOURCE)
+unset(OpenMP_Fortran_CHECK_VERSION_SOURCE)
diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake
index 8dbaf11..30fc5c6 100644
--- a/Modules/FindOpenSSL.cmake
+++ b/Modules/FindOpenSSL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenSSL
 # -----------
@@ -39,21 +42,6 @@
 # Set ``OPENSSL_USE_STATIC_LIBS`` to ``TRUE`` to look for static libraries.
 # Set ``OPENSSL_MSVC_STATIC_RT`` set ``TRUE`` to choose the MT version of the lib.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-# Copyright 2009-2011 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (UNIX)
   find_package(PkgConfig QUIET)
   pkg_check_modules(_OPENSSL QUIET openssl)
@@ -133,22 +121,31 @@ if(WIN32 AND NOT CYGWIN)
       set(_OPENSSL_MSVC_RT_MODE "MD")
     endif ()
 
+    # Since OpenSSL 1.1, lib names are like libcrypto32MTd.lib and libssl32MTd.lib
+    if( "${CMAKE_SIZEOF_VOID_P}" STREQUAL "8" )
+        set(_OPENSSL_MSVC_ARCH_SUFFIX "64")
+    else()
+        set(_OPENSSL_MSVC_ARCH_SUFFIX "32")
+    endif()
+
     if(OPENSSL_USE_STATIC_LIBS)
       set(_OPENSSL_PATH_SUFFIXES
-        "lib"
-        "VC/static"
         "lib/VC/static"
+        "VC/static"
+        "lib"
         )
     else()
       set(_OPENSSL_PATH_SUFFIXES
-        "lib"
-        "VC"
         "lib/VC"
+        "VC"
+        "lib"
         )
     endif ()
 
     find_library(LIB_EAY_DEBUG
       NAMES
+        libcrypto${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
+        libcryptod
         libeay32${_OPENSSL_MSVC_RT_MODE}d
         libeay32d
       NAMES_PER_DIR
@@ -159,6 +156,8 @@ if(WIN32 AND NOT CYGWIN)
 
     find_library(LIB_EAY_RELEASE
       NAMES
+        libcrypto${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
+        libcrypto
         libeay32${_OPENSSL_MSVC_RT_MODE}
         libeay32
       NAMES_PER_DIR
@@ -169,6 +168,8 @@ if(WIN32 AND NOT CYGWIN)
 
     find_library(SSL_EAY_DEBUG
       NAMES
+        libssl${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
+        libssld
         ssleay32${_OPENSSL_MSVC_RT_MODE}d
         ssleay32d
       NAMES_PER_DIR
@@ -179,6 +180,8 @@ if(WIN32 AND NOT CYGWIN)
 
     find_library(SSL_EAY_RELEASE
       NAMES
+        libssl${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
+        libssl
         ssleay32${_OPENSSL_MSVC_RT_MODE}
         ssleay32
         ssl
@@ -212,8 +215,8 @@ if(WIN32 AND NOT CYGWIN)
       NAMES_PER_DIR
       ${_OPENSSL_ROOT_HINTS_AND_PATHS}
       PATH_SUFFIXES
-        "lib"
         "lib/MinGW"
+        "lib"
     )
 
     find_library(SSL_EAY
@@ -222,8 +225,8 @@ if(WIN32 AND NOT CYGWIN)
       NAMES_PER_DIR
       ${_OPENSSL_ROOT_HINTS_AND_PATHS}
       PATH_SUFFIXES
-        "lib"
         "lib/MinGW"
+        "lib"
     )
 
     mark_as_advanced(SSL_EAY LIB_EAY)
@@ -236,6 +239,7 @@ if(WIN32 AND NOT CYGWIN)
     # Not sure what to pick for -say- intel, let's use the toplevel ones and hope someone report issues:
     find_library(LIB_EAY
       NAMES
+        libcrypto
         libeay32
       NAMES_PER_DIR
       ${_OPENSSL_ROOT_HINTS_AND_PATHS}
@@ -247,6 +251,7 @@ if(WIN32 AND NOT CYGWIN)
 
     find_library(SSL_EAY
       NAMES
+        libssl
         ssleay32
       NAMES_PER_DIR
       ${_OPENSSL_ROOT_HINTS_AND_PATHS}
@@ -328,11 +333,11 @@ function(from_hex HEX DEC)
   set(${DEC} ${_res} PARENT_SCOPE)
 endfunction()
 
-if (OPENSSL_INCLUDE_DIR)
-  if(OPENSSL_INCLUDE_DIR AND EXISTS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h")
-    file(STRINGS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" openssl_version_str
-         REGEX "^#[\t ]*define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")
+if(OPENSSL_INCLUDE_DIR AND EXISTS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h")
+  file(STRINGS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" openssl_version_str
+       REGEX "^#[\t ]*define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")
 
+  if(openssl_version_str)
     # The version number is encoded as 0xMNNFFPPS: major minor fix patch status
     # The status gives if this is a developer or prerelease and is ignored here.
     # Major, minor, and fix directly translate into the version numbers shown in
@@ -399,13 +404,6 @@ if(OPENSSL_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES "C"
         IMPORTED_LOCATION "${OPENSSL_CRYPTO_LIBRARY}")
     endif()
-    if(EXISTS "${LIB_EAY_LIBRARY_DEBUG}")
-      set_property(TARGET OpenSSL::Crypto APPEND PROPERTY
-        IMPORTED_CONFIGURATIONS DEBUG)
-      set_target_properties(OpenSSL::Crypto PROPERTIES
-        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
-        IMPORTED_LOCATION_DEBUG "${LIB_EAY_LIBRARY_DEBUG}")
-    endif()
     if(EXISTS "${LIB_EAY_LIBRARY_RELEASE}")
       set_property(TARGET OpenSSL::Crypto APPEND PROPERTY
         IMPORTED_CONFIGURATIONS RELEASE)
@@ -413,6 +411,13 @@ if(OPENSSL_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
         IMPORTED_LOCATION_RELEASE "${LIB_EAY_LIBRARY_RELEASE}")
     endif()
+    if(EXISTS "${LIB_EAY_LIBRARY_DEBUG}")
+      set_property(TARGET OpenSSL::Crypto APPEND PROPERTY
+        IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(OpenSSL::Crypto PROPERTIES
+        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+        IMPORTED_LOCATION_DEBUG "${LIB_EAY_LIBRARY_DEBUG}")
+    endif()
   endif()
   if(NOT TARGET OpenSSL::SSL AND
       (EXISTS "${OPENSSL_SSL_LIBRARY}" OR
@@ -427,13 +432,6 @@ if(OPENSSL_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES "C"
         IMPORTED_LOCATION "${OPENSSL_SSL_LIBRARY}")
     endif()
-    if(EXISTS "${SSL_EAY_LIBRARY_DEBUG}")
-      set_property(TARGET OpenSSL::SSL APPEND PROPERTY
-        IMPORTED_CONFIGURATIONS DEBUG)
-      set_target_properties(OpenSSL::SSL PROPERTIES
-        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
-        IMPORTED_LOCATION_DEBUG "${SSL_EAY_LIBRARY_DEBUG}")
-    endif()
     if(EXISTS "${SSL_EAY_LIBRARY_RELEASE}")
       set_property(TARGET OpenSSL::SSL APPEND PROPERTY
         IMPORTED_CONFIGURATIONS RELEASE)
@@ -441,6 +439,13 @@ if(OPENSSL_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
         IMPORTED_LOCATION_RELEASE "${SSL_EAY_LIBRARY_RELEASE}")
     endif()
+    if(EXISTS "${SSL_EAY_LIBRARY_DEBUG}")
+      set_property(TARGET OpenSSL::SSL APPEND PROPERTY
+        IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(OpenSSL::SSL PROPERTIES
+        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+        IMPORTED_LOCATION_DEBUG "${SSL_EAY_LIBRARY_DEBUG}")
+    endif()
     if(TARGET OpenSSL::Crypto)
       set_target_properties(OpenSSL::SSL PROPERTIES
         INTERFACE_LINK_LIBRARIES OpenSSL::Crypto)
diff --git a/Modules/FindOpenSceneGraph.cmake b/Modules/FindOpenSceneGraph.cmake
index 5a800e4..af873fa 100644
--- a/Modules/FindOpenSceneGraph.cmake
+++ b/Modules/FindOpenSceneGraph.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenSceneGraph
 # ------------------
@@ -95,20 +98,6 @@
 #   add_executable(foo foo.cc)
 #   target_link_libraries(foo ${OPENSCENEGRAPH_LIBRARIES})
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009-2012 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # Naming convention:
 #  Local variables of the form _osg_foo
diff --git a/Modules/FindOpenThreads.cmake b/Modules/FindOpenThreads.cmake
index 69bab3d..54804b8 100644
--- a/Modules/FindOpenThreads.cmake
+++ b/Modules/FindOpenThreads.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindOpenThreads
 # ---------------
@@ -23,20 +26,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-# Copyright 2012 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <OpenThreads/Thread>
 
diff --git a/Modules/FindPHP4.cmake b/Modules/FindPHP4.cmake
index 25fff8c..426453b 100644
--- a/Modules/FindPHP4.cmake
+++ b/Modules/FindPHP4.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPHP4
 # --------
@@ -13,19 +16,6 @@
 #   PHP4_INCLUDE_PATH       = path to where php.h can be found
 #   PHP4_EXECUTABLE         = full path to the php4 binary
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(PHP4_POSSIBLE_INCLUDE_PATHS
   /usr/include/php4
   /usr/local/include/php4
@@ -58,8 +48,8 @@ mark_as_advanced(
 
 if(APPLE)
 # this is a hack for now
-  set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS
-   "${CMAKE_SHARED_MODULE_CREATE_C_FLAGS} -Wl,-flat_namespace")
+  string(APPEND CMAKE_SHARED_MODULE_CREATE_C_FLAGS
+   " -Wl,-flat_namespace")
   foreach(symbol
     __efree
     __emalloc
@@ -82,8 +72,8 @@ if(APPLE)
     _zend_wrong_param_count
     _zval_used_for_init
     )
-    set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS
-      "${CMAKE_SHARED_MODULE_CREATE_C_FLAGS},-U,${symbol}")
+    string(APPEND CMAKE_SHARED_MODULE_CREATE_C_FLAGS
+      ",-U,${symbol}")
   endforeach()
 endif()
 
diff --git a/Modules/FindPNG.cmake b/Modules/FindPNG.cmake
index 5050d91..6f94d50 100644
--- a/Modules/FindPNG.cmake
+++ b/Modules/FindPNG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPNG
 # -------
@@ -42,20 +45,6 @@
 # Since PNG depends on the ZLib compression library, none of the above
 # will be defined unless ZLib can be found.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-# Copyright 2016 Raumfeld
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(PNG_FIND_QUIETLY)
   set(_FIND_ZLIB_ARG QUIET)
 endif()
@@ -126,13 +115,6 @@ if(ZLIB_FOUND)
             IMPORTED_LINK_INTERFACE_LANGUAGES "C"
             IMPORTED_LOCATION "${PNG_LIBRARY}")
         endif()
-        if(EXISTS "${PNG_LIBRARY_DEBUG}")
-          set_property(TARGET PNG::PNG APPEND PROPERTY
-            IMPORTED_CONFIGURATIONS DEBUG)
-          set_target_properties(PNG::PNG PROPERTIES
-            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
-            IMPORTED_LOCATION_DEBUG "${PNG_LIBRARY_DEBUG}")
-        endif()
         if(EXISTS "${PNG_LIBRARY_RELEASE}")
           set_property(TARGET PNG::PNG APPEND PROPERTY
             IMPORTED_CONFIGURATIONS RELEASE)
@@ -140,6 +122,13 @@ if(ZLIB_FOUND)
             IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
             IMPORTED_LOCATION_RELEASE "${PNG_LIBRARY_RELEASE}")
         endif()
+        if(EXISTS "${PNG_LIBRARY_DEBUG}")
+          set_property(TARGET PNG::PNG APPEND PROPERTY
+            IMPORTED_CONFIGURATIONS DEBUG)
+          set_target_properties(PNG::PNG PROPERTIES
+            IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+            IMPORTED_LOCATION_DEBUG "${PNG_LIBRARY_DEBUG}")
+        endif()
       endif()
   endif ()
 
diff --git a/Modules/FindPackageHandleStandardArgs.cmake b/Modules/FindPackageHandleStandardArgs.cmake
index fe2dbea..7b46877 100644
--- a/Modules/FindPackageHandleStandardArgs.cmake
+++ b/Modules/FindPackageHandleStandardArgs.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 FindPackageHandleStandardArgs
 -----------------------------
@@ -126,19 +129,6 @@ directory for ``automoc4``.  Then the call to
 message.
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 
@@ -169,10 +159,10 @@ macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE)
       foreach(currentConfigIndex RANGE ${configsCount})
         list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename)
         list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version)
-        set(configsText "${configsText}    ${filename} (version ${version})\n")
+        string(APPEND configsText "    ${filename} (version ${version})\n")
       endforeach()
       if (${_NAME}_NOT_FOUND_MESSAGE)
-        set(configsText "${configsText}    Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n")
+        string(APPEND configsText "    Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n")
       endif()
       _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}")
 
@@ -253,9 +243,9 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
   foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS})
     if(NOT ${_CURRENT_VAR})
       set(FPHSA_FOUND_${_NAME} FALSE)
-      set(MISSING_VARS "${MISSING_VARS} ${_CURRENT_VAR}")
+      string(APPEND MISSING_VARS " ${_CURRENT_VAR}")
     else()
-      set(DETAILS "${DETAILS}[${${_CURRENT_VAR}}]")
+      string(APPEND DETAILS "[${${_CURRENT_VAR}}]")
     endif()
   endforeach()
   if(FPHSA_FOUND_${_NAME})
@@ -277,24 +267,24 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
         if(NOT DEFINED FOUND_COMPONENTS_MSG)
           set(FOUND_COMPONENTS_MSG "found components: ")
         endif()
-        set(FOUND_COMPONENTS_MSG "${FOUND_COMPONENTS_MSG} ${comp}")
+        string(APPEND FOUND_COMPONENTS_MSG " ${comp}")
 
       else()
 
         if(NOT DEFINED MISSING_COMPONENTS_MSG)
           set(MISSING_COMPONENTS_MSG "missing components: ")
         endif()
-        set(MISSING_COMPONENTS_MSG "${MISSING_COMPONENTS_MSG} ${comp}")
+        string(APPEND MISSING_COMPONENTS_MSG " ${comp}")
 
         if(${_NAME}_FIND_REQUIRED_${comp})
           set(${_NAME}_FOUND FALSE)
-          set(MISSING_VARS "${MISSING_VARS} ${comp}")
+          string(APPEND MISSING_VARS " ${comp}")
         endif()
 
       endif()
     endforeach()
     set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}")
-    set(DETAILS "${DETAILS}[c${COMPONENT_MSG}]")
+    string(APPEND DETAILS "[c${COMPONENT_MSG}]")
   endif()
 
   # version handling:
@@ -368,7 +358,7 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
   endif ()
 
   if(VERSION_OK)
-    set(DETAILS "${DETAILS}[v${VERSION}(${${_NAME}_FIND_VERSION})]")
+    string(APPEND DETAILS "[v${VERSION}(${${_NAME}_FIND_VERSION})]")
   else()
     set(${_NAME}_FOUND FALSE)
   endif()
diff --git a/Modules/FindPackageMessage.cmake b/Modules/FindPackageMessage.cmake
index a0349d3..6821cee 100644
--- a/Modules/FindPackageMessage.cmake
+++ b/Modules/FindPackageMessage.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPackageMessage
 # ------------------
@@ -26,19 +29,6 @@
 #    ...
 #   endif()
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(FIND_PACKAGE_MESSAGE pkg msg details)
   # Avoid printing a message repeatedly for the same find result.
   if(NOT ${pkg}_FIND_QUIETLY)
diff --git a/Modules/FindPerl.cmake b/Modules/FindPerl.cmake
index 70284b6..a0c8a33 100644
--- a/Modules/FindPerl.cmake
+++ b/Modules/FindPerl.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPerl
 # --------
@@ -12,19 +15,6 @@
 #   PERL_FOUND          - If false, don't attempt to use perl.
 #   PERL_VERSION_STRING - version of perl found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindCygwin.cmake)
 
 set(PERL_POSSIBLE_BIN_PATHS
diff --git a/Modules/FindPerlLibs.cmake b/Modules/FindPerlLibs.cmake
index 54ccd24..42729d7 100644
--- a/Modules/FindPerlLibs.cmake
+++ b/Modules/FindPerlLibs.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPerlLibs
 # ------------
@@ -37,20 +40,6 @@
 #   PERL_PRIVLIB       = path to the priv lib install directory
 #   PERL_EXTRA_C_FLAGS = Compilation flags used to build perl
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2008      Andreas Schneider <asn at cryptomilk.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # find the perl executable
 include(${CMAKE_CURRENT_LIST_DIR}/FindPerl.cmake)
 
diff --git a/Modules/FindPhysFS.cmake b/Modules/FindPhysFS.cmake
index ff584c7..fe5b397 100644
--- a/Modules/FindPhysFS.cmake
+++ b/Modules/FindPhysFS.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPhysFS
 # ----------
@@ -13,19 +16,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(PHYSFS_INCLUDE_DIR physfs.h
   HINTS
     ENV PHYSFSDIR
diff --git a/Modules/FindPike.cmake b/Modules/FindPike.cmake
index 2d6a03d..dff55a4 100644
--- a/Modules/FindPike.cmake
+++ b/Modules/FindPike.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPike
 # --------
@@ -13,19 +16,6 @@
 #   PIKE_INCLUDE_PATH       = path to where program.h is found
 #   PIKE_EXECUTABLE         = full path to the pike binary
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 file(GLOB PIKE_POSSIBLE_INCLUDE_PATHS
   /usr/include/pike/*
   /usr/local/include/pike/*)
diff --git a/Modules/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake
index b79e9df..072a27a 100644
--- a/Modules/FindPkgConfig.cmake
+++ b/Modules/FindPkgConfig.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPkgConfig
 # -------------
@@ -12,22 +15,6 @@
 # :variable:`PKG_CONFIG_EXECUTABLE` variable or the ``PKG_CONFIG``
 # environment variable first.
 
-#=============================================================================
-# Copyright 2006-2014 Kitware, Inc.
-# Copyright 2014      Christoph Grüninger <foss at grueninger.de>
-# Copyright 2006      Enrico Scholz <enrico.scholz at informatik.tu-chemnitz.de>
-# Copyright 2016      Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 ### Common stuff ####
 set(PKG_CONFIG_VERSION 1)
 
@@ -200,7 +187,7 @@ function(_pkg_create_imp_target _prefix _no_cmake_path _no_cmake_environment_pat
     set(_find_opts "NO_CMAKE_PATH")
   endif()
   if(_no_cmake_environment_path)
-    set(_find_opts "${_find_opts} NO_CMAKE_ENVIRONMENT_PATH")
+    string(APPEND _find_opts " NO_CMAKE_ENVIRONMENT_PATH")
   endif()
 
   foreach (flag IN LISTS ${_prefix}_LDFLAGS)
@@ -316,9 +303,13 @@ macro(_pkg_check_modules_internal _is_required _is_silent _no_cmake_path _no_cma
             list(APPEND _lib_dirs "lib/${CMAKE_LIBRARY_ARCHITECTURE}/pkgconfig")
           endif()
         else()
-          # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+          # not debian, check the FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS properties
+          get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
+          if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+            list(APPEND _lib_dirs "lib32/pkgconfig")
+          endif()
           get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-          if(uselib64)
+          if(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
             list(APPEND _lib_dirs "lib64/pkgconfig")
           endif()
         endif()
diff --git a/Modules/FindPostgreSQL.cmake b/Modules/FindPostgreSQL.cmake
index d05d3da..874128c 100644
--- a/Modules/FindPostgreSQL.cmake
+++ b/Modules/FindPostgreSQL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPostgreSQL
 # --------------
@@ -13,19 +16,6 @@
 #   PostgreSQL_LIBRARY_DIRS  - the link directories for PostgreSQL libraries
 #   PostgreSQL_VERSION_STRING - the version of PostgreSQL found (since CMake 2.8.8)
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # ----------------------------------------------------------------------------
 # History:
 # This module is derived from the module originally found in the VTK source tree.
@@ -37,7 +27,7 @@
 # In Windows the default installation of PostgreSQL uses that as part of the path.
 # E.g C:\Program Files\PostgreSQL\8.4.
 # Currently, the following version numbers are known to this module:
-# "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0"
+# "9.6" "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0"
 #
 # To use this variable just do something like this:
 # set(PostgreSQL_ADDITIONAL_VERSIONS "9.2" "8.4.4")
@@ -81,7 +71,7 @@ set(PostgreSQL_ROOT_DIR_MESSAGE "Set the PostgreSQL_ROOT system variable to wher
 
 
 set(PostgreSQL_KNOWN_VERSIONS ${PostgreSQL_ADDITIONAL_VERSIONS}
-    "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0")
+    "9.6" "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0")
 
 # Define additional search paths for root directories.
 set( PostgreSQL_ROOT_DIRECTORIES
@@ -186,7 +176,7 @@ set(PostgreSQL_FOUND  ${POSTGRESQL_FOUND})
 if(PostgreSQL_FOUND)
   set(PostgreSQL_INCLUDE_DIRS ${PostgreSQL_INCLUDE_DIR} ${PostgreSQL_TYPE_INCLUDE_DIR} )
   set(PostgreSQL_LIBRARY_DIRS ${PostgreSQL_LIBRARY_DIR} )
-  set(PostgreSQL_LIBRARIES ${PostgreSQL_LIBRARY_TO_FIND})
+  set(PostgreSQL_LIBRARIES ${PostgreSQL_LIBRARY})
 endif()
 
 mark_as_advanced(PostgreSQL_INCLUDE_DIR PostgreSQL_TYPE_INCLUDE_DIR PostgreSQL_LIBRARY )
diff --git a/Modules/FindProducer.cmake b/Modules/FindProducer.cmake
index aef84ea..500c8ed 100644
--- a/Modules/FindProducer.cmake
+++ b/Modules/FindProducer.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindProducer
 # ------------
@@ -28,19 +31,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <Producer/CameraGroup>
 
diff --git a/Modules/FindProtobuf.cmake b/Modules/FindProtobuf.cmake
index 2807bb9..14e392a 100644
--- a/Modules/FindProtobuf.cmake
+++ b/Modules/FindProtobuf.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindProtobuf
 # ------------
@@ -94,21 +97,6 @@
 #   ``ARGN``
 #     ``.proto`` filess
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009-2011 Philip Lowman <philip at yhbt.com>
-# Copyright 2008 Esben Mose Hansen, Ange Optimization ApS
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(PROTOBUF_GENERATE_CPP SRCS HDRS)
   if(NOT ARGN)
     message(SEND_ERROR "Error: PROTOBUF_GENERATE_CPP() called without any proto files")
@@ -148,6 +136,12 @@ function(PROTOBUF_GENERATE_CPP SRCS HDRS)
   foreach(FIL ${ARGN})
     get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
     get_filename_component(FIL_WE ${FIL} NAME_WE)
+    if(NOT PROTOBUF_GENERATE_CPP_APPEND_PATH)
+      get_filename_component(FIL_DIR ${FIL} DIRECTORY)
+      if(FIL_DIR)
+        set(FIL_WE "${FIL_DIR}/${FIL_WE}")
+      endif()
+    endif()
 
     list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc")
     list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h")
@@ -205,6 +199,12 @@ function(PROTOBUF_GENERATE_PYTHON SRCS)
   foreach(FIL ${ARGN})
     get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
     get_filename_component(FIL_WE ${FIL} NAME_WE)
+    if(NOT PROTOBUF_GENERATE_CPP_APPEND_PATH)
+      get_filename_component(FIL_DIR ${FIL} DIRECTORY)
+      if(FIL_DIR)
+        set(FIL_WE "${FIL_DIR}/${FIL_WE}")
+      endif()
+    endif()
 
     list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py")
     add_custom_command(
diff --git a/Modules/FindPythonInterp.cmake b/Modules/FindPythonInterp.cmake
index e194185..103e820 100644
--- a/Modules/FindPythonInterp.cmake
+++ b/Modules/FindPythonInterp.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPythonInterp
 # ----------------
@@ -33,26 +36,11 @@
 # get the currently active Python version by default with a consistent version
 # of PYTHON_LIBRARIES.
 
-#=============================================================================
-# Copyright 2005-2010 Kitware, Inc.
-# Copyright 2011 Bjoern Ricks <bjoern.ricks at gmail.com>
-# Copyright 2012 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 unset(_Python_NAMES)
 
 set(_PYTHON1_VERSIONS 1.6 1.5)
 set(_PYTHON2_VERSIONS 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0)
-set(_PYTHON3_VERSIONS 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
+set(_PYTHON3_VERSIONS 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
 
 if(PythonInterp_FIND_VERSION)
     if(PythonInterp_FIND_VERSION_COUNT GREATER 1)
diff --git a/Modules/FindPythonLibs.cmake b/Modules/FindPythonLibs.cmake
index ab92f86..1ebbf29 100644
--- a/Modules/FindPythonLibs.cmake
+++ b/Modules/FindPythonLibs.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindPythonLibs
 # --------------
@@ -37,19 +40,6 @@
 # get the currently active Python version by default with a consistent version
 # of PYTHON_LIBRARIES.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Use the executable's path as a hint
 set(_Python_LIBRARY_PATH_HINT)
 if(PYTHON_EXECUTABLE)
@@ -84,7 +74,7 @@ set(CMAKE_FIND_FRAMEWORK LAST)
 
 set(_PYTHON1_VERSIONS 1.6 1.5)
 set(_PYTHON2_VERSIONS 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0)
-set(_PYTHON3_VERSIONS 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
+set(_PYTHON3_VERSIONS 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
 
 if(PythonLibs_FIND_VERSION)
     if(PythonLibs_FIND_VERSION_COUNT GREATER 1)
diff --git a/Modules/FindQt.cmake b/Modules/FindQt.cmake
index 41b7271..4d8aea9 100644
--- a/Modules/FindQt.cmake
+++ b/Modules/FindQt.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindQt
 # ------
@@ -30,19 +33,6 @@
 #   QT4_INSTALLED is set to TRUE if qt4 is found.
 #   QT3_INSTALLED is set to TRUE if qt3 is found.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # look for signs of qt3 installations
 file(GLOB GLOB_TEMP_VAR /usr/lib*/qt-3*/bin/qmake /usr/lib*/qt3*/bin/qmake)
 if(GLOB_TEMP_VAR)
diff --git a/Modules/FindQt3.cmake b/Modules/FindQt3.cmake
index 86997ba..fa9f3a1 100644
--- a/Modules/FindQt3.cmake
+++ b/Modules/FindQt3.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindQt3
 # -------
@@ -35,19 +38,6 @@
 #  QT_WRAP_CPP, set true if QT_MOC_EXECUTABLE is found
 #  QT_WRAP_UI set true if QT_UIC_EXECUTABLE is found
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # If Qt4 has already been found, fail.
 if(QT4_FOUND)
   if(Qt3_FIND_REQUIRED)
diff --git a/Modules/FindQt4.cmake b/Modules/FindQt4.cmake
index d167a13..b0c49e5 100644
--- a/Modules/FindQt4.cmake
+++ b/Modules/FindQt4.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindQt4
 # -------
@@ -297,19 +300,6 @@
 # ``QT_VERSION_PATCH``
 #  The patch version of Qt found.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Use find_package( Qt4 COMPONENTS ... ) to enable modules
 if( Qt4_FIND_COMPONENTS )
   foreach( component ${Qt4_FIND_COMPONENTS} )
@@ -764,7 +754,7 @@ if (QT_QMAKE_EXECUTABLE AND
   #############################################
   cmake_push_check_state()
   # Add QT_INCLUDE_DIR to CMAKE_REQUIRED_INCLUDES
-  set(CMAKE_REQUIRED_INCLUDES "${CMAKE_REQUIRED_INCLUDES};${QT_INCLUDE_DIR}")
+  list(APPEND CMAKE_REQUIRED_INCLUDES "${QT_INCLUDE_DIR}")
   set(CMAKE_REQUIRED_QUIET ${Qt4_FIND_QUIETLY})
   # Check for Window system symbols (note: only one should end up being set)
   CHECK_CXX_SYMBOL_EXISTS(Q_WS_X11 "QtCore/qglobal.h" Q_WS_X11)
diff --git a/Modules/FindQuickTime.cmake b/Modules/FindQuickTime.cmake
index 2779269..2ee1899 100644
--- a/Modules/FindQuickTime.cmake
+++ b/Modules/FindQuickTime.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindQuickTime
 # -------------
@@ -13,19 +16,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(QUICKTIME_INCLUDE_DIR QuickTime/QuickTime.h QuickTime.h
   HINTS
     ENV QUICKTIME_DIR
diff --git a/Modules/FindRTI.cmake b/Modules/FindRTI.cmake
index 1aad0a8..b2ef076 100644
--- a/Modules/FindRTI.cmake
+++ b/Modules/FindRTI.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindRTI
 # -------
@@ -30,20 +33,6 @@
 #
 # Report problems to <certi-devel at nongnu.org>
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-# Copyright 2008 Petr Gotthard <gotthard at honeywell.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(RTI_MESSAGE_QUIETLY QUIET TYPE MSG)
   if(NOT ${QUIET})
     message(${TYPE} "${MSG}")
diff --git a/Modules/FindRuby.cmake b/Modules/FindRuby.cmake
index e5ea210..b0e9b47 100644
--- a/Modules/FindRuby.cmake
+++ b/Modules/FindRuby.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindRuby
 # --------
@@ -30,20 +33,6 @@
 # ``RUBY_INCLUDE_PATH``
 #   same as RUBY_INCLUDE_DIRS, only provided for compatibility reasons, don't use it
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2008-2009 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #   RUBY_ARCHDIR=`$RUBY -r rbconfig -e 'printf("%s",Config::CONFIG@<:@"archdir"@:>@)'`
 #   RUBY_SITEARCHDIR=`$RUBY -r rbconfig -e 'printf("%s",Config::CONFIG@<:@"sitearchdir"@:>@)'`
 #   RUBY_SITEDIR=`$RUBY -r rbconfig -e 'printf("%s",Config::CONFIG@<:@"sitelibdir"@:>@)'`
diff --git a/Modules/FindSDL.cmake b/Modules/FindSDL.cmake
index 45ca1d4..c0cdd98 100644
--- a/Modules/FindSDL.cmake
+++ b/Modules/FindSDL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL
 # -------
@@ -68,20 +71,6 @@
 # "SDL.h", not <SDL/SDL.h>.  This is done for portability reasons
 # because not all systems place things in SDL/ (see FreeBSD).
 
-#=============================================================================
-# Copyright 2003-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(SDL_INCLUDE_DIR SDL.h
   HINTS
     ENV SDLDIR
diff --git a/Modules/FindSDL_image.cmake b/Modules/FindSDL_image.cmake
index e7517c5..8cdaa7a 100644
--- a/Modules/FindSDL_image.cmake
+++ b/Modules/FindSDL_image.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL_image
 # -------------
@@ -33,20 +36,6 @@
 # module, but with modifications to recognize OS X frameworks and
 # additional Unix paths (FreeBSD, etc).
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT SDL_IMAGE_INCLUDE_DIR AND SDLIMAGE_INCLUDE_DIR)
   set(SDL_IMAGE_INCLUDE_DIR ${SDLIMAGE_INCLUDE_DIR} CACHE PATH "directory cache
 entry initialized from old variable name")
diff --git a/Modules/FindSDL_mixer.cmake b/Modules/FindSDL_mixer.cmake
index 72ec654..35233d1 100644
--- a/Modules/FindSDL_mixer.cmake
+++ b/Modules/FindSDL_mixer.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL_mixer
 # -------------
@@ -33,20 +36,6 @@
 # module, but with modifications to recognize OS X frameworks and
 # additional Unix paths (FreeBSD, etc).
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT SDL_MIXER_INCLUDE_DIR AND SDLMIXER_INCLUDE_DIR)
   set(SDL_MIXER_INCLUDE_DIR ${SDLMIXER_INCLUDE_DIR} CACHE PATH "directory cache
 entry initialized from old variable name")
diff --git a/Modules/FindSDL_net.cmake b/Modules/FindSDL_net.cmake
index 11c250c..b406946 100644
--- a/Modules/FindSDL_net.cmake
+++ b/Modules/FindSDL_net.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL_net
 # -----------
@@ -32,20 +35,6 @@
 # module, but with modifications to recognize OS X frameworks and
 # additional Unix paths (FreeBSD, etc).
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT SDL_NET_INCLUDE_DIR AND SDLNET_INCLUDE_DIR)
   set(SDL_NET_INCLUDE_DIR ${SDLNET_INCLUDE_DIR} CACHE PATH "directory cache
 entry initialized from old variable name")
diff --git a/Modules/FindSDL_sound.cmake b/Modules/FindSDL_sound.cmake
index 494d358..3198088 100644
--- a/Modules/FindSDL_sound.cmake
+++ b/Modules/FindSDL_sound.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL_sound
 # -------------
@@ -77,20 +80,6 @@
 # override this selectionor set the CMake environment CMAKE_INCLUDE_PATH
 # to modify the search paths.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(SDL_SOUND_EXTRAS "" CACHE STRING "SDL_sound extra flags")
 mark_as_advanced(SDL_SOUND_EXTRAS)
 
@@ -123,7 +112,7 @@ if(SDL_FOUND AND SDL_SOUND_INCLUDE_DIR AND SDL_SOUND_LIBRARY)
   # To get multiple single variables to work, I must separate them with a "\;"
   # I could go back and modify the FindSDL.cmake module, but that's kind of painful.
   # The solution would be to try something like:
-  # set(SDL_TRY_COMPILE_LIBRARY_LIST "${SDL_TRY_COMPILE_LIBRARY_LIST}\;${CMAKE_THREAD_LIBS_INIT}")
+  # string(APPEND SDL_TRY_COMPILE_LIBRARY_LIST "\;${CMAKE_THREAD_LIBS_INIT}")
   # Instead, it was suggested on the mailing list to write a temporary CMakeLists.txt
   # with a temporary test project and invoke that with TRY_COMPILE.
   # See message thread "Figuring out dependencies for a library in order to build"
@@ -173,7 +162,7 @@ if(SDL_FOUND AND SDL_SOUND_INCLUDE_DIR AND SDL_SOUND_LIBRARY)
    # would fix the problem.
    set(TMP_TRY_LIBS)
    foreach(lib ${SDL_SOUND_LIBRARY} ${SDL_LIBRARY})
-     set(TMP_TRY_LIBS "${TMP_TRY_LIBS} \"${lib}\"")
+     string(APPEND TMP_TRY_LIBS " \"${lib}\"")
    endforeach()
 
    # message("TMP_TRY_LIBS ${TMP_TRY_LIBS}")
diff --git a/Modules/FindSDL_ttf.cmake b/Modules/FindSDL_ttf.cmake
index 38f6e1d..aa705f2 100644
--- a/Modules/FindSDL_ttf.cmake
+++ b/Modules/FindSDL_ttf.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSDL_ttf
 # -----------
@@ -32,20 +35,6 @@
 # module, but with modifications to recognize OS X frameworks and
 # additional Unix paths (FreeBSD, etc).
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-# Copyright 2012 Benjamin Eikel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT SDL_TTF_INCLUDE_DIR AND SDLTTF_INCLUDE_DIR)
   set(SDL_TTF_INCLUDE_DIR ${SDLTTF_INCLUDE_DIR} CACHE PATH "directory cache
 entry initialized from old variable name")
diff --git a/Modules/FindSWIG.cmake b/Modules/FindSWIG.cmake
index 818d1f2..92c032f 100644
--- a/Modules/FindSWIG.cmake
+++ b/Modules/FindSWIG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSWIG
 # --------
@@ -22,21 +25,6 @@
 # to be found can be changed from the command line by means of setting
 # SWIG_EXECUTABLE
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2011 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-# Copyright 2014 Sylvain Joubert <joubert.sy at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(SWIG_EXECUTABLE NAMES swig3.0 swig2.0 swig)
 
 if(SWIG_EXECUTABLE)
diff --git a/Modules/FindSelfPackers.cmake b/Modules/FindSelfPackers.cmake
index 238be89..01d0641 100644
--- a/Modules/FindSelfPackers.cmake
+++ b/Modules/FindSelfPackers.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSelfPackers
 # ---------------
@@ -12,19 +15,6 @@
 #
 #   UPX: http://wildsau.idv.uni-linz.ac.at/mfx/upx.html
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindCygwin.cmake)
 
 find_program(SELF_PACKER_FOR_EXECUTABLE
diff --git a/Modules/FindSquish.cmake b/Modules/FindSquish.cmake
index 51e279d..6c8813c 100644
--- a/Modules/FindSquish.cmake
+++ b/Modules/FindSquish.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSquish
 # ----------
@@ -117,21 +120,6 @@
 #    This is deprecated. Use SQUISH_V3_ADD_TEST() if you are using Squish 3.x instead.
 
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-# Copyright 2012 Alexander Neundorf
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 include(CMakeParseArguments)
 
 set(SQUISH_INSTALL_DIR_STRING "Directory containing the bin, doc, and lib directories for Squish; this should be the root of the installation directory.")
diff --git a/Modules/FindSubversion.cmake b/Modules/FindSubversion.cmake
index 804f44c..537d3b2 100644
--- a/Modules/FindSubversion.cmake
+++ b/Modules/FindSubversion.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindSubversion
 # --------------
@@ -58,20 +61,6 @@
 #     message("Last changed log is ${Project_LAST_CHANGED_LOG}")
 #   endif()
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Tristan Carel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(Subversion_SVN_EXECUTABLE svn
   PATHS
     [HKEY_LOCAL_MACHINE\\Software\\TortoiseSVN;Directory]/bin
diff --git a/Modules/FindTCL.cmake b/Modules/FindTCL.cmake
index a83e277..12d6616 100644
--- a/Modules/FindTCL.cmake
+++ b/Modules/FindTCL.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindTCL
 # -------
@@ -41,19 +44,6 @@
 #       this point it is safer you ask directly where the *source* tree is
 #       and dig from there.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeFindFrameworks.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/FindTclsh.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/FindWish.cmake)
diff --git a/Modules/FindTIFF.cmake b/Modules/FindTIFF.cmake
index e600498..23ae308 100644
--- a/Modules/FindTIFF.cmake
+++ b/Modules/FindTIFF.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindTIFF
 # --------
@@ -36,20 +39,6 @@
 # ``TIFF_LIBRARY``
 #   the path to the TIFF library
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-# Copyright 2015 University of Dundee
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(TIFF_INCLUDE_DIR tiff.h)
 
 set(TIFF_NAMES ${TIFF_NAMES} tiff libtiff tiff3 libtiff3)
@@ -98,13 +87,6 @@ if(TIFF_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES "C"
         IMPORTED_LOCATION "${TIFF_LIBRARY}")
     endif()
-    if(EXISTS "${TIFF_LIBRARY_DEBUG}")
-      set_property(TARGET TIFF::TIFF APPEND PROPERTY
-        IMPORTED_CONFIGURATIONS DEBUG)
-      set_target_properties(TIFF::TIFF PROPERTIES
-        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
-        IMPORTED_LOCATION_DEBUG "${TIFF_LIBRARY_DEBUG}")
-    endif()
     if(EXISTS "${TIFF_LIBRARY_RELEASE}")
       set_property(TARGET TIFF::TIFF APPEND PROPERTY
         IMPORTED_CONFIGURATIONS RELEASE)
@@ -112,6 +94,13 @@ if(TIFF_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
         IMPORTED_LOCATION_RELEASE "${TIFF_LIBRARY_RELEASE}")
     endif()
+    if(EXISTS "${TIFF_LIBRARY_DEBUG}")
+      set_property(TARGET TIFF::TIFF APPEND PROPERTY
+        IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(TIFF::TIFF PROPERTIES
+        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+        IMPORTED_LOCATION_DEBUG "${TIFF_LIBRARY_DEBUG}")
+    endif()
   endif()
 endif()
 
diff --git a/Modules/FindTclStub.cmake b/Modules/FindTclStub.cmake
index 3c24f97..9711bd6 100644
--- a/Modules/FindTclStub.cmake
+++ b/Modules/FindTclStub.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindTclStub
 # -----------
@@ -41,19 +44,6 @@
 #       Let's leave that choice to the user by allowing him to assign
 #       TCL_STUB_LIBRARY to any Tcl library, debug or not.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindTCL.cmake)
 
 get_filename_component(TCL_TCLSH_PATH "${TCL_TCLSH}" PATH)
diff --git a/Modules/FindTclsh.cmake b/Modules/FindTclsh.cmake
index 2fd5332..c8a87ec 100644
--- a/Modules/FindTclsh.cmake
+++ b/Modules/FindTclsh.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindTclsh
 # ---------
@@ -16,19 +19,6 @@
 # In cygwin, look for the cygwin version first.  Don't look for it later
 # to avoid finding the cygwin version on a Win32 build.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(CYGWIN)
   find_program(TCL_TCLSH NAMES cygtclsh83 cygtclsh80)
 endif()
diff --git a/Modules/FindThreads.cmake b/Modules/FindThreads.cmake
index 719dace..2c6a58b 100644
--- a/Modules/FindThreads.cmake
+++ b/Modules/FindThreads.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindThreads
 # -----------
@@ -37,20 +40,6 @@
 # target. Use of both the imported target as well as this switch is highly
 # recommended for new code.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-# Copyright 2011-2015 Rolf Eike Beer <eike at sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include (CheckLibraryExists)
 include (CheckSymbolExists)
 set(Threads_FOUND FALSE)
diff --git a/Modules/FindUnixCommands.cmake b/Modules/FindUnixCommands.cmake
index 869ba38..d2b6a4d 100644
--- a/Modules/FindUnixCommands.cmake
+++ b/Modules/FindUnixCommands.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindUnixCommands
 # ----------------
@@ -7,19 +10,6 @@
 # This module looks for the Unix commands bash, cp, gzip, mv, rm, and tar
 # and stores the result in the variables BASH, CP, GZIP, MV, RM, and TAR.
 
-#=============================================================================
-# Copyright 2001-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindCygwin.cmake)
 
 find_program(BASH
diff --git a/Modules/FindVulkan.cmake b/Modules/FindVulkan.cmake
new file mode 100644
index 0000000..820e0eb
--- /dev/null
+++ b/Modules/FindVulkan.cmake
@@ -0,0 +1,75 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#.rst:
+# FindVulkan
+# ----------
+#
+# Try to find Vulkan
+#
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines :prop_tgt:`IMPORTED` target ``Vulkan::Vulkan``, if
+# Vulkan has been found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the following variables::
+#
+#   Vulkan_FOUND          - True if Vulkan was found
+#   Vulkan_INCLUDE_DIRS   - include directories for Vulkan
+#   Vulkan_LIBRARIES      - link against this library to use Vulkan
+#
+# The module will also define two cache variables::
+#
+#   Vulkan_INCLUDE_DIR    - the Vulkan include directory
+#   Vulkan_LIBRARY        - the path to the Vulkan library
+#
+
+if(WIN32)
+  find_path(Vulkan_INCLUDE_DIR
+    NAMES vulkan/vulkan.h
+    PATHS
+      "$ENV{VULKAN_SDK}/Include"
+    )
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+    find_library(Vulkan_LIBRARY
+      NAMES vulkan-1
+      PATHS
+        "$ENV{VULKAN_SDK}/Bin")
+  elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
+    find_library(Vulkan_LIBRARY
+      NAMES vulkan-1
+      PATHS
+        "$ENV{VULKAN_SDK}/Bin32")
+  endif()
+else()
+    find_path(Vulkan_INCLUDE_DIR
+      NAMES vulkan/vulkan.h
+      PATHS
+        "$ENV{VULKAN_SDK}/include")
+    find_library(Vulkan_LIBRARY
+      NAMES vulkan
+      PATHS
+        "$ENV{VULKAN_SDK}/lib")
+endif()
+
+set(Vulkan_LIBRARIES ${Vulkan_LIBRARY})
+set(Vulkan_INCLUDE_DIRS ${Vulkan_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(Vulkan
+  DEFAULT_MSG
+  Vulkan_LIBRARY Vulkan_INCLUDE_DIR)
+
+mark_as_advanced(Vulkan_INCLUDE_DIR Vulkan_LIBRARY)
+
+if(Vulkan_FOUND AND NOT TARGET Vulkan::Vulkan)
+  add_library(Vulkan::Vulkan UNKNOWN IMPORTED)
+  set_target_properties(Vulkan::Vulkan PROPERTIES
+    IMPORTED_LOCATION "${Vulkan_LIBRARIES}"
+    INTERFACE_INCLUDE_DIRECTORIES "${Vulkan_INCLUDE_DIRS}")
+endif()
diff --git a/Modules/FindWget.cmake b/Modules/FindWget.cmake
index b303b40..68419e2 100644
--- a/Modules/FindWget.cmake
+++ b/Modules/FindWget.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindWget
 # --------
@@ -11,19 +14,6 @@
 #   WGET_EXECUTABLE: the full path to the wget tool.
 #   WGET_FOUND: True if wget has been found.
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindCygwin.cmake)
 
 find_program(WGET_EXECUTABLE
diff --git a/Modules/FindWish.cmake b/Modules/FindWish.cmake
index df301b4..b64b041 100644
--- a/Modules/FindWish.cmake
+++ b/Modules/FindWish.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindWish
 # --------
@@ -16,19 +19,6 @@
 #
 # if UNIX is defined, then it will look for the cygwin version first
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(UNIX)
   find_program(TK_WISH cygwish80 )
 endif()
diff --git a/Modules/FindX11.cmake b/Modules/FindX11.cmake
index 90c1499..f7dfc82 100644
--- a/Modules/FindX11.cmake
+++ b/Modules/FindX11.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindX11
 # -------
@@ -51,19 +54,6 @@
 #   X11_Xv_INCLUDE_PATH,           X11_Xv_LIB,         X11_Xv_FOUND
 #   X11_XSync_INCLUDE_PATH,        (in X11_Xext_LIB),  X11_XSync_FOUND
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (UNIX)
   set(X11_FOUND 0)
   # X11 is never a framework and some header files may be
diff --git a/Modules/FindXCTest.cmake b/Modules/FindXCTest.cmake
index 805a58c..a97bb1b 100644
--- a/Modules/FindXCTest.cmake
+++ b/Modules/FindXCTest.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 FindXCTest
 ----------
@@ -58,19 +61,6 @@ The following variables are set by including this module:
 
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2015 Gregor Jasny
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_path(XCTest_INCLUDE_DIR
   NAMES "XCTest/XCTest.h"
   DOC "XCTest include directory")
diff --git a/Modules/FindXMLRPC.cmake b/Modules/FindXMLRPC.cmake
index 1491754..dd9dffc 100644
--- a/Modules/FindXMLRPC.cmake
+++ b/Modules/FindXMLRPC.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindXMLRPC
 # ----------
@@ -28,19 +31,6 @@
 #
 #   find_package(XMLRPC REQUIRED libwww-client)
 
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # First find the config script from which to obtain other values.
 find_program(XMLRPC_C_CONFIG NAMES xmlrpc-c-config)
 
diff --git a/Modules/FindXalanC.cmake b/Modules/FindXalanC.cmake
index 016b7aa..1951b49 100644
--- a/Modules/FindXalanC.cmake
+++ b/Modules/FindXalanC.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindXalanC
 # -----------
@@ -40,19 +43,6 @@
 
 # Written by Roger Leigh <rleigh at codelibre.net>
 
-#=============================================================================
-# Copyright 2016 University of Dundee
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(_XalanC_GET_VERSION  version_hdr)
     file(STRINGS ${version_hdr} _contents REGEX "^[ \t]*#define XALAN_VERSION_.*")
     if(_contents)
@@ -143,13 +133,6 @@ if(XalanC_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
         IMPORTED_LOCATION "${XalanC_LIBRARY}")
     endif()
-    if(EXISTS "${XalanC_LIBRARY_DEBUG}")
-      set_property(TARGET XalanC::XalanC APPEND PROPERTY
-        IMPORTED_CONFIGURATIONS DEBUG)
-      set_target_properties(XalanC::XalanC PROPERTIES
-        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
-        IMPORTED_LOCATION_DEBUG "${XalanC_LIBRARY_DEBUG}")
-    endif()
     if(EXISTS "${XalanC_LIBRARY_RELEASE}")
       set_property(TARGET XalanC::XalanC APPEND PROPERTY
         IMPORTED_CONFIGURATIONS RELEASE)
@@ -157,6 +140,13 @@ if(XalanC_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
         IMPORTED_LOCATION_RELEASE "${XalanC_LIBRARY_RELEASE}")
     endif()
+    if(EXISTS "${XalanC_LIBRARY_DEBUG}")
+      set_property(TARGET XalanC::XalanC APPEND PROPERTY
+        IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(XalanC::XalanC PROPERTIES
+        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+        IMPORTED_LOCATION_DEBUG "${XalanC_LIBRARY_DEBUG}")
+    endif()
     set_target_properties(XalanC::XalanC PROPERTIES INTERFACE_LINK_LIBRARIES XercesC::XercesC)
   endif()
 endif()
diff --git a/Modules/FindXercesC.cmake b/Modules/FindXercesC.cmake
index a4b80e5..51e68d5 100644
--- a/Modules/FindXercesC.cmake
+++ b/Modules/FindXercesC.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindXercesC
 # -----------
@@ -38,19 +41,6 @@
 
 # Written by Roger Leigh <rleigh at codelibre.net>
 
-#=============================================================================
-# Copyright 2014-2015 University of Dundee
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(_XercesC_GET_VERSION  version_hdr)
     file(STRINGS ${version_hdr} _contents REGEX "^[ \t]*#define XERCES_VERSION_.*")
     if(_contents)
@@ -122,13 +112,6 @@ if(XercesC_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
         IMPORTED_LOCATION "${XercesC_LIBRARY}")
     endif()
-    if(EXISTS "${XercesC_LIBRARY_DEBUG}")
-      set_property(TARGET XercesC::XercesC APPEND PROPERTY
-        IMPORTED_CONFIGURATIONS DEBUG)
-      set_target_properties(XercesC::XercesC PROPERTIES
-        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
-        IMPORTED_LOCATION_DEBUG "${XercesC_LIBRARY_DEBUG}")
-    endif()
     if(EXISTS "${XercesC_LIBRARY_RELEASE}")
       set_property(TARGET XercesC::XercesC APPEND PROPERTY
         IMPORTED_CONFIGURATIONS RELEASE)
@@ -136,5 +119,12 @@ if(XercesC_FOUND)
         IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
         IMPORTED_LOCATION_RELEASE "${XercesC_LIBRARY_RELEASE}")
     endif()
+    if(EXISTS "${XercesC_LIBRARY_DEBUG}")
+      set_property(TARGET XercesC::XercesC APPEND PROPERTY
+        IMPORTED_CONFIGURATIONS DEBUG)
+      set_target_properties(XercesC::XercesC PROPERTIES
+        IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
+        IMPORTED_LOCATION_DEBUG "${XercesC_LIBRARY_DEBUG}")
+    endif()
   endif()
 endif()
diff --git a/Modules/FindZLIB.cmake b/Modules/FindZLIB.cmake
index a57f450..5ee55b3 100644
--- a/Modules/FindZLIB.cmake
+++ b/Modules/FindZLIB.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindZLIB
 # --------
@@ -46,19 +49,6 @@
 # A user may set ``ZLIB_ROOT`` to a zlib installation root to tell this
 # module where to look.
 
-#=============================================================================
-# Copyright 2001-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(_ZLIB_SEARCHES)
 
 # Search ZLIB_ROOT first if it is set.
@@ -96,7 +86,7 @@ endif()
 unset(ZLIB_NAMES)
 unset(ZLIB_NAMES_DEBUG)
 
-mark_as_advanced(ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
+mark_as_advanced(ZLIB_INCLUDE_DIR)
 
 if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
     file(STRINGS "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_H REGEX "^#define ZLIB_VERSION \"[^\"]*\"$")
@@ -110,7 +100,7 @@ if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
     set(ZLIB_VERSION_TWEAK "")
     if( "${ZLIB_H}" MATCHES "ZLIB_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\\.([0-9]+)")
         set(ZLIB_VERSION_TWEAK "${CMAKE_MATCH_1}")
-        set(ZLIB_VERSION_STRING "${ZLIB_VERSION_STRING}.${ZLIB_VERSION_TWEAK}")
+        string(APPEND ZLIB_VERSION_STRING ".${ZLIB_VERSION_TWEAK}")
     endif()
 
     set(ZLIB_MAJOR_VERSION "${ZLIB_VERSION_MAJOR}")
diff --git a/Modules/Findosg.cmake b/Modules/Findosg.cmake
index 5ab2846..474ea82 100644
--- a/Modules/Findosg.cmake
+++ b/Modules/Findosg.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Findosg
 # -------
@@ -35,19 +38,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgUtil/SceneView>
diff --git a/Modules/FindosgAnimation.cmake b/Modules/FindosgAnimation.cmake
index 403e68e..5b26b64 100644
--- a/Modules/FindosgAnimation.cmake
+++ b/Modules/FindosgAnimation.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgAnimation
 # ----------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgAnimation/Animation>
diff --git a/Modules/FindosgDB.cmake b/Modules/FindosgDB.cmake
index 0e5bdef..6ddf53c 100644
--- a/Modules/FindosgDB.cmake
+++ b/Modules/FindosgDB.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgDB
 # ---------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgDB/DatabasePager>
diff --git a/Modules/FindosgFX.cmake b/Modules/FindosgFX.cmake
index 7b2cb76..e4bc276 100644
--- a/Modules/FindosgFX.cmake
+++ b/Modules/FindosgFX.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgFX
 # ---------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgFX/BumpMapping>
diff --git a/Modules/FindosgGA.cmake b/Modules/FindosgGA.cmake
index 2e80ff2..97adeb7 100644
--- a/Modules/FindosgGA.cmake
+++ b/Modules/FindosgGA.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgGA
 # ---------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgGA/FlightManipulator>
diff --git a/Modules/FindosgIntrospection.cmake b/Modules/FindosgIntrospection.cmake
index 1b52a6a..e735942 100644
--- a/Modules/FindosgIntrospection.cmake
+++ b/Modules/FindosgIntrospection.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgIntrospection
 # --------------------
@@ -30,19 +33,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgIntrospection/Reflection>
diff --git a/Modules/FindosgManipulator.cmake b/Modules/FindosgManipulator.cmake
index 6f54082..b88f1a4 100644
--- a/Modules/FindosgManipulator.cmake
+++ b/Modules/FindosgManipulator.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgManipulator
 # ------------------
@@ -30,19 +33,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgManipulator/TrackballDragger>
diff --git a/Modules/FindosgParticle.cmake b/Modules/FindosgParticle.cmake
index 82e9a13..059746a 100644
--- a/Modules/FindosgParticle.cmake
+++ b/Modules/FindosgParticle.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgParticle
 # ---------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgParticle/FireEffect>
diff --git a/Modules/FindosgPresentation.cmake b/Modules/FindosgPresentation.cmake
index 1cd57b3..84a4105 100644
--- a/Modules/FindosgPresentation.cmake
+++ b/Modules/FindosgPresentation.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgPresentation
 # -------------------
@@ -31,19 +34,6 @@
 # Created by Eric Wing.  Modified to work with osgPresentation by Robert
 # Osfield, January 2012.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgPresentation/SlideEventHandler>
diff --git a/Modules/FindosgProducer.cmake b/Modules/FindosgProducer.cmake
index ad4902b..e5700bf 100644
--- a/Modules/FindosgProducer.cmake
+++ b/Modules/FindosgProducer.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgProducer
 # ---------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgProducer/OsgSceneHandler>
diff --git a/Modules/FindosgQt.cmake b/Modules/FindosgQt.cmake
index b5c1718..04a2393 100644
--- a/Modules/FindosgQt.cmake
+++ b/Modules/FindosgQt.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgQt
 # ---------
@@ -29,19 +32,6 @@
 # Created by Eric Wing.  Modified to work with osgQt by Robert Osfield,
 # January 2012.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgQt/GraphicsWindowQt>
diff --git a/Modules/FindosgShadow.cmake b/Modules/FindosgShadow.cmake
index b0d22e7..0a7ba23 100644
--- a/Modules/FindosgShadow.cmake
+++ b/Modules/FindosgShadow.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgShadow
 # -------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgShadow/ShadowTexture>
diff --git a/Modules/FindosgSim.cmake b/Modules/FindosgSim.cmake
index ce088dc..15426a2 100644
--- a/Modules/FindosgSim.cmake
+++ b/Modules/FindosgSim.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgSim
 # ----------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgSim/ImpostorSprite>
diff --git a/Modules/FindosgTerrain.cmake b/Modules/FindosgTerrain.cmake
index bfde773..04eae14 100644
--- a/Modules/FindosgTerrain.cmake
+++ b/Modules/FindosgTerrain.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgTerrain
 # --------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgTerrain/Terrain>
diff --git a/Modules/FindosgText.cmake b/Modules/FindosgText.cmake
index 32cd115..1e2d9fd 100644
--- a/Modules/FindosgText.cmake
+++ b/Modules/FindosgText.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgText
 # -----------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgText/Text>
diff --git a/Modules/FindosgUtil.cmake b/Modules/FindosgUtil.cmake
index 9797425..13e0b80 100644
--- a/Modules/FindosgUtil.cmake
+++ b/Modules/FindosgUtil.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgUtil
 # -----------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgUtil/SceneView>
diff --git a/Modules/FindosgViewer.cmake b/Modules/FindosgViewer.cmake
index b355530..a91c49c 100644
--- a/Modules/FindosgViewer.cmake
+++ b/Modules/FindosgViewer.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgViewer
 # -------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgViewer/Viewer>
diff --git a/Modules/FindosgVolume.cmake b/Modules/FindosgVolume.cmake
index 8d3ad6c..1178ed3 100644
--- a/Modules/FindosgVolume.cmake
+++ b/Modules/FindosgVolume.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgVolume
 # -------------
@@ -29,19 +32,6 @@
 #
 # Created by Eric Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgVolume/Volume>
diff --git a/Modules/FindosgWidget.cmake b/Modules/FindosgWidget.cmake
index ec3c3bc..78999ec 100644
--- a/Modules/FindosgWidget.cmake
+++ b/Modules/FindosgWidget.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindosgWidget
 # -------------
@@ -30,19 +33,6 @@
 # FindosgWidget.cmake tweaked from Findosg* suite as created by Eric
 # Wing.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Header files are presumed to be included like
 # #include <osg/PositionAttitudeTransform>
 # #include <osgWidget/Widget>
diff --git a/Modules/Findosg_functions.cmake b/Modules/Findosg_functions.cmake
index d10fae9..c81c448 100644
--- a/Modules/Findosg_functions.cmake
+++ b/Modules/Findosg_functions.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Findosg_functions
 # -----------------
@@ -10,20 +13,6 @@
 # libraries and nodekits.  Please see FindOpenSceneGraph.cmake for full
 # documentation.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2009-2012 Philip Lowman <philip at yhbt.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # OSG_FIND_PATH
 #
diff --git a/Modules/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake
index 8c07e6c..77091f4 100644
--- a/Modules/FindwxWidgets.cmake
+++ b/Modules/FindwxWidgets.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindwxWidgets
 # -------------
@@ -104,20 +107,6 @@
 #    # and for each of your dependent executable/library targets:
 #    target_link_libraries(<YourTarget> ${wxWidgets_LIBRARIES})
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2007-2009 Miguel A. Figueroa-Villanueva <miguelf at ieee dot org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #
 # FIXME: check this and provide a correct sample usage...
 #        Remember to connect back to the upper text.
@@ -452,6 +441,7 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
       D:/
       ENV ProgramFiles
     PATH_SUFFIXES
+      wxWidgets-3.1.0
       wxWidgets-3.0.2
       wxWidgets-3.0.1
       wxWidgets-3.0.0
@@ -501,12 +491,27 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
     # Select one default tree inside the already determined wx tree.
     # Prefer static/shared order usually consistent with build
     # settings.
+    set(_WX_TOOL "")
+    set(_WX_TOOLVER "")
+    set(_WX_ARCH "")
     if(MINGW)
-      set(WX_LIB_DIR_PREFIX gcc)
-    elseif(CMAKE_CL_64)
-      set(WX_LIB_DIR_PREFIX vc_x64)
-    else()
-      set(WX_LIB_DIR_PREFIX vc)
+      set(_WX_TOOL gcc)
+    elseif(MSVC)
+      set(_WX_TOOL vc)
+      if(MSVC14)
+        set(_WX_TOOLVER 140)
+      elseif(MSVC12)
+        set(_WX_TOOLVER 120)
+      elseif(MSVC11)
+        set(_WX_TOOLVER 110)
+      elseif(MSVC10)
+        set(_WX_TOOLVER 100)
+      elseif(MSVC90)
+        set(_WX_TOOLVER 90)
+      endif()
+      if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+        set(_WX_ARCH _x64)
+      endif()
     endif()
     if(BUILD_SHARED_LIBS)
       find_path(wxWidgets_LIB_DIR
@@ -520,8 +525,10 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
           mswunivu/wx/setup.h
           mswunivud/wx/setup.h
         PATHS
-        ${WX_ROOT_DIR}/lib/${WX_LIB_DIR_PREFIX}_dll   # prefer shared
-        ${WX_ROOT_DIR}/lib/${WX_LIB_DIR_PREFIX}_lib
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_dll   # prefer shared
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_dll                 # prefer shared
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_lib
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_lib
         DOC "Path to wxWidgets libraries"
         NO_DEFAULT_PATH
         )
@@ -537,12 +544,17 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
           mswunivu/wx/setup.h
           mswunivud/wx/setup.h
         PATHS
-        ${WX_ROOT_DIR}/lib/${WX_LIB_DIR_PREFIX}_lib   # prefer static
-        ${WX_ROOT_DIR}/lib/${WX_LIB_DIR_PREFIX}_dll
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_lib   # prefer static
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_lib                 # prefer static
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_dll
+        ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_dll
         DOC "Path to wxWidgets libraries"
         NO_DEFAULT_PATH
         )
     endif()
+    unset(_WX_TOOL)
+    unset(_WX_TOOLVER)
+    unset(_WX_ARCH)
 
     # If wxWidgets_LIB_DIR changed, clear all libraries.
     if(NOT WX_LIB_DIR STREQUAL wxWidgets_LIB_DIR)
@@ -854,7 +866,7 @@ else()
           if(_retv EQUAL 0)
             file(TO_CMAKE_PATH ${_native_path} _native_path)
             DBG_MSG_V("Path ${_path} converted to ${_native_path}")
-            set(_tmp_path "${_tmp_path} ${_native_path}")
+            string(APPEND _tmp_path " ${_native_path}")
           endif()
         endforeach()
         DBG_MSG("Setting wxWidgets_INCLUDE_DIRS = ${_tmp_path}")
diff --git a/Modules/FindwxWindows.cmake b/Modules/FindwxWindows.cmake
index 6e441c3..76eb6be 100644
--- a/Modules/FindwxWindows.cmake
+++ b/Modules/FindwxWindows.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # FindwxWindows
 # -------------
@@ -77,20 +80,6 @@
 # AUTHOR Jan Woetzel <http://www.mip.informatik.uni-kiel.de/~jw>
 # (07/2003-01/2006)
 
-#=============================================================================
-# Copyright 2000-2009 Kitware, Inc.
-# Copyright 2003-2006 Jan Woetzel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # ------------------------------------------------------------------
 #
 # -removed OPTION for CMAKE_WXWINDOWS_USE_GL. Force the developer to SET it before calling this.
@@ -650,7 +639,7 @@ else()
 
       # do we need additionial wx GL stuff like GLCanvas ?
       if(WXWINDOWS_USE_GL)
-        set(WX_CONFIG_ARGS_LIBS "${WX_CONFIG_ARGS_LIBS} --gl-libs" )
+        string(APPEND WX_CONFIG_ARGS_LIBS " --gl-libs" )
       endif()
       ##message("DBG: WX_CONFIG_ARGS_LIBS=${WX_CONFIG_ARGS_LIBS}===")
 
diff --git a/Modules/FortranCInterface.cmake b/Modules/FortranCInterface.cmake
index c12dd4c..3899a2d 100644
--- a/Modules/FortranCInterface.cmake
+++ b/Modules/FortranCInterface.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 FortranCInterface
 -----------------
@@ -186,19 +189,6 @@ tells FortranCInterface to try given ``GLOBAL`` and ``MODULE`` manglings.
 are not needed.)
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #-----------------------------------------------------------------------------
 # Execute at most once in a project.
 if(FortranCInterface_SOURCE_DIR)
@@ -270,7 +260,7 @@ function(FortranCInterface_HEADER file)
   set(_desc_MODULE_ "/* Mangling for Fortran module symbols with underscores. */")
   foreach(macro GLOBAL GLOBAL_ MODULE MODULE_)
     if(FortranCInterface_${macro}_MACRO)
-      set(HEADER_CONTENT "${HEADER_CONTENT}
+      string(APPEND HEADER_CONTENT "
 ${_desc_${macro}}
 #define ${MACRO_NAMESPACE}${macro}${FortranCInterface_${macro}_MACRO}
 ")
@@ -279,7 +269,7 @@ ${_desc_${macro}}
 
   # Generate symbol mangling definitions.
   if(SYMBOLS)
-    set(HEADER_CONTENT "${HEADER_CONTENT}
+    string(APPEND HEADER_CONTENT "
 /*--------------------------------------------------------------------------*/
 /* Mangle some symbols automatically.                                       */
 ")
@@ -300,7 +290,7 @@ ${_desc_${macro}}
         set(form "")
       endif()
       if(FortranCInterface_MODULE${form}_MACRO)
-        set(HEADER_CONTENT "${HEADER_CONTENT}#define ${SYMBOL_NAMESPACE}${module}_${function} ${MACRO_NAMESPACE}MODULE${form}(${m_lower},${f_lower}, ${m_upper},${f_upper})\n")
+        string(APPEND HEADER_CONTENT "#define ${SYMBOL_NAMESPACE}${module}_${function} ${MACRO_NAMESPACE}MODULE${form}(${m_lower},${f_lower}, ${m_upper},${f_upper})\n")
       else()
         message(AUTHOR_WARNING "No FortranCInterface mangling known for ${f}")
       endif()
@@ -314,7 +304,7 @@ ${_desc_${macro}}
       string(TOUPPER "${f}" f_upper)
       string(TOLOWER "${f}" f_lower)
       if(FortranCInterface_GLOBAL${form}_MACRO)
-        set(HEADER_CONTENT "${HEADER_CONTENT}#define ${SYMBOL_NAMESPACE}${f} ${MACRO_NAMESPACE}GLOBAL${form}(${f_lower}, ${f_upper})\n")
+        string(APPEND HEADER_CONTENT "#define ${SYMBOL_NAMESPACE}${f} ${MACRO_NAMESPACE}GLOBAL${form}(${f_lower}, ${f_upper})\n")
       else()
         message(AUTHOR_WARNING "No FortranCInterface mangling known for ${f}")
       endif()
diff --git a/Modules/FortranCInterface/CMakeLists.txt b/Modules/FortranCInterface/CMakeLists.txt
index 721a262..dee57b5 100644
--- a/Modules/FortranCInterface/CMakeLists.txt
+++ b/Modules/FortranCInterface/CMakeLists.txt
@@ -1,13 +1,5 @@
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 cmake_minimum_required(VERSION ${CMAKE_VERSION})
 project(FortranCInterface C Fortran)
diff --git a/Modules/FortranCInterface/Detect.cmake b/Modules/FortranCInterface/Detect.cmake
index bee7dae..9984efd 100644
--- a/Modules/FortranCInterface/Detect.cmake
+++ b/Modules/FortranCInterface/Detect.cmake
@@ -1,13 +1,5 @@
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 configure_file(${FortranCInterface_SOURCE_DIR}/Input.cmake.in
                ${FortranCInterface_BINARY_DIR}/Input.cmake @ONLY)
diff --git a/Modules/FortranCInterface/Verify/CMakeLists.txt b/Modules/FortranCInterface/Verify/CMakeLists.txt
index cde3c53..98cdeb7 100644
--- a/Modules/FortranCInterface/Verify/CMakeLists.txt
+++ b/Modules/FortranCInterface/Verify/CMakeLists.txt
@@ -1,13 +1,5 @@
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 cmake_minimum_required(VERSION ${CMAKE_VERSION})
 project(VerifyFortranC C Fortran)
diff --git a/Modules/GNUInstallDirs.cmake b/Modules/GNUInstallDirs.cmake
index b42084e..059a2fc 100644
--- a/Modules/GNUInstallDirs.cmake
+++ b/Modules/GNUInstallDirs.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # GNUInstallDirs
 # --------------
@@ -99,21 +102,23 @@
 #   `Filesystem Hierarchy Standard`_.
 #
 # .. _`Filesystem Hierarchy Standard`: https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html
-
-#=============================================================================
-# Copyright 2015 Alex Turbov <i.zaufi at gmail.com>
-# Copyright 2011 Nikita Krupen'ko <krnekit at gmail.com>
-# Copyright 2011 Kitware, Inc.
 #
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
+# Macros
+# ^^^^^^
+#
+# .. command:: GNUInstallDirs_get_absolute_install_dir
 #
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+#   ::
+#
+#     GNUInstallDirs_get_absolute_install_dir(absvar var)
+#
+#   Set the given variable ``absvar`` to the absolute path contained
+#   within the variable ``var``.  This is to allow the computation of an
+#   absolute path, accounting for all the special cases documented
+#   above.  While this macro is used to compute the various
+#   ``CMAKE_INSTALL_FULL_<dir>`` variables, it is exposed publicly to
+#   allow users who create additional path variables to also compute
+#   absolute paths where necessary, using the same logic.
 
 # Installation directories
 #
@@ -248,7 +253,7 @@ if(NOT CMAKE_INSTALL_DATADIR)
   set(CMAKE_INSTALL_DATADIR "${CMAKE_INSTALL_DATAROOTDIR}")
 endif()
 
-if(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD")
+if(CMAKE_SYSTEM_NAME MATCHES "^(.*BSD|DragonFly)$")
   if(NOT CMAKE_INSTALL_INFODIR)
     set(CMAKE_INSTALL_INFODIR "" CACHE PATH "info documentation (info)")
     set(CMAKE_INSTALL_INFODIR "info")
@@ -300,55 +305,59 @@ mark_as_advanced(
   CMAKE_INSTALL_DOCDIR
   )
 
-# Result directories
-#
-foreach(dir
-    BINDIR
-    SBINDIR
-    LIBEXECDIR
-    SYSCONFDIR
-    SHAREDSTATEDIR
-    LOCALSTATEDIR
-    LIBDIR
-    INCLUDEDIR
-    OLDINCLUDEDIR
-    DATAROOTDIR
-    DATADIR
-    INFODIR
-    LOCALEDIR
-    MANDIR
-    DOCDIR
-    )
-  if(NOT IS_ABSOLUTE "${CMAKE_INSTALL_${dir}}")
+macro(GNUInstallDirs_get_absolute_install_dir absvar var)
+  if(NOT IS_ABSOLUTE "${${var}}")
     # Handle special cases:
     # - CMAKE_INSTALL_PREFIX == /
     # - CMAKE_INSTALL_PREFIX == /usr
     # - CMAKE_INSTALL_PREFIX == /opt/...
     if("${CMAKE_INSTALL_PREFIX}" STREQUAL "/")
       if("${dir}" STREQUAL "SYSCONFDIR" OR "${dir}" STREQUAL "LOCALSTATEDIR")
-        set(CMAKE_INSTALL_FULL_${dir} "/${CMAKE_INSTALL_${dir}}")
+        set(${absvar} "/${${var}}")
       else()
-        if (NOT "${CMAKE_INSTALL_${dir}}" MATCHES "^usr/")
-          set(CMAKE_INSTALL_${dir} "usr/${CMAKE_INSTALL_${dir}}")
+        if (NOT "${${var}}" MATCHES "^usr/")
+          set(${var} "usr/${${var}}")
         endif()
-        set(CMAKE_INSTALL_FULL_${dir} "/${CMAKE_INSTALL_${dir}}")
+        set(${absvar} "/${${var}}")
       endif()
     elseif("${CMAKE_INSTALL_PREFIX}" MATCHES "^/usr/?$")
       if("${dir}" STREQUAL "SYSCONFDIR" OR "${dir}" STREQUAL "LOCALSTATEDIR")
-        set(CMAKE_INSTALL_FULL_${dir} "/${CMAKE_INSTALL_${dir}}")
+        set(${absvar} "/${${var}}")
       else()
-        set(CMAKE_INSTALL_FULL_${dir} "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_${dir}}")
+        set(${absvar} "${CMAKE_INSTALL_PREFIX}/${${var}}")
       endif()
     elseif("${CMAKE_INSTALL_PREFIX}" MATCHES "^/opt/.*")
       if("${dir}" STREQUAL "SYSCONFDIR" OR "${dir}" STREQUAL "LOCALSTATEDIR")
-        set(CMAKE_INSTALL_FULL_${dir} "/${CMAKE_INSTALL_${dir}}${CMAKE_INSTALL_PREFIX}")
+        set(${absvar} "/${${var}}${CMAKE_INSTALL_PREFIX}")
       else()
-        set(CMAKE_INSTALL_FULL_${dir} "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_${dir}}")
+        set(${absvar} "${CMAKE_INSTALL_PREFIX}/${${var}}")
       endif()
     else()
-      set(CMAKE_INSTALL_FULL_${dir} "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_${dir}}")
+      set(${absvar} "${CMAKE_INSTALL_PREFIX}/${${var}}")
     endif()
   else()
-    set(CMAKE_INSTALL_FULL_${dir} "${CMAKE_INSTALL_${dir}}")
+    set(${absvar} "${${var}}")
   endif()
+endmacro()
+
+# Result directories
+#
+foreach(dir
+    BINDIR
+    SBINDIR
+    LIBEXECDIR
+    SYSCONFDIR
+    SHAREDSTATEDIR
+    LOCALSTATEDIR
+    LIBDIR
+    INCLUDEDIR
+    OLDINCLUDEDIR
+    DATAROOTDIR
+    DATADIR
+    INFODIR
+    LOCALEDIR
+    MANDIR
+    DOCDIR
+    )
+  GNUInstallDirs_get_absolute_install_dir(CMAKE_INSTALL_FULL_${dir} CMAKE_INSTALL_${dir})
 endforeach()
diff --git a/Modules/GenerateExportHeader.cmake b/Modules/GenerateExportHeader.cmake
index 6389d30..c201714 100644
--- a/Modules/GenerateExportHeader.cmake
+++ b/Modules/GenerateExportHeader.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # GenerateExportHeader
 # --------------------
@@ -20,6 +23,7 @@
 #              [NO_DEPRECATED_MACRO_NAME <no_deprecated_macro_name>]
 #              [DEFINE_NO_DEPRECATED]
 #              [PREFIX_NAME <prefix_name>]
+#              [CUSTOM_CONTENT_FROM_VARIABLE <variable>]
 #    )
 #
 #
@@ -60,8 +64,10 @@
 # The CMake fragment will generate a file in the
 # ``${CMAKE_CURRENT_BINARY_DIR}`` called ``somelib_export.h`` containing the
 # macros ``SOMELIB_EXPORT``, ``SOMELIB_NO_EXPORT``, ``SOMELIB_DEPRECATED``,
-# ``SOMELIB_DEPRECATED_EXPORT`` and ``SOMELIB_DEPRECATED_NO_EXPORT``.  The
-# resulting file should be installed with other headers in the library.
+# ``SOMELIB_DEPRECATED_EXPORT`` and ``SOMELIB_DEPRECATED_NO_EXPORT``.
+# They will be followed by content taken from the variable specified by
+# the ``CUSTOM_CONTENT_FROM_VARIABLE`` option, if any.
+# The resulting file should be installed with other headers in the library.
 #
 # The ``BASE_NAME`` argument can be used to override the file name and the
 # names used for the macros:
@@ -78,7 +84,7 @@
 # ``OTHER_NAME_EXPORT``, ``OTHER_NAME_NO_EXPORT`` and ``OTHER_NAME_DEPRECATED``
 # etc.
 #
-# The ``BASE_NAME`` may be overridden by specifiying other options in the
+# The ``BASE_NAME`` may be overridden by specifying other options in the
 # function.  For example:
 #
 # .. code-block:: cmake
@@ -178,19 +184,6 @@
 # :prop_tgt:`CXX_VISIBILITY_PRESET <<LANG>_VISIBILITY_PRESET>` and
 # :prop_tgt:`VISIBILITY_INLINES_HIDDEN` instead.
 
-#=============================================================================
-# Copyright 2011 Stephen Kelly <steveire at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CMakeParseArguments)
 include(CheckCXXCompilerFlag)
 
@@ -205,7 +198,7 @@ macro(_test_compiler_hidden_visibility)
 
   if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.2")
     set(GCC_TOO_OLD TRUE)
-  elseif(CMAKE_COMPILER_IS_GNUC AND CMAKE_C_COMPILER_VERSION VERSION_LESS "4.2")
+  elseif(CMAKE_COMPILER_IS_GNUCC AND CMAKE_C_COMPILER_VERSION VERSION_LESS "4.2")
     set(GCC_TOO_OLD TRUE)
   elseif(CMAKE_CXX_COMPILER_ID MATCHES Intel AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "12.0")
     set(_INTEL_TOO_OLD TRUE)
@@ -288,7 +281,7 @@ macro(_DO_GENERATE_EXPORT_HEADER TARGET_LIBRARY)
   set(options DEFINE_NO_DEPRECATED)
   set(oneValueArgs PREFIX_NAME BASE_NAME EXPORT_MACRO_NAME EXPORT_FILE_NAME
     DEPRECATED_MACRO_NAME NO_EXPORT_MACRO_NAME STATIC_DEFINE
-    NO_DEPRECATED_MACRO_NAME)
+    NO_DEPRECATED_MACRO_NAME CUSTOM_CONTENT_FROM_VARIABLE)
   set(multiValueArgs)
 
   cmake_parse_arguments(_GEH "${options}" "${oneValueArgs}" "${multiValueArgs}"
@@ -361,6 +354,14 @@ macro(_DO_GENERATE_EXPORT_HEADER TARGET_LIBRARY)
   endif()
   string(MAKE_C_IDENTIFIER ${EXPORT_IMPORT_CONDITION} EXPORT_IMPORT_CONDITION)
 
+  if(_GEH_CUSTOM_CONTENT_FROM_VARIABLE)
+    if(DEFINED "${_GEH_CUSTOM_CONTENT_FROM_VARIABLE}")
+      set(CUSTOM_CONTENT "${${_GEH_CUSTOM_CONTENT_FROM_VARIABLE}}")
+    else()
+      set(CUSTOM_CONTENT "")
+    endif()
+  endif()
+
   configure_file("${_GENERATE_EXPORT_HEADER_MODULE_DIR}/exportheader.cmake.in"
     "${EXPORT_FILE_NAME}" @ONLY)
 endmacro()
@@ -404,6 +405,7 @@ function(add_compiler_export_flags)
   if(ARGC GREATER 0)
     set(${ARGV0} "${EXTRA_FLAGS}" PARENT_SCOPE)
   else()
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_FLAGS}" PARENT_SCOPE)
+    string(APPEND CMAKE_CXX_FLAGS " ${EXTRA_FLAGS}")
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE)
   endif()
 endfunction()
diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake
index fb7bf93..5ab9dc5 100644
--- a/Modules/GetPrerequisites.cmake
+++ b/Modules/GetPrerequisites.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # GetPrerequisites
 # ----------------
@@ -162,19 +165,6 @@
 #    embedded
 #    other
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(gp_append_unique list_var value)
   set(contains 0)
 
@@ -544,7 +534,7 @@ function(gp_resolved_file_type original_file file exepath dirs type_var)
       string(TOLOWER "$ENV{windir}" windir)
       file(TO_CMAKE_PATH "${windir}" windir)
 
-      if(lower MATCHES "^(api-ms-win-|${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*msvc[^/]+dll)")
+      if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-)[^/]+dll)")
         set(is_system 1)
       endif()
 
@@ -572,7 +562,7 @@ function(gp_resolved_file_type original_file file exepath dirs type_var)
           string(TOLOWER "${env_windir}" windir)
           string(TOLOWER "${env_sysdir}" sysroot)
 
-          if(lower MATCHES "^(api-ms-win-|${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*msvc[^/]+dll)")
+          if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-)[^/]+dll)")
             set(is_system 1)
           endif()
         endif()
@@ -751,9 +741,13 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa
     set(gp_regex_fallback "")
     set(gp_regex_cmp_count 1)
     # objdump generates copious output so we create a grep filter to pre-filter results
-    find_program(gp_grep_cmd grep)
+    if(WIN32)
+      find_program(gp_grep_cmd findstr)
+    else()
+      find_program(gp_grep_cmd grep)
+    endif()
     if(gp_grep_cmd)
-      set(gp_cmd_maybe_filter COMMAND ${gp_grep_cmd} "^[[:blank:]]*DLL Name: ")
+      set(gp_cmd_maybe_filter COMMAND ${gp_grep_cmd} "-a" "^[[:blank:]]*DLL Name: ")
     endif()
   else()
     message(STATUS "warning: gp_tool='${gp_tool}' is an unknown tool...")
@@ -796,7 +790,7 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa
     set(old_ld_env "$ENV{LD_LIBRARY_PATH}")
     set(new_ld_env "${exepath}")
     foreach(dir ${dirs})
-      set(new_ld_env "${new_ld_env}:${dir}")
+      string(APPEND new_ld_env ":${dir}")
     endforeach()
     set(ENV{LD_LIBRARY_PATH} "${new_ld_env}:$ENV{LD_LIBRARY_PATH}")
   endif()
diff --git a/Modules/ITKCompatibility.cmake b/Modules/ITKCompatibility.cmake
index ca2d69b..fef0653 100644
--- a/Modules/ITKCompatibility.cmake
+++ b/Modules/ITKCompatibility.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # work around an old bug in ITK prior to verison 3.0
 set(TIFF_RIGHT_VERSION 1)
diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake
index 1c6e751..b0446c9 100644
--- a/Modules/InstallRequiredSystemLibraries.cmake
+++ b/Modules/InstallRequiredSystemLibraries.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # InstallRequiredSystemLibraries
 # ------------------------------
@@ -48,19 +51,6 @@
 #   Specify the :command:`install(PROGRAMS)` command ``COMPONENT``
 #   option.  If not specified, no such option will be used.
 
-#=============================================================================
-# Copyright 2006-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(MSVC)
   file(TO_CMAKE_PATH "$ENV{SYSTEMROOT}" SYSTEMROOT)
 
diff --git a/Modules/KDE3Macros.cmake b/Modules/KDE3Macros.cmake
index 07864f5..b3f31ed 100644
--- a/Modules/KDE3Macros.cmake
+++ b/Modules/KDE3Macros.cmake
@@ -1,18 +1,7 @@
-#
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
 #
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # See FindKDE3.cmake for documentation.
 #
diff --git a/Modules/MacroAddFileDependencies.cmake b/Modules/MacroAddFileDependencies.cmake
index 38df1d3..db26814 100644
--- a/Modules/MacroAddFileDependencies.cmake
+++ b/Modules/MacroAddFileDependencies.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # MacroAddFileDependencies
 # ------------------------
@@ -12,19 +15,6 @@
 # You can just use set_property(SOURCE <file> APPEND PROPERTY
 # OBJECT_DEPENDS depend_files) instead.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro (MACRO_ADD_FILE_DEPENDENCIES _file)
 
    get_source_file_property(_deps ${_file} OBJECT_DEPENDS)
diff --git a/Modules/MatlabTestsRedirect.cmake b/Modules/MatlabTestsRedirect.cmake
index 77b7afe..a0c6621 100644
--- a/Modules/MatlabTestsRedirect.cmake
+++ b/Modules/MatlabTestsRedirect.cmake
@@ -1,20 +1,9 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 # This is an undocumented internal helper for the FindMatlab
 # module ``matlab_add_unit_test`` command.
 
-#=============================================================================
-# Copyright 2014-2015 Raffi Enficiaud, Max Planck Society
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 # Usage: cmake
 #   -Dtest_timeout=180
 #   -Doutput_directory=
@@ -23,11 +12,12 @@
 #   -DMatlab_PROGRAM=matlab_exe_location
 #   -DMatlab_ADDITIONNAL_STARTUP_OPTIONS=""
 #   -Dtest_name=name_of_the_test
+#   -Dcustom_Matlab_test_command=""
 #   -Dcmd_to_run_before_test=""
 #   -Dunittest_file_to_run
 #   -P FindMatlab_TestsRedirect.cmake
 
-set(Matlab_UNIT_TESTS_CMD -nosplash -nojvm -nodesktop -nodisplay ${Matlab_ADDITIONNAL_STARTUP_OPTIONS})
+set(Matlab_UNIT_TESTS_CMD -nosplash -nodesktop -nodisplay ${Matlab_ADDITIONNAL_STARTUP_OPTIONS})
 if(WIN32)
   set(Matlab_UNIT_TESTS_CMD ${Matlab_UNIT_TESTS_CMD} -wait)
 endif()
@@ -36,6 +26,13 @@ if(NOT test_timeout)
   set(test_timeout 180)
 endif()
 
+# If timeout is -1, then do not put a timeout on the execute_process
+if(test_timeout EQUAL -1)
+  set(test_timeout "")
+else()
+  set(test_timeout TIMEOUT ${test_timeout})
+endif()
+
 if(NOT cmd_to_run_before_test)
   set(cmd_to_run_before_test)
 endif()
@@ -46,20 +43,34 @@ get_filename_component(unittest_file_to_run_name "${unittest_file_to_run}" NAME_
 set(concat_string '${unittest_file_directory}')
 foreach(s IN LISTS additional_paths)
   if(NOT "${s}" STREQUAL "")
-    set(concat_string "${concat_string}, '${s}'")
+    string(APPEND concat_string ", '${s}'")
   endif()
 endforeach()
 
-set(unittest_to_run "runtests('${unittest_file_to_run_name}'), exit(max([ans(1,:).Failed]))")
+if(custom_Matlab_test_command)
+  set(unittest_to_run "${custom_Matlab_test_command}")
+else()
+  set(unittest_to_run "runtests('${unittest_file_to_run_name}'), exit(max([ans(1,:).Failed]))")
+endif()
+
+
 if(no_unittest_framework)
   set(unittest_to_run "try, ${unittest_file_to_run_name}, catch err, disp('An exception has been thrown during the execution'), disp(err), disp(err.stack), exit(1), end, exit(0)")
 endif()
 
 set(Matlab_SCRIPT_TO_RUN
-    "addpath(${concat_string}), path, ${cmd_to_run_before_test}, ${unittest_to_run}"
+    "addpath(${concat_string}); ${cmd_to_run_before_test}; ${unittest_to_run}"
    )
+# if the working directory is not specified then default
+# to the output_directory because the log file will go there
+# if the working_directory is specified it will override the
+# output_directory
+if(NOT working_directory)
+  set(working_directory "${output_directory}")
+endif()
 
-set(Matlab_LOG_FILE "${output_directory}/${test_name}.log")
+string(REPLACE "/" "_" log_file_name "${test_name}.log")
+set(Matlab_LOG_FILE "${working_directory}/${log_file_name}")
 
 set(devnull)
 if(UNIX)
@@ -69,11 +80,14 @@ elseif(WIN32)
 endif()
 
 execute_process(
-  COMMAND "${Matlab_PROGRAM}" ${Matlab_UNIT_TESTS_CMD} -logfile "${test_name}.log" -r "${Matlab_SCRIPT_TO_RUN}"
+  # Do not use a full path to log file.  Depend on the fact that the log file
+  # is always going to go in the working_directory.  This is because matlab
+  # on unix is a shell script that does not handle spaces in the logfile path.
+  COMMAND "${Matlab_PROGRAM}" ${Matlab_UNIT_TESTS_CMD} -logfile "${log_file_name}" -r "${Matlab_SCRIPT_TO_RUN}"
   RESULT_VARIABLE res
-  TIMEOUT ${test_timeout}
+  ${test_timeout}
   OUTPUT_QUIET # we do not want the output twice
-  WORKING_DIRECTORY "${output_directory}"
+  WORKING_DIRECTORY "${working_directory}"
   ${devnull}
   )
 
@@ -87,5 +101,5 @@ message("Matlab test ${name_of_the_test} output:\n${matlab_log_content}") # if w
 
 
 if(NOT (res EQUAL 0))
-  message( FATAL_ERROR "[MATLAB] TEST FAILED" )
+  message( FATAL_ERROR "[MATLAB] TEST FAILED Matlab returned ${res}" )
 endif()
diff --git a/Modules/NSIS.template.in b/Modules/NSIS.template.in
index 92a3142..9001888 100644
--- a/Modules/NSIS.template.in
+++ b/Modules/NSIS.template.in
@@ -157,13 +157,6 @@ Var AR_RegFlags
   !define MUI_HEADERIMAGE
   !define MUI_ABORTWARNING
 
-;--------------------------------
-; path functions
-
-!verbose 3
-!include "WinMessages.NSH"
-!verbose 4
-
 ;----------------------------------------
 ; based upon a script of "Written by KiCHiK 2003-01-18 05:57:02"
 ;----------------------------------------
@@ -912,7 +905,7 @@ Function .onInit
 
   MessageBox MB_YESNOCANCEL|MB_ICONEXCLAMATION \
   "@CPACK_NSIS_PACKAGE_NAME@ is already installed. $\n$\nDo you want to uninstall the old version before installing the new one?" \
-  IDYES uninst IDNO inst
+  /SD IDYES IDYES uninst IDNO inst
   Abort
 
 ;Run the uninstaller
@@ -920,7 +913,7 @@ uninst:
   ClearErrors
   StrLen $2 "\Uninstall.exe"
   StrCpy $3 $0 -$2 # remove "\Uninstall.exe" from UninstallString to get path
-  ExecWait '"$0" _?=$3' ;Do not copy the uninstaller to a temp file
+  ExecWait '"$0" /S _?=$3' ;Do not copy the uninstaller to a temp file
 
   IfErrors uninst_failed inst
 uninst_failed:
diff --git a/Modules/Platform/AIX-Clang-C.cmake b/Modules/Platform/AIX-Clang-C.cmake
new file mode 100644
index 0000000..0e8a1c0
--- /dev/null
+++ b/Modules/Platform/AIX-Clang-C.cmake
@@ -0,0 +1 @@
+include(Platform/AIX-GNU-C)
diff --git a/Modules/Platform/AIX-Clang-CXX.cmake b/Modules/Platform/AIX-Clang-CXX.cmake
new file mode 100644
index 0000000..6b9110e
--- /dev/null
+++ b/Modules/Platform/AIX-Clang-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/AIX-GNU-CXX)
diff --git a/Modules/Platform/AIX-GNU-CXX.cmake b/Modules/Platform/AIX-GNU-CXX.cmake
index ec8e83f..d047801 100644
--- a/Modules/Platform/AIX-GNU-CXX.cmake
+++ b/Modules/Platform/AIX-GNU-CXX.cmake
@@ -1,2 +1,3 @@
 include(Platform/AIX-GNU)
 __aix_compiler_gnu(CXX)
+unset(CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN)
diff --git a/Modules/Platform/AIX-GNU.cmake b/Modules/Platform/AIX-GNU.cmake
index d6f5331..ca6e97c 100644
--- a/Modules/Platform/AIX-GNU.cmake
+++ b/Modules/Platform/AIX-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__AIX_COMPILER_GNU)
@@ -21,9 +11,9 @@ set(__AIX_COMPILER_GNU 1)
 #
 # By default, runtime linking is enabled. All shared objects specified on the command line
 # will be listed, even if there are no symbols referenced, in the output file.
-set (CMAKE_SHARED_LINKER_FLAGS_INIT "-Wl,-brtl")
-set (CMAKE_MODULE_LINKER_FLAGS_INIT "-Wl,-brtl")
-set (CMAKE_EXE_LINKER_FLAGS_INIT "-Wl,-brtl")
+string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " -Wl,-brtl")
+string(APPEND CMAKE_MODULE_LINKER_FLAGS_INIT " -Wl,-brtl")
+string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " -Wl,-brtl")
 
 
 macro(__aix_compiler_gnu lang)
@@ -34,4 +24,5 @@ macro(__aix_compiler_gnu lang)
   set(CMAKE_${lang}_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH 1)
 
   set(CMAKE_${lang}_LINK_FLAGS "-Wl,-bnoipath")
+  unset(CMAKE_${lang}_COMPILE_OPTIONS_VISIBILITY)
 endmacro()
diff --git a/Modules/Platform/AIX-XL.cmake b/Modules/Platform/AIX-XL.cmake
index 5470441..b3078ff 100644
--- a/Modules/Platform/AIX-XL.cmake
+++ b/Modules/Platform/AIX-XL.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__AIX_COMPILER_XL)
@@ -21,9 +11,9 @@ set(__AIX_COMPILER_XL 1)
 #
 # By default, runtime linking is enabled. All shared objects specified on the command line
 # will be listed, even if there are no symbols referenced, in the output file.
-set(CMAKE_SHARED_LINKER_FLAGS_INIT "-Wl,-brtl")
-set(CMAKE_MODULE_LINKER_FLAGS_INIT "-Wl,-brtl")
-set(CMAKE_EXE_LINKER_FLAGS_INIT "-Wl,-brtl")
+string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " -Wl,-brtl")
+string(APPEND CMAKE_MODULE_LINKER_FLAGS_INIT " -Wl,-brtl")
+string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " -Wl,-brtl")
 
 
 macro(__aix_compiler_xl lang)
diff --git a/Modules/Platform/ARTOS-GNU-C.cmake b/Modules/Platform/ARTOS-GNU-C.cmake
index 967d0e7..fe8d782 100644
--- a/Modules/Platform/ARTOS-GNU-C.cmake
+++ b/Modules/Platform/ARTOS-GNU-C.cmake
@@ -1,9 +1,9 @@
 # Define ARTOS to select proper behaviour and tell preprocessor to accept C++ style comments.
-set(CMAKE_C_FLAGS_INIT "-DARTOS -Xp -+")
+string(APPEND CMAKE_C_FLAGS_INIT " -DARTOS -Xp -+")
 # ac doesn't support -g properly and doesn't support the normal gcc optimization options. Just use the defaults set by ac.
-set(CMAKE_C_FLAGS_DEBUG_INIT "")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "-DNDEBUG")
-set(CMAKE_C_FLAGS_RELEASE_INIT "-DNDEBUG")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " ")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -DNDEBUG")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -DNDEBUG")
 # Most projects expect the stdio functions to be available.
 set(CMAKE_C_STANDARD_LIBRARIES_INIT "stdio.a")
diff --git a/Modules/Platform/Android-Clang-C.cmake b/Modules/Platform/Android-Clang-C.cmake
new file mode 100644
index 0000000..9e16911
--- /dev/null
+++ b/Modules/Platform/Android-Clang-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android-Clang)
+__android_compiler_clang(C)
diff --git a/Modules/Platform/Android-Clang-CXX.cmake b/Modules/Platform/Android-Clang-CXX.cmake
new file mode 100644
index 0000000..7111836
--- /dev/null
+++ b/Modules/Platform/Android-Clang-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android-Clang)
+__android_compiler_clang(CXX)
diff --git a/Modules/Platform/Android-Clang.cmake b/Modules/Platform/Android-Clang.cmake
new file mode 100644
index 0000000..f0cf4a5
--- /dev/null
+++ b/Modules/Platform/Android-Clang.cmake
@@ -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.
+
+# This module is shared by multiple languages; use include blocker.
+if(__ANDROID_COMPILER_CLANG)
+  return()
+endif()
+set(__ANDROID_COMPILER_CLANG 1)
+
+# Support for NVIDIA Nsight Tegra Visual Studio Edition was previously
+# implemented in the CMake VS IDE generators.  Avoid interfering with
+# that functionality for now.  Later we may try to integrate this.
+if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+  macro(__android_compiler_clang lang)
+  endmacro()
+  return()
+endif()
+
+# Commonly used Android toolchain files that pre-date CMake upstream support
+# set CMAKE_SYSTEM_VERSION to 1.  Avoid interfering with them.
+if(CMAKE_SYSTEM_VERSION EQUAL 1)
+  macro(__android_compiler_clang lang)
+  endmacro()
+  return()
+endif()
+
+include(Platform/Android-Common)
+
+# The NDK toolchain configuration files at:
+#
+#   <ndk>/[build/core/]toolchains/*-clang*/setup.mk
+#
+# contain logic to set LLVM_TRIPLE for Clang-based toolchains for each target.
+# We need to produce the same target here to produce compatible binaries.
+include(Platform/Android/abi-${CMAKE_ANDROID_ARCH_ABI}-Clang)
+
+macro(__android_compiler_clang lang)
+  __android_compiler_common(${lang})
+  if(NOT CMAKE_${lang}_COMPILER_TARGET)
+    set(CMAKE_${lang}_COMPILER_TARGET "${_ANDROID_ABI_CLANG_TARGET}")
+  endif()
+endmacro()
diff --git a/Modules/Platform/Android-Common.cmake b/Modules/Platform/Android-Common.cmake
new file mode 100644
index 0000000..6544696
--- /dev/null
+++ b/Modules/Platform/Android-Common.cmake
@@ -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.
+
+# This module is shared by multiple languages; use include blocker.
+if(__ANDROID_COMPILER_COMMON)
+  return()
+endif()
+set(__ANDROID_COMPILER_COMMON 1)
+
+if(CMAKE_ANDROID_NDK)
+  # <ndk>/build/core/definitions.mk
+
+  set(_ANDROID_STL_TYPES
+    none
+    system
+    c++_static
+    c++_shared
+    gabi++_static
+    gabi++_shared
+    gnustl_static
+    gnustl_shared
+    stlport_static
+    stlport_shared
+    )
+
+  if(CMAKE_ANDROID_STL_TYPE)
+    list(FIND _ANDROID_STL_TYPES "${CMAKE_ANDROID_STL_TYPE}" _ANDROID_STL_TYPE_FOUND)
+    if(_ANDROID_STL_TYPE_FOUND EQUAL -1)
+      string(REPLACE ";" "\n  " _msg ";${_ANDROID_STL_TYPES}")
+      message(FATAL_ERROR
+        "The CMAKE_ANDROID_STL_TYPE '${CMAKE_ANDROID_STL_TYPE}' is not one of the allowed values:${_msg}\n"
+        )
+    endif()
+    unset(_ANDROID_STL_TYPE_FOUND)
+  else()
+    set(CMAKE_ANDROID_STL_TYPE "gnustl_static")
+  endif()
+
+  unset(_ANDROID_STL_TYPES)
+
+  # Forward Android-specific platform variables to try_compile projects.
+  list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES
+    CMAKE_ANDROID_STL_TYPE
+    )
+endif()
+
+if(CMAKE_ANDROID_STL_TYPE)
+  if(CMAKE_ANDROID_NDK)
+
+    macro(__android_stl_inc lang dir req)
+      if(EXISTS "${dir}")
+        list(APPEND CMAKE_${lang}_STANDARD_INCLUDE_DIRECTORIES "${dir}")
+      elseif(${req})
+        message(FATAL_ERROR
+          "Android: STL '${CMAKE_ANDROID_STL_TYPE}' include directory not found:\n"
+          "  ${dir}"
+          )
+      endif()
+    endmacro()
+
+    macro(__android_stl_lib lang lib req)
+      if(CMAKE_ANDROID_ARCH_ABI MATCHES "^armeabi" AND NOT CMAKE_ANDROID_ARM_MODE)
+        get_filename_component(_ANDROID_STL_LIBDIR "${lib}" DIRECTORY)
+        get_filename_component(_ANDROID_STL_LIBNAME "${lib}" NAME)
+        set(_ANDROID_STL_LIBTHUMB "${_ANDROID_STL_LIBDIR}/thumb/${_ANDROID_STL_LIBNAME}")
+        unset(_ANDROID_STL_LIBDIR)
+        unset(_ANDROID_STL_LIBNAME)
+      else()
+        set(_ANDROID_STL_LIBTHUMB "")
+      endif()
+
+      if(_ANDROID_STL_LIBTHUMB AND EXISTS "${_ANDROID_STL_LIBTHUMB}")
+        string(APPEND CMAKE_${lang}_STANDARD_LIBRARIES " \"${_ANDROID_STL_LIBTHUMB}\"")
+      elseif(EXISTS "${lib}")
+        string(APPEND CMAKE_${lang}_STANDARD_LIBRARIES " \"${lib}\"")
+      elseif(${req})
+        message(FATAL_ERROR
+          "Android: STL '${CMAKE_ANDROID_STL_TYPE}' library file not found:\n"
+          "  ${lib}"
+          )
+      endif()
+
+      unset(_ANDROID_STL_LIBTHUMB)
+    endmacro()
+
+    include(Platform/Android/ndk-stl-${CMAKE_ANDROID_STL_TYPE})
+  else()
+    macro(__android_stl lang)
+    endmacro()
+  endif()
+else()
+  macro(__android_stl lang)
+  endmacro()
+endif()
+
+# The NDK toolchain configuration files at:
+#
+#   <ndk>/[build/core/]toolchains/*/setup.mk
+#
+# contain logic to set TARGET_CFLAGS and TARGET_LDFLAGS (and debug/release
+# variants) to tell their build system what flags to pass for each ABI.
+# We need to produce the same flags here to produce compatible binaries.
+# We initialize these variables here and set them in the compiler-specific
+# modules that include this one.  Then we use them in the macro below when
+# it is called.
+set(_ANDROID_ABI_INIT_CFLAGS "")
+set(_ANDROID_ABI_INIT_CFLAGS_DEBUG "")
+set(_ANDROID_ABI_INIT_CFLAGS_RELEASE "")
+set(_ANDROID_ABI_INIT_LDFLAGS "")
+
+macro(__android_compiler_common lang)
+  if(_ANDROID_ABI_INIT_CFLAGS)
+    string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_ANDROID_ABI_INIT_CFLAGS}")
+  endif()
+  if(_ANDROID_ABI_INIT_CFLAGS_DEBUG)
+    string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " ${_ANDROID_ABI_INIT_CFLAGS_DEBUG}")
+  endif()
+  if(_ANDROID_ABI_INIT_CFLAGS_RELEASE)
+    string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " ${_ANDROID_ABI_INIT_CFLAGS_RELEASE}")
+    string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " ${_ANDROID_ABI_INIT_CFLAGS_RELEASE}")
+    string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " ${_ANDROID_ABI_INIT_CFLAGS_RELEASE}")
+  endif()
+  if(_ANDROID_ABI_INIT_LDFLAGS)
+    foreach(t EXE SHARED MODULE)
+      string(APPEND CMAKE_${t}_LINKER_FLAGS_INIT " ${_ANDROID_ABI_INIT_LDFLAGS}")
+    endforeach()
+  endif()
+
+  if(DEFINED _ANDROID_STL_EXCEPTIONS)
+    if(_ANDROID_STL_EXCEPTIONS)
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " -fexceptions")
+    else()
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " -fno-exceptions")
+    endif()
+  endif()
+
+  if("x${lang}" STREQUAL "xCXX" AND DEFINED _ANDROID_STL_RTTI)
+    if(_ANDROID_STL_RTTI)
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " -frtti")
+    else()
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " -fno-rtti")
+    endif()
+  endif()
+
+  if("x${lang}" STREQUAL "xCXX")
+    __android_stl(CXX)
+  endif()
+endmacro()
diff --git a/Modules/Platform/Android-Determine-C.cmake b/Modules/Platform/Android-Determine-C.cmake
new file mode 100644
index 0000000..c7d1d15
--- /dev/null
+++ b/Modules/Platform/Android-Determine-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android/Determine-Compiler)
+__android_determine_compiler(C)
diff --git a/Modules/Platform/Android-Determine-CXX.cmake b/Modules/Platform/Android-Determine-CXX.cmake
new file mode 100644
index 0000000..3a3de88
--- /dev/null
+++ b/Modules/Platform/Android-Determine-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android/Determine-Compiler)
+__android_determine_compiler(CXX)
diff --git a/Modules/Platform/Android-Determine.cmake b/Modules/Platform/Android-Determine.cmake
new file mode 100644
index 0000000..6d370ab
--- /dev/null
+++ b/Modules/Platform/Android-Determine.cmake
@@ -0,0 +1,291 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# When CMAKE_SYSTEM_NAME is "Android", CMakeDetermineSystem loads this module.
+# This module detects platform-wide information about the Android target
+# in order to store it in "CMakeSystem.cmake".
+
+# Support for NVIDIA Nsight Tegra Visual Studio Edition was previously
+# implemented in the CMake VS IDE generators.  Avoid interfering with
+# that functionality for now.  Later we may try to integrate this.
+if(CMAKE_GENERATOR MATCHES "Visual Studio")
+  return()
+endif()
+
+# Commonly used Android toolchain files that pre-date CMake upstream support
+# set CMAKE_SYSTEM_VERSION to 1.  Avoid interfering with them.
+if(CMAKE_SYSTEM_VERSION EQUAL 1)
+  return()
+endif()
+
+# If the user provided CMAKE_SYSROOT for us, extract information from it.
+set(_ANDROID_SYSROOT_NDK "")
+set(_ANDROID_SYSROOT_API "")
+set(_ANDROID_SYSROOT_ARCH "")
+set(_ANDROID_SYSROOT_STANDALONE_TOOLCHAIN "")
+if(CMAKE_SYSROOT)
+  if(NOT IS_DIRECTORY "${CMAKE_SYSROOT}")
+    message(FATAL_ERROR
+      "Android: The specified CMAKE_SYSROOT:\n"
+      "  ${CMAKE_SYSROOT}\n"
+      "is not an existing directory."
+      )
+  endif()
+  if(CMAKE_SYSROOT MATCHES "^([^\\\n]*)/platforms/android-([0-9]+)/arch-([a-z0-9_]+)$")
+    set(_ANDROID_SYSROOT_NDK "${CMAKE_MATCH_1}")
+    set(_ANDROID_SYSROOT_API "${CMAKE_MATCH_2}")
+    set(_ANDROID_SYSROOT_ARCH "${CMAKE_MATCH_3}")
+  elseif(CMAKE_SYSROOT MATCHES "^([^\\\n]*)/sysroot$")
+    set(_ANDROID_SYSROOT_STANDALONE_TOOLCHAIN "${CMAKE_MATCH_1}")
+  else()
+    message(FATAL_ERROR
+      "The value of CMAKE_SYSROOT:\n"
+      "  ${CMAKE_SYSROOT}\n"
+      "does not match any of the forms:\n"
+      "  <ndk>/platforms/android-<api>/arch-<arch>\n"
+      "  <standalone-toolchain>/sysroot\n"
+      "where:\n"
+      "  <ndk>  = Android NDK directory (with forward slashes)\n"
+      "  <api>  = Android API version number (decimal digits)\n"
+      "  <arch> = Android ARCH name (lower case)\n"
+      "  <standalone-toolchain> = Path to standalone toolchain prefix\n"
+      )
+  endif()
+endif()
+
+# Find the Android NDK.
+if(CMAKE_ANDROID_NDK)
+  if(NOT IS_DIRECTORY "${CMAKE_ANDROID_NDK}")
+    message(FATAL_ERROR
+      "Android: The NDK root directory specified by CMAKE_ANDROID_NDK:\n"
+      "  ${CMAKE_ANDROID_NDK}\n"
+      "does not exist."
+      )
+  endif()
+elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  if(NOT IS_DIRECTORY "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}")
+    message(FATAL_ERROR
+      "Android: The standalone toolchain directory specified by CMAKE_ANDROID_STANDALONE_TOOLCHAIN:\n"
+      "  ${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}\n"
+      "does not exist."
+      )
+  endif()
+  if(NOT EXISTS "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h")
+    message(FATAL_ERROR
+      "Android: The standalone toolchain directory specified by CMAKE_ANDROID_STANDALONE_TOOLCHAIN:\n"
+      "  ${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}\n"
+      "does not contain a sysroot with a known layout.  The file:\n"
+      "  ${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h\n"
+      "does not exist."
+      )
+  endif()
+else()
+  if(IS_DIRECTORY "${_ANDROID_SYSROOT_NDK}")
+    set(CMAKE_ANDROID_NDK "${_ANDROID_SYSROOT_NDK}")
+  elseif(IS_DIRECTORY "${_ANDROID_SYSROOT_STANDALONE_TOOLCHAIN}")
+    set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN "${_ANDROID_SYSROOT_STANDALONE_TOOLCHAIN}")
+  elseif(IS_DIRECTORY "${ANDROID_NDK}")
+    file(TO_CMAKE_PATH "${ANDROID_NDK}" CMAKE_ANDROID_NDK)
+  elseif(IS_DIRECTORY "${ANDROID_STANDALONE_TOOLCHAIN}")
+    file(TO_CMAKE_PATH "${ANDROID_STANDALONE_TOOLCHAIN}" CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  elseif(IS_DIRECTORY "$ENV{ANDROID_NDK_ROOT}")
+    file(TO_CMAKE_PATH "$ENV{ANDROID_NDK_ROOT}" CMAKE_ANDROID_NDK)
+  elseif(IS_DIRECTORY "$ENV{ANDROID_NDK}")
+    file(TO_CMAKE_PATH "$ENV{ANDROID_NDK}" CMAKE_ANDROID_NDK)
+  elseif(IS_DIRECTORY "$ENV{ANDROID_STANDALONE_TOOLCHAIN}")
+    file(TO_CMAKE_PATH "$ENV{ANDROID_STANDALONE_TOOLCHAIN}" CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  endif()
+  # TODO: Search harder for the NDK or standalone toolchain.
+endif()
+
+set(_ANDROID_STANDALONE_TOOLCHAIN_API "")
+if(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  set(_ANDROID_API_LEVEL_H_REGEX "^[\t ]*#[\t ]*define[\t ]+__ANDROID_API__[\t ]+([0-9]+)")
+  file(STRINGS "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h"
+    _ANDROID_API_LEVEL_H_CONTENT REGEX "${_ANDROID_API_LEVEL_H_REGEX}")
+  if(_ANDROID_API_LEVEL_H_CONTENT MATCHES "${_ANDROID_API_LEVEL_H_REGEX}")
+    set(_ANDROID_STANDALONE_TOOLCHAIN_API "${CMAKE_MATCH_1}")
+  endif()
+endif()
+
+if(NOT CMAKE_ANDROID_NDK AND NOT CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  message(FATAL_ERROR "Android: Neither the NDK or a standalone toolchain was found.")
+endif()
+
+# Select an API.
+if(CMAKE_SYSTEM_VERSION)
+  set(_ANDROID_API_VAR CMAKE_SYSTEM_VERSION)
+elseif(CMAKE_ANDROID_API)
+  set(CMAKE_SYSTEM_VERSION "${CMAKE_ANDROID_API}")
+  set(_ANDROID_API_VAR CMAKE_ANDROID_API)
+elseif(_ANDROID_SYSROOT_API)
+  set(CMAKE_SYSTEM_VERSION "${_ANDROID_SYSROOT_API}")
+  set(_ANDROID_API_VAR CMAKE_SYSROOT)
+elseif(_ANDROID_STANDALONE_TOOLCHAIN_API)
+  set(CMAKE_SYSTEM_VERSION "${_ANDROID_STANDALONE_TOOLCHAIN_API}")
+endif()
+if(CMAKE_SYSTEM_VERSION)
+  if(CMAKE_ANDROID_API AND NOT "x${CMAKE_ANDROID_API}" STREQUAL "x${CMAKE_SYSTEM_VERSION}")
+    message(FATAL_ERROR
+      "Android: The API specified by CMAKE_ANDROID_API='${CMAKE_ANDROID_API}' is not consistent with CMAKE_SYSTEM_VERSION='${CMAKE_SYSTEM_VERSION}'."
+      )
+  endif()
+  if(_ANDROID_SYSROOT_API)
+    foreach(v CMAKE_ANDROID_API CMAKE_SYSTEM_VERSION)
+      if(${v} AND NOT "x${_ANDROID_SYSROOT_API}" STREQUAL "x${${v}}")
+        message(FATAL_ERROR
+          "Android: The API specified by ${v}='${${v}}' is not consistent with CMAKE_SYSROOT:\n"
+          "  ${CMAKE_SYSROOT}"
+          )
+      endif()
+    endforeach()
+  endif()
+  if(CMAKE_ANDROID_NDK AND NOT IS_DIRECTORY "${CMAKE_ANDROID_NDK}/platforms/android-${CMAKE_SYSTEM_VERSION}")
+    message(FATAL_ERROR
+      "Android: The API specified by ${_ANDROID_API_VAR}='${${_ANDROID_API_VAR}}' does not exist in the NDK.  "
+      "The directory:\n"
+      "  ${CMAKE_ANDROID_NDK}/platforms/android-${CMAKE_SYSTEM_VERSION}\n"
+      "does not exist."
+      )
+  endif()
+elseif(CMAKE_ANDROID_NDK)
+  file(GLOB _ANDROID_APIS_1 RELATIVE "${CMAKE_ANDROID_NDK}/platforms" "${CMAKE_ANDROID_NDK}/platforms/android-[0-9]")
+  file(GLOB _ANDROID_APIS_2 RELATIVE "${CMAKE_ANDROID_NDK}/platforms" "${CMAKE_ANDROID_NDK}/platforms/android-[0-9][0-9]")
+  list(SORT _ANDROID_APIS_1)
+  list(SORT _ANDROID_APIS_2)
+  set(_ANDROID_APIS ${_ANDROID_APIS_1} ${_ANDROID_APIS_2})
+  unset(_ANDROID_APIS_1)
+  unset(_ANDROID_APIS_2)
+  if(_ANDROID_APIS STREQUAL "")
+    message(FATAL_ERROR
+      "Android: No APIs found in the NDK.  No\n"
+      "  ${CMAKE_ANDROID_NDK}/platforms/android-*\n"
+      "directories exist."
+      )
+  endif()
+  string(REPLACE "android-" "" _ANDROID_APIS "${_ANDROID_APIS}")
+  list(REVERSE _ANDROID_APIS)
+  list(GET _ANDROID_APIS 0 CMAKE_SYSTEM_VERSION)
+  unset(_ANDROID_APIS)
+endif()
+if(NOT CMAKE_SYSTEM_VERSION MATCHES "^[0-9]+$")
+  message(FATAL_ERROR "Android: The API specified by CMAKE_SYSTEM_VERSION='${CMAKE_SYSTEM_VERSION}' is not an integer.")
+endif()
+
+# https://developer.android.com/ndk/guides/abis.html
+
+set(_ANDROID_ABI_arm64-v8a_PROC   "aarch64")
+set(_ANDROID_ABI_arm64-v8a_ARCH   "arm64")
+set(_ANDROID_ABI_armeabi-v7a_PROC "armv7-a")
+set(_ANDROID_ABI_armeabi-v7a_ARCH "arm")
+set(_ANDROID_ABI_armeabi-v6_PROC  "armv6")
+set(_ANDROID_ABI_armeabi-v6_ARCH  "arm")
+set(_ANDROID_ABI_armeabi_PROC     "armv5te")
+set(_ANDROID_ABI_armeabi_ARCH     "arm")
+set(_ANDROID_ABI_mips_PROC        "mips")
+set(_ANDROID_ABI_mips_ARCH        "mips")
+set(_ANDROID_ABI_mips64_PROC      "mips64")
+set(_ANDROID_ABI_mips64_ARCH      "mips64")
+set(_ANDROID_ABI_x86_PROC         "i686")
+set(_ANDROID_ABI_x86_ARCH         "x86")
+set(_ANDROID_ABI_x86_64_PROC      "x86_64")
+set(_ANDROID_ABI_x86_64_ARCH      "x86_64")
+
+set(_ANDROID_PROC_aarch64_ARCH_ABI "arm64-v8a")
+set(_ANDROID_PROC_armv7-a_ARCH_ABI "armeabi-v7a")
+set(_ANDROID_PROC_armv6_ARCH_ABI   "armeabi-v6")
+set(_ANDROID_PROC_armv5te_ARCH_ABI "armeabi")
+set(_ANDROID_PROC_i686_ARCH_ABI    "x86")
+set(_ANDROID_PROC_mips_ARCH_ABI    "mips")
+set(_ANDROID_PROC_mips64_ARCH_ABI  "mips64")
+set(_ANDROID_PROC_x86_64_ARCH_ABI  "x86_64")
+
+set(_ANDROID_ARCH_arm64_ABI  "arm64-v8a")
+set(_ANDROID_ARCH_arm_ABI    "armeabi")
+set(_ANDROID_ARCH_mips_ABI   "mips")
+set(_ANDROID_ARCH_mips64_ABI "mips64")
+set(_ANDROID_ARCH_x86_ABI    "x86")
+set(_ANDROID_ARCH_x86_64_ABI "x86_64")
+
+# Validate inputs.
+if(CMAKE_ANDROID_ARCH_ABI AND NOT DEFINED "_ANDROID_ABI_${CMAKE_ANDROID_ARCH_ABI}_PROC")
+  message(FATAL_ERROR "Android: Unknown ABI CMAKE_ANDROID_ARCH_ABI='${CMAKE_ANDROID_ARCH_ABI}'.")
+endif()
+if(CMAKE_SYSTEM_PROCESSOR AND NOT DEFINED "_ANDROID_PROC_${CMAKE_SYSTEM_PROCESSOR}_ARCH_ABI")
+  message(FATAL_ERROR "Android: Unknown processor CMAKE_SYSTEM_PROCESSOR='${CMAKE_SYSTEM_PROCESSOR}'.")
+endif()
+if(_ANDROID_SYSROOT_ARCH AND NOT DEFINED "_ANDROID_ARCH_${_ANDROID_SYSROOT_ARCH}_ABI")
+  message(FATAL_ERROR
+    "Android: Unknown architecture '${_ANDROID_SYSROOT_ARCH}' specified in CMAKE_SYSROOT:\n"
+    "  ${CMAKE_SYSROOT}"
+    )
+endif()
+
+# Select an ABI.
+if(NOT CMAKE_ANDROID_ARCH_ABI)
+  if(CMAKE_SYSTEM_PROCESSOR)
+    set(CMAKE_ANDROID_ARCH_ABI "${_ANDROID_PROC_${CMAKE_SYSTEM_PROCESSOR}_ARCH_ABI}")
+  elseif(_ANDROID_SYSROOT_ARCH)
+    set(CMAKE_ANDROID_ARCH_ABI "${_ANDROID_ARCH_${_ANDROID_SYSROOT_ARCH}_ABI}")
+  else()
+    # https://developer.android.com/ndk/guides/application_mk.html
+    # Default is the oldest ARM ABI.
+    set(CMAKE_ANDROID_ARCH_ABI "armeabi")
+  endif()
+endif()
+set(CMAKE_ANDROID_ARCH "${_ANDROID_ABI_${CMAKE_ANDROID_ARCH_ABI}_ARCH}")
+if(_ANDROID_SYSROOT_ARCH AND NOT "x${_ANDROID_SYSROOT_ARCH}" STREQUAL "x${CMAKE_ANDROID_ARCH}")
+  message(FATAL_ERROR
+    "Android: Architecture '${_ANDROID_SYSROOT_ARCH}' specified in CMAKE_SYSROOT:\n"
+    "  ${CMAKE_SYSROOT}\n"
+    "does not match architecture '${CMAKE_ANDROID_ARCH}' for the ABI '${CMAKE_ANDROID_ARCH_ABI}'."
+    )
+endif()
+
+# Select a processor.
+if(NOT CMAKE_SYSTEM_PROCESSOR)
+  set(CMAKE_SYSTEM_PROCESSOR "${_ANDROID_ABI_${CMAKE_ANDROID_ARCH_ABI}_PROC}")
+endif()
+
+# If the user specified both an ABI and a processor then they might not match.
+if(NOT _ANDROID_ABI_${CMAKE_ANDROID_ARCH_ABI}_PROC STREQUAL CMAKE_SYSTEM_PROCESSOR)
+  message(FATAL_ERROR "Android: The specified CMAKE_ANDROID_ARCH_ABI='${CMAKE_ANDROID_ARCH_ABI}' and CMAKE_SYSTEM_PROCESSOR='${CMAKE_SYSTEM_PROCESSOR}' is not a valid combination.")
+endif()
+
+# Save the Android-specific information in CMakeSystem.cmake.
+set(CMAKE_SYSTEM_CUSTOM_CODE "
+set(CMAKE_ANDROID_NDK \"${CMAKE_ANDROID_NDK}\")
+set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN \"${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}\")
+set(CMAKE_ANDROID_ARCH \"${CMAKE_ANDROID_ARCH}\")
+set(CMAKE_ANDROID_ARCH_ABI \"${CMAKE_ANDROID_ARCH_ABI}\")
+")
+
+# Select an ARM variant.
+if(CMAKE_ANDROID_ARCH_ABI MATCHES "^armeabi")
+  if(CMAKE_ANDROID_ARM_MODE)
+    set(CMAKE_ANDROID_ARM_MODE 1)
+  else()
+    set(CMAKE_ANDROID_ARM_MODE 0)
+  endif()
+  string(APPEND CMAKE_SYSTEM_CUSTOM_CODE
+    "set(CMAKE_ANDROID_ARM_MODE \"${CMAKE_ANDROID_ARM_MODE}\")\n"
+    )
+elseif(DEFINED CMAKE_ANDROID_ARM_MODE)
+  message(FATAL_ERROR "Android: CMAKE_ANDROID_ARM_MODE is set but is valid only for 'armeabi' architectures.")
+endif()
+
+if(CMAKE_ANDROID_ARCH_ABI STREQUAL "armeabi-v7a")
+  if(CMAKE_ANDROID_ARM_NEON)
+    set(CMAKE_ANDROID_ARM_NEON 1)
+  else()
+    set(CMAKE_ANDROID_ARM_NEON 0)
+  endif()
+  string(APPEND CMAKE_SYSTEM_CUSTOM_CODE
+    "set(CMAKE_ANDROID_ARM_NEON \"${CMAKE_ANDROID_ARM_NEON}\")\n"
+    )
+elseif(DEFINED CMAKE_ANDROID_ARM_NEON)
+  message(FATAL_ERROR "Android: CMAKE_ANDROID_ARM_NEON is set but is valid only for 'armeabi-v7a' architecture.")
+endif()
+
+# Report the chosen architecture.
+message(STATUS "Android: Targeting API '${CMAKE_SYSTEM_VERSION}' with architecture '${CMAKE_ANDROID_ARCH}', ABI '${CMAKE_ANDROID_ARCH_ABI}', and processor '${CMAKE_SYSTEM_PROCESSOR}'")
diff --git a/Modules/Platform/Android-GNU-C.cmake b/Modules/Platform/Android-GNU-C.cmake
new file mode 100644
index 0000000..78a6a50
--- /dev/null
+++ b/Modules/Platform/Android-GNU-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android-GNU)
+__android_compiler_gnu(C)
diff --git a/Modules/Platform/Android-GNU-CXX.cmake b/Modules/Platform/Android-GNU-CXX.cmake
new file mode 100644
index 0000000..41279d1
--- /dev/null
+++ b/Modules/Platform/Android-GNU-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android-GNU)
+__android_compiler_gnu(CXX)
diff --git a/Modules/Platform/Android-GNU.cmake b/Modules/Platform/Android-GNU.cmake
new file mode 100644
index 0000000..e1f79ca
--- /dev/null
+++ b/Modules/Platform/Android-GNU.cmake
@@ -0,0 +1,33 @@
+# 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(__ANDROID_COMPILER_GNU)
+  return()
+endif()
+set(__ANDROID_COMPILER_GNU 1)
+
+# Support for NVIDIA Nsight Tegra Visual Studio Edition was previously
+# implemented in the CMake VS IDE generators.  Avoid interfering with
+# that functionality for now.  Later we may try to integrate this.
+if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+  macro(__android_compiler_gnu lang)
+  endmacro()
+  return()
+endif()
+
+# Commonly used Android toolchain files that pre-date CMake upstream support
+# set CMAKE_SYSTEM_VERSION to 1.  Avoid interfering with them.
+if(CMAKE_SYSTEM_VERSION EQUAL 1)
+  macro(__android_compiler_gnu lang)
+  endmacro()
+  return()
+endif()
+
+include(Platform/Android-Common)
+
+include(Platform/Android/abi-${CMAKE_ANDROID_ARCH_ABI}-GNU)
+
+macro(__android_compiler_gnu lang)
+  __android_compiler_common(${lang})
+endmacro()
diff --git a/Modules/Platform/Android-Initialize.cmake b/Modules/Platform/Android-Initialize.cmake
new file mode 100644
index 0000000..a327223
--- /dev/null
+++ b/Modules/Platform/Android-Initialize.cmake
@@ -0,0 +1,41 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# When CMAKE_SYSTEM_NAME is "Android", CMakeSystemSpecificInitialize loads this
+# module.
+
+# Support for NVIDIA Nsight Tegra Visual Studio Edition was previously
+# implemented in the CMake VS IDE generators.  Avoid interfering with
+# that functionality for now.  Later we may try to integrate this.
+if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+  return()
+endif()
+
+# Commonly used Android toolchain files that pre-date CMake upstream support
+# set CMAKE_SYSTEM_VERSION to 1.  Avoid interfering with them.
+if(CMAKE_SYSTEM_VERSION EQUAL 1)
+  return()
+endif()
+
+if(NOT CMAKE_SYSROOT)
+  if(CMAKE_ANDROID_NDK)
+    set(CMAKE_SYSROOT "${CMAKE_ANDROID_NDK}/platforms/android-${CMAKE_SYSTEM_VERSION}/arch-${CMAKE_ANDROID_ARCH}")
+  elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+    set(CMAKE_SYSROOT "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/sysroot")
+  endif()
+endif()
+
+if(CMAKE_SYSROOT)
+  if(NOT IS_DIRECTORY "${CMAKE_SYSROOT}")
+    message(FATAL_ERROR
+      "Android: The system root directory needed for the selected Android version and architecture does not exist:\n"
+      "  ${CMAKE_SYSROOT}\n"
+      )
+  endif()
+else()
+  message(FATAL_ERROR
+    "Android: No CMAKE_SYSROOT was selected."
+    )
+endif()
+
+set(CMAKE_BUILD_TYPE_INIT Debug)
diff --git a/Modules/Platform/Android.cmake b/Modules/Platform/Android.cmake
index 1bdad04..3d69733 100644
--- a/Modules/Platform/Android.cmake
+++ b/Modules/Platform/Android.cmake
@@ -1,5 +1,7 @@
 include(Platform/Linux)
 
+set(ANDROID 1)
+
 # Android has soname, but binary names must end in ".so" so we cannot append
 # a version number.  Also we cannot portably represent symlinks on the host.
 set(CMAKE_PLATFORM_NO_VERSIONED_SONAME 1)
diff --git a/Modules/Platform/Android/Determine-Compiler-NDK.cmake b/Modules/Platform/Android/Determine-Compiler-NDK.cmake
new file mode 100644
index 0000000..953bc85
--- /dev/null
+++ b/Modules/Platform/Android/Determine-Compiler-NDK.cmake
@@ -0,0 +1,246 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# In Android NDK releases there is build system toolchain selection logic in
+# these files:
+#
+# * <ndk>/build/core/init.mk
+# * <ndk>/build/core/setup-toolchain.mk
+# * <ndk>/[build/core/]toolchains/<toolchain>/{config.mk,setup.mk}
+#
+# We parse information out of the ``config.mk`` and ``setup.mk`` files below.
+#
+# There is also a "toolchains" directory with the prebuilt toolchains themselves:
+#
+# * <triple-or-arch>-<gcc-version>/prebuilt/<host>/bin/<triple>-gcc(.exe)?
+#   The gcc compiler to be invoked.
+#
+# * llvm*/prebuilt/<host>/bin/clang
+#   The clang compiler to be invoked with flags:
+#     -target <triple>
+#     -gcc-toolchain <ndk>/toolchains/<triple-or-arch>-<gcc-version>
+
+# Glob available toolchains in the NDK, restricted by any version request.
+if(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION STREQUAL "clang")
+  set(_ANDROID_TOOL_PATTERNS "*-clang" "*-clang[0-9].[0-9]")
+elseif(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION)
+  if(NOT CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION MATCHES "^(clang)?[0-9]\\.[0-9]$")
+    message(FATAL_ERROR
+      "Android: The CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION value '${CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION}' "
+      "is not one of the allowed forms:\n"
+      "  <major>.<minor>       = GCC of specified version\n"
+      "  clang<major>.<minor>  = Clang of specified version\n"
+      "  clang                 = Clang of most recent available version\n"
+      )
+  endif()
+  set(_ANDROID_TOOL_PATTERNS "*-${CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION}")
+else()
+  set(_ANDROID_TOOL_PATTERNS "*-[0-9].[0-9]")
+endif()
+set(_ANDROID_CONFIG_MK_PATTERNS)
+foreach(base "build/core/toolchains" "toolchains")
+  foreach(pattern IN LISTS _ANDROID_TOOL_PATTERNS)
+    list(APPEND _ANDROID_CONFIG_MK_PATTERNS
+      "${CMAKE_ANDROID_NDK}/${base}/${pattern}/config.mk"
+      )
+  endforeach()
+endforeach()
+unset(_ANDROID_TOOL_PATTERNS)
+file(GLOB _ANDROID_CONFIG_MKS ${_ANDROID_CONFIG_MK_PATTERNS})
+unset(_ANDROID_CONFIG_MK_PATTERNS)
+
+# Find the newest toolchain version matching the ABI.
+set(_ANDROID_TOOL_NAME "")
+set(_ANDROID_TOOL_VERS 0)
+set(_ANDROID_TOOL_SETUP_MK "")
+foreach(config_mk IN LISTS _ANDROID_CONFIG_MKS)
+  # Check that the toolchain matches the ABI.
+  file(STRINGS "${config_mk}" _ANDROID_TOOL_ABIS REGEX "^TOOLCHAIN_ABIS :=.* ${CMAKE_ANDROID_ARCH_ABI}( |$)")
+  if(NOT _ANDROID_TOOL_ABIS)
+    continue()
+  endif()
+  unset(_ANDROID_TOOL_ABIS)
+
+  # Check the version.
+  if("${config_mk}" MATCHES [[/([^/]+-(clang)?([0-9]\.[0-9]|))/config.mk$]])
+    set(_ANDROID_CUR_NAME "${CMAKE_MATCH_1}")
+    set(_ANDROID_CUR_VERS "${CMAKE_MATCH_3}")
+    if(_ANDROID_TOOL_VERS STREQUAL "")
+      # already the latest possible
+    elseif(_ANDROID_CUR_VERS STREQUAL "" OR _ANDROID_CUR_VERS VERSION_GREATER _ANDROID_TOOL_VERS)
+      set(_ANDROID_TOOL_NAME "${_ANDROID_CUR_NAME}")
+      set(_ANDROID_TOOL_VERS "${_ANDROID_CUR_VERS}")
+      string(REPLACE "/config.mk" "/setup.mk" _ANDROID_TOOL_SETUP_MK "${config_mk}")
+    endif()
+    unset(_ANDROID_CUR_TOOL)
+    unset(_ANDROID_CUR_VERS)
+  endif()
+endforeach()
+
+# Verify that we have a suitable toolchain.
+if(NOT _ANDROID_TOOL_NAME)
+  if(_ANDROID_CONFIG_MKS)
+    string(REPLACE ";" "\n  " _ANDROID_TOOLS_MSG "after considering:;${_ANDROID_CONFIG_MKS}")
+  else()
+    set(_ANDROID_TOOLS_MSG "")
+  endif()
+  if(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION)
+    string(CONCAT _ANDROID_TOOLS_MSG
+      "of the version specified by CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION:\n"
+      "  ${CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION}\n"
+      "${_ANDROID_TOOLS_MSG}")
+  endif()
+  message(FATAL_ERROR
+    "Android: No toolchain for ABI '${CMAKE_ANDROID_ARCH_ABI}' found in the NDK:\n"
+    "  ${CMAKE_ANDROID_NDK}\n"
+    "${_ANDROID_TOOLS_MSG}"
+    )
+endif()
+unset(_ANDROID_CONFIG_MKS)
+
+# For clang toolchains we still need to find a gcc toolchain.
+if(_ANDROID_TOOL_NAME MATCHES "-clang")
+  set(_ANDROID_TOOL_CLANG_NAME "${_ANDROID_TOOL_NAME}")
+  set(_ANDROID_TOOL_CLANG_VERS "${_ANDROID_TOOL_VERS}")
+  set(_ANDROID_TOOL_NAME "")
+  set(_ANDROID_TOOL_VERS "")
+else()
+  set(_ANDROID_TOOL_CLANG_NAME "")
+  set(_ANDROID_TOOL_CLANG_VERS "")
+endif()
+
+# Parse the toolchain setup.mk file to extract information we need.
+# Their content is not standardized across toolchains or NDK versions,
+# so we match known cases.  Note that the parsing is stateful across
+# lines because we need to substitute for some Make variable references.
+if(CMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG)
+  message(STATUS "loading: ${_ANDROID_TOOL_SETUP_MK}")
+endif()
+file(STRINGS "${_ANDROID_TOOL_SETUP_MK}" _ANDROID_TOOL_SETUP REGEX "^(LLVM|TOOLCHAIN)_[A-Z_]+ +:= +.*$")
+unset(_ANDROID_TOOL_SETUP_MK)
+set(_ANDROID_TOOL_PREFIX "")
+set(_ANDROID_TOOL_NAME_ONLY "")
+set(_ANDROID_TOOL_LLVM_NAME "")
+set(_ANDROID_TOOL_LLVM_VERS "")
+foreach(line IN LISTS _ANDROID_TOOL_SETUP)
+  if(CMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG)
+    message(STATUS "setup.mk: ${line}")
+  endif()
+
+  if(line MATCHES [[^TOOLCHAIN_PREFIX +:= +.*/bin/([^$/ ]*) *$]])
+    # We just matched the toolchain prefix with no Make variable references.
+    set(_ANDROID_TOOL_PREFIX "${CMAKE_MATCH_1}")
+  elseif(_ANDROID_TOOL_CLANG_NAME)
+    # For clang toolchains we need to find more information.
+    if(line MATCHES [[^TOOLCHAIN_VERSION +:= +([0-9.]+) *$]])
+      # We just matched the gcc toolchain version number.  Save it for later.
+      set(_ANDROID_TOOL_VERS "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^TOOLCHAIN_NAME +:= +(.*\$\(TOOLCHAIN_VERSION\)) *$]])
+      # We just matched the gcc toolchain name with a version number placeholder, so substitute it.
+      # The gcc toolchain version number will have already been extracted from a TOOLCHAIN_VERSION line.
+      string(REPLACE "$(TOOLCHAIN_VERSION)" "${_ANDROID_TOOL_VERS}" _ANDROID_TOOL_NAME "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^TOOLCHAIN_NAME +:= +([^$/ ]+) *$]])
+      # We just matched the gcc toolchain name without version number.  Save it for later.
+      set(_ANDROID_TOOL_NAME_ONLY "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^TOOLCHAIN_PREFIX +:= +.*/bin/(\$\(TOOLCHAIN_NAME\)-) *$]])
+      # We just matched the toolchain prefix with a name placholder, so substitute it.
+      # The gcc toolchain name will have already been extracted without version number from a TOOLCHAIN_NAME line.
+      string(REPLACE "$(TOOLCHAIN_NAME)" "${_ANDROID_TOOL_NAME_ONLY}" _ANDROID_TOOL_PREFIX "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^LLVM_VERSION +:= +([0-9.]+)$]])
+      # We just matched the llvm prebuilt binary toolchain version number.  Save it for later.
+      set(_ANDROID_TOOL_LLVM_VERS "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^LLVM_NAME +:= +(llvm-\$\(LLVM_VERSION\)) *$]])
+      # We just matched the llvm prebuilt binary toolchain directory name with a version number placeholder,
+      # so substitute it. The llvm prebuilt binary toolchain version number will have already been extracted
+      # from a LLVM_VERSION line.
+      string(REPLACE "$(LLVM_VERSION)" "${_ANDROID_TOOL_LLVM_VERS}" _ANDROID_TOOL_LLVM_NAME "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^LLVM_TOOLCHAIN_PREBUILT_ROOT +:= +\$\(call get-toolchain-root.*,([^$ ]+)\) *$]])
+      # We just matched the llvm prebuilt binary toolchain directory name.
+      set(_ANDROID_TOOL_LLVM_NAME "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^TOOLCHAIN_ROOT +:= +\$\(call get-toolchain-root.*,(\$\(TOOLCHAIN_NAME\)-[0-9.]+)\) *$]])
+      # We just matched a placeholder for the name followed by a version number.
+      # The gcc toolchain name will have already been extracted without version number from a TOOLCHAIN_NAME line.
+      # Substitute for the placeholder to get the full gcc toolchain name.
+      string(REPLACE "$(TOOLCHAIN_NAME)" "${_ANDROID_TOOL_NAME_ONLY}" _ANDROID_TOOL_NAME "${CMAKE_MATCH_1}")
+    elseif(line MATCHES [[^TOOLCHAIN_ROOT +:= +\$\(call get-toolchain-root.*,([^$ ]+)\) *$]])
+      # We just matched the full gcc toolchain name without placeholder.
+      set(_ANDROID_TOOL_NAME "${CMAKE_MATCH_1}")
+    endif()
+  endif()
+endforeach()
+unset(_ANDROID_TOOL_NAME_ONLY)
+unset(_ANDROID_TOOL_LLVM_VERS)
+unset(_ANDROID_TOOL_SETUP)
+
+# Fall back to parsing the version and prefix from the tool name.
+if(NOT _ANDROID_TOOL_VERS AND "${_ANDROID_TOOL_NAME}" MATCHES "-([0-9.]+)$")
+  set(_ANDROID_TOOL_VERS "${CMAKE_MATCH_1}")
+endif()
+if(NOT _ANDROID_TOOL_PREFIX AND "${_ANDROID_TOOL_NAME}" MATCHES "^(.*-)[0-9.]+$")
+  set(_ANDROID_TOOL_PREFIX "${CMAKE_MATCH_1}")
+endif()
+
+# Identify the host platform.
+if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
+  if(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "x86_64")
+    set(_ANDROID_HOST_DIR "darwin-x86_64")
+  else()
+    set(_ANDROID_HOST_DIR "darwin-x86")
+  endif()
+elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
+  if(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "x86_64")
+    set(_ANDROID_HOST_DIR "linux-x86_64")
+  else()
+    set(_ANDROID_HOST_DIR "linux-x86")
+  endif()
+elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
+  if(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "AMD64")
+    set(_ANDROID_HOST_DIR "windows-x86_64")
+  else()
+    set(_ANDROID_HOST_DIR "windows")
+  endif()
+else()
+  message(FATAL_ERROR "Android: Builds hosted on '${CMAKE_HOST_SYSTEM_NAME}' not supported.")
+endif()
+
+# Help CMakeFindBinUtils locate things.
+set(_CMAKE_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_PREFIX}")
+
+set(_ANDROID_TOOL_C_TOOLCHAIN_VERSION "${_ANDROID_TOOL_VERS}")
+set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "${CMAKE_ANDROID_NDK}/toolchains/${_ANDROID_TOOL_NAME}/prebuilt/${_ANDROID_HOST_DIR}/bin/${_ANDROID_TOOL_PREFIX}")
+set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "${_ANDROID_HOST_EXT}")
+
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "${_ANDROID_TOOL_C_TOOLCHAIN_VERSION}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX "${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
+
+if(_ANDROID_TOOL_CLANG_NAME)
+  message(STATUS "Android: Selected Clang toolchain '${_ANDROID_TOOL_CLANG_NAME}' with GCC toolchain '${_ANDROID_TOOL_NAME}'")
+  set(_ANDROID_TOOL_C_COMPILER "${CMAKE_ANDROID_NDK}/toolchains/${_ANDROID_TOOL_LLVM_NAME}/prebuilt/${_ANDROID_HOST_DIR}/bin/clang${_ANDROID_HOST_EXT}")
+  set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN ${CMAKE_ANDROID_NDK}/toolchains/${_ANDROID_TOOL_NAME}/prebuilt/${_ANDROID_HOST_DIR})
+  set(_ANDROID_TOOL_CXX_COMPILER "${CMAKE_ANDROID_NDK}/toolchains/${_ANDROID_TOOL_LLVM_NAME}/prebuilt/${_ANDROID_HOST_DIR}/bin/clang++${_ANDROID_HOST_EXT}")
+  set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN}")
+else()
+  message(STATUS "Android: Selected GCC toolchain '${_ANDROID_TOOL_NAME}'")
+  set(_ANDROID_TOOL_C_COMPILER "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}gcc${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
+  set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN "")
+  set(_ANDROID_TOOL_CXX_COMPILER "${_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX}g++${_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX}")
+  set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "")
+endif()
+
+if(CMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG)
+  message(STATUS "_ANDROID_TOOL_NAME=${_ANDROID_TOOL_NAME}")
+  message(STATUS "_ANDROID_TOOL_VERS=${_ANDROID_TOOL_VERS}")
+  message(STATUS "_ANDROID_TOOL_PREFIX=${_ANDROID_TOOL_PREFIX}")
+  message(STATUS "_ANDROID_TOOL_CLANG_NAME=${_ANDROID_TOOL_CLANG_NAME}")
+  message(STATUS "_ANDROID_TOOL_CLANG_VERS=${_ANDROID_TOOL_CLANG_VERS}")
+  message(STATUS "_ANDROID_TOOL_LLVM_NAME=${_ANDROID_TOOL_LLVM_NAME}")
+endif()
+
+unset(_ANDROID_TOOL_NAME)
+unset(_ANDROID_TOOL_VERS)
+unset(_ANDROID_TOOL_PREFIX)
+unset(_ANDROID_TOOL_CLANG_NAME)
+unset(_ANDROID_TOOL_CLANG_VERS)
+unset(_ANDROID_TOOL_LLVM_NAME)
+unset(_ANDROID_HOST_DIR)
diff --git a/Modules/Platform/Android/Determine-Compiler-Standalone.cmake b/Modules/Platform/Android/Determine-Compiler-Standalone.cmake
new file mode 100644
index 0000000..6393105
--- /dev/null
+++ b/Modules/Platform/Android/Determine-Compiler-Standalone.cmake
@@ -0,0 +1,59 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+set(_ANDROID_TOOL_C_COMPILER "")
+set(_ANDROID_TOOL_CXX_COMPILER "")
+set(_ANDROID_TOOL_PREFIX "")
+file(GLOB _gcc "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/*-gcc${_ANDROID_HOST_EXT}")
+foreach(gcc IN LISTS _gcc)
+  if("${gcc}" MATCHES "/bin/([^/]*)gcc${_ANDROID_HOST_EXT}$")
+    set(_ANDROID_TOOL_PREFIX "${CMAKE_MATCH_1}")
+    break()
+  endif()
+endforeach()
+
+if(NOT _ANDROID_TOOL_PREFIX)
+  message(FATAL_ERROR
+    "Android: No '*-gcc' compiler found in CMAKE_ANDROID_STANDALONE_TOOLCHAIN:\n"
+    "  ${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}"
+    )
+endif()
+
+# Help CMakeFindBinUtils locate things.
+set(_CMAKE_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_PREFIX}")
+
+execute_process(
+  COMMAND "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/${_ANDROID_TOOL_PREFIX}gcc${_ANDROID_HOST_EXT}" -dumpversion
+  OUTPUT_VARIABLE _gcc_version
+  ERROR_VARIABLE _gcc_error
+  OUTPUT_STRIP_TRAILING_WHITESPACE
+  )
+if(_gcc_version MATCHES "^([0-9]+\\.[0-9]+)")
+  set(_ANDROID_TOOL_C_TOOLCHAIN_VERSION "${CMAKE_MATCH_1}")
+else()
+  message(FATAL_ERROR
+    "Android: Failed to extract the standalone toolchain version.  The command:\n"
+    "  '${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/${_ANDROID_TOOL_PREFIX}gcc${_ANDROID_HOST_EXT}' '-dumpversion'\n"
+    "produced output:\n"
+    "  ${_gcc_version}\n"
+    )
+endif()
+
+set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/${_ANDROID_TOOL_PREFIX}")
+set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "${_ANDROID_HOST_EXT}")
+
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "${_ANDROID_TOOL_C_TOOLCHAIN_VERSION}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX "${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
+
+if(EXISTS "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/clang${_ANDROID_HOST_EXT}")
+  set(_ANDROID_TOOL_C_COMPILER "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/clang${_ANDROID_HOST_EXT}")
+  set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}")
+  set(_ANDROID_TOOL_CXX_COMPILER "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/clang++${_ANDROID_HOST_EXT}")
+  set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}")
+else()
+  set(_ANDROID_TOOL_C_COMPILER "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}gcc${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
+  set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN "")
+  set(_ANDROID_TOOL_CXX_COMPILER "${_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX}g++${_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX}")
+  set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "")
+endif()
diff --git a/Modules/Platform/Android/Determine-Compiler.cmake b/Modules/Platform/Android/Determine-Compiler.cmake
new file mode 100644
index 0000000..2fd2c4a
--- /dev/null
+++ b/Modules/Platform/Android/Determine-Compiler.cmake
@@ -0,0 +1,70 @@
+# 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(__ANDROID_DETERMINE_COMPILER)
+  return()
+endif()
+set(__ANDROID_DETERMINE_COMPILER 1)
+
+# Support for NVIDIA Nsight Tegra Visual Studio Edition was previously
+# implemented in the CMake VS IDE generators.  Avoid interfering with
+# that functionality for now.  Later we may try to integrate this.
+if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+  macro(__android_determine_compiler lang)
+  endmacro()
+  return()
+endif()
+
+# Commonly used Android toolchain files that pre-date CMake upstream support
+# set CMAKE_SYSTEM_VERSION to 1.  Avoid interfering with them.
+if(CMAKE_SYSTEM_VERSION EQUAL 1)
+  macro(__android_determine_compiler lang)
+  endmacro()
+  return()
+endif()
+
+# Identify the host platform.
+if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
+  set(_ANDROID_HOST_EXT "")
+elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
+  set(_ANDROID_HOST_EXT "")
+elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
+  set(_ANDROID_HOST_EXT ".exe")
+else()
+  message(FATAL_ERROR "Android: Builds hosted on '${CMAKE_HOST_SYSTEM_NAME}' not supported.")
+endif()
+
+if(CMAKE_ANDROID_NDK)
+  include(Platform/Android/Determine-Compiler-NDK)
+elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  include(Platform/Android/Determine-Compiler-Standalone)
+else()
+  set(_ANDROID_TOOL_C_COMPILER "")
+  set(_ANDROID_TOOL_C_TOOLCHAIN_VERSION "")
+  set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN "")
+  set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "")
+  set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "")
+  set(_ANDROID_TOOL_CXX_COMPILER "")
+  set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "")
+  set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "")
+  set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "")
+  set(_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX "")
+endif()
+
+unset(_ANDROID_HOST_EXT)
+
+macro(__android_determine_compiler lang)
+  if(_ANDROID_TOOL_${lang}_COMPILER)
+    set(CMAKE_${lang}_COMPILER "${_ANDROID_TOOL_${lang}_COMPILER}")
+    set(CMAKE_${lang}_COMPILER_EXTERNAL_TOOLCHAIN "${_ANDROID_TOOL_${lang}_COMPILER_EXTERNAL_TOOLCHAIN}")
+
+    # Save the Android-specific information in CMake${lang}Compiler.cmake.
+    set(CMAKE_${lang}_COMPILER_CUSTOM_CODE "
+set(CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_VERSION}\")
+set(CMAKE_${lang}_COMPILER_EXTERNAL_TOOLCHAIN \"${_ANDROID_TOOL_${lang}_COMPILER_EXTERNAL_TOOLCHAIN}\")
+set(CMAKE_${lang}_ANDROID_TOOLCHAIN_PREFIX \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_PREFIX}\")
+set(CMAKE_${lang}_ANDROID_TOOLCHAIN_SUFFIX \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_SUFFIX}\")
+")
+  endif()
+endmacro()
diff --git a/Modules/Platform/Android/abi-arm64-v8a-Clang.cmake b/Modules/Platform/Android/abi-arm64-v8a-Clang.cmake
new file mode 100644
index 0000000..3ff1fe5
--- /dev/null
+++ b/Modules/Platform/Android/abi-arm64-v8a-Clang.cmake
@@ -0,0 +1,8 @@
+# <ndk>/build/core/toolchains/aarch64-linux-android-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "aarch64-none-linux-android")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-arm64-v8a-GNU.cmake b/Modules/Platform/Android/abi-arm64-v8a-GNU.cmake
new file mode 100644
index 0000000..538ec2f
--- /dev/null
+++ b/Modules/Platform/Android/abi-arm64-v8a-GNU.cmake
@@ -0,0 +1,6 @@
+# <ndk>/build/core/toolchains/aarch64-linux-android-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-armeabi-Clang.cmake b/Modules/Platform/Android/abi-armeabi-Clang.cmake
new file mode 100644
index 0000000..4fc3009
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-Clang.cmake
@@ -0,0 +1,20 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "armv5te-none-linux-androideabi")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv5te"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -msoft-float"
+  " -mtune=xscale"
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-armeabi-GNU.cmake b/Modules/Platform/Android/abi-armeabi-GNU.cmake
new file mode 100644
index 0000000..10cac00
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-GNU.cmake
@@ -0,0 +1,18 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv5te"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -msoft-float"
+  " -mtune=xscale"
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-armeabi-v6-Clang.cmake b/Modules/Platform/Android/abi-armeabi-v6-Clang.cmake
new file mode 100644
index 0000000..15f1d4a
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-v6-Clang.cmake
@@ -0,0 +1,19 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "armv6-none-linux-androideabi")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv6"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -mfloat-abi=softfp"
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-armeabi-v6-GNU.cmake b/Modules/Platform/Android/abi-armeabi-v6-GNU.cmake
new file mode 100644
index 0000000..7492de0
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-v6-GNU.cmake
@@ -0,0 +1,17 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv6"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -mfloat-abi=softfp"
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-armeabi-v7a-Clang.cmake b/Modules/Platform/Android/abi-armeabi-v7a-Clang.cmake
new file mode 100644
index 0000000..3a3efb3
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-v7a-Clang.cmake
@@ -0,0 +1,29 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "armv7-none-linux-androideabi")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv7-a"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+if(CMAKE_ANDROID_ARM_NEON)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mfpu=neon")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mfpu=vfpv3-d16")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_LDFLAGS
+  " -Wl,--fix-cortex-a8"
+  )
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -mfloat-abi=softfp"
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-armeabi-v7a-GNU.cmake b/Modules/Platform/Android/abi-armeabi-v7a-GNU.cmake
new file mode 100644
index 0000000..d27e37e
--- /dev/null
+++ b/Modules/Platform/Android/abi-armeabi-v7a-GNU.cmake
@@ -0,0 +1,27 @@
+# <ndk>/build/core/toolchains/arm-linux-androideabi-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -march=armv7-a"
+  )
+
+if(CMAKE_ANDROID_ARM_MODE)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -marm")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mthumb")
+endif()
+
+if(CMAKE_ANDROID_ARM_NEON)
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mfpu=neon")
+else()
+  string(APPEND _ANDROID_ABI_INIT_CFLAGS " -mfpu=vfpv3-d16")
+endif()
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -mfloat-abi=softfp"
+  " -fpic"
+  )
+
+string(APPEND _ANDROID_ABI_INIT_LDFLAGS
+  " -Wl,--fix-cortex-a8"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-common-Clang.cmake b/Modules/Platform/Android/abi-common-Clang.cmake
new file mode 100644
index 0000000..6025170
--- /dev/null
+++ b/Modules/Platform/Android/abi-common-Clang.cmake
@@ -0,0 +1,6 @@
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  #" -Wno-invalid-command-line-argument"
+  #" -Wno-unused-command-line-argument"
+  )
+
+include(Platform/Android/abi-common)
diff --git a/Modules/Platform/Android/abi-common-GNU.cmake b/Modules/Platform/Android/abi-common-GNU.cmake
new file mode 100644
index 0000000..40d829f
--- /dev/null
+++ b/Modules/Platform/Android/abi-common-GNU.cmake
@@ -0,0 +1 @@
+include(Platform/Android/abi-common)
diff --git a/Modules/Platform/Android/abi-common.cmake b/Modules/Platform/Android/abi-common.cmake
new file mode 100644
index 0000000..12d8e5c
--- /dev/null
+++ b/Modules/Platform/Android/abi-common.cmake
@@ -0,0 +1,4 @@
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -funwind-tables"
+  " -no-canonical-prefixes"
+  )
diff --git a/Modules/Platform/Android/abi-mips-Clang.cmake b/Modules/Platform/Android/abi-mips-Clang.cmake
new file mode 100644
index 0000000..bf6b9fc
--- /dev/null
+++ b/Modules/Platform/Android/abi-mips-Clang.cmake
@@ -0,0 +1,8 @@
+# <ndk>/build/core/toolchains/mipsel-linux-android-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "mipsel-none-linux-android")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-mips-GNU.cmake b/Modules/Platform/Android/abi-mips-GNU.cmake
new file mode 100644
index 0000000..d380440
--- /dev/null
+++ b/Modules/Platform/Android/abi-mips-GNU.cmake
@@ -0,0 +1,6 @@
+# <ndk>/build/core/toolchains/mipsel-linux-android-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-mips64-Clang.cmake b/Modules/Platform/Android/abi-mips64-Clang.cmake
new file mode 100644
index 0000000..1a94107
--- /dev/null
+++ b/Modules/Platform/Android/abi-mips64-Clang.cmake
@@ -0,0 +1,8 @@
+# <ndk>/build/core/toolchains/mips64el-linux-android-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "mips64el-none-linux-android")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-mips64-GNU.cmake b/Modules/Platform/Android/abi-mips64-GNU.cmake
new file mode 100644
index 0000000..4525d40
--- /dev/null
+++ b/Modules/Platform/Android/abi-mips64-GNU.cmake
@@ -0,0 +1,6 @@
+# <ndk>/build/core/toolchains/mips64el-linux-android-4.9/setup.mk
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fpic"
+  )
+
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-x86-Clang.cmake b/Modules/Platform/Android/abi-x86-Clang.cmake
new file mode 100644
index 0000000..f63ed36
--- /dev/null
+++ b/Modules/Platform/Android/abi-x86-Clang.cmake
@@ -0,0 +1,8 @@
+# <ndk>/build/core/toolchains/x86-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "i686-none-linux-android")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fPIC"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-x86-GNU.cmake b/Modules/Platform/Android/abi-x86-GNU.cmake
new file mode 100644
index 0000000..76ea5ca
--- /dev/null
+++ b/Modules/Platform/Android/abi-x86-GNU.cmake
@@ -0,0 +1,2 @@
+# <ndk>/build/core/toolchains/x86-4.9/setup.mk
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/abi-x86_64-Clang.cmake b/Modules/Platform/Android/abi-x86_64-Clang.cmake
new file mode 100644
index 0000000..c15042b
--- /dev/null
+++ b/Modules/Platform/Android/abi-x86_64-Clang.cmake
@@ -0,0 +1,8 @@
+# <ndk>/build/core/toolchains/x86_64-clang/setup.mk
+set(_ANDROID_ABI_CLANG_TARGET "x86_64-none-linux-android")
+
+string(APPEND _ANDROID_ABI_INIT_CFLAGS
+  " -fPIC"
+  )
+
+include(Platform/Android/abi-common-Clang)
diff --git a/Modules/Platform/Android/abi-x86_64-GNU.cmake b/Modules/Platform/Android/abi-x86_64-GNU.cmake
new file mode 100644
index 0000000..441bdcd
--- /dev/null
+++ b/Modules/Platform/Android/abi-x86_64-GNU.cmake
@@ -0,0 +1,2 @@
+# <ndk>/build/core/toolchains/x86_64-4.9/setup.mk
+include(Platform/Android/abi-common-GNU)
diff --git a/Modules/Platform/Android/ndk-stl-c++.cmake b/Modules/Platform/Android/ndk-stl-c++.cmake
new file mode 100644
index 0000000..b27015d
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-c++.cmake
@@ -0,0 +1,21 @@
+# <ndk>/sources/cxx-stl/llvm-libc++/Android.mk
+set(_ANDROID_STL_RTTI 1)
+set(_ANDROID_STL_EXCEPTIONS 1)
+macro(__android_stl_cxx lang filename)
+  # Add the include directory.
+  if(EXISTS "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libcxx/include/cstddef")
+    # r12 and below
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libcxx/include" 1)
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++abi/libcxxabi/include" 1)
+  else()
+    # r13 and above
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/include" 1)
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++abi/include" 1)
+  endif()
+
+  # Add a secondary include directory if it exists.
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/android/support/include" 0)
+
+  # Add the library file.
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-c++_shared.cmake b/Modules/Platform/Android/ndk-stl-c++_shared.cmake
new file mode 100644
index 0000000..f585adb
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-c++_shared.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-c++)
+macro(__android_stl lang)
+  __android_stl_cxx(${lang} libc++_shared.so)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-c++_static.cmake b/Modules/Platform/Android/ndk-stl-c++_static.cmake
new file mode 100644
index 0000000..8e562f8
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-c++_static.cmake
@@ -0,0 +1,6 @@
+include(Platform/Android/ndk-stl-c++)
+macro(__android_stl lang)
+  __android_stl_cxx(${lang} libc++_static.a)
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libs/${CMAKE_ANDROID_ARCH_ABI}/libc++abi.a" 0)
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libs/${CMAKE_ANDROID_ARCH_ABI}/libandroid_support.a" 0)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gabi++.cmake b/Modules/Platform/Android/ndk-stl-gabi++.cmake
new file mode 100644
index 0000000..850a47a
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gabi++.cmake
@@ -0,0 +1,7 @@
+# <ndk>/sources/cxx-stl/gabi++/Android.mk
+set(_ANDROID_STL_RTTI 1)
+set(_ANDROID_STL_EXCEPTIONS 1)
+macro(__android_stl_gabixx lang filename)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gabi++/include" 1)
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gabi++/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gabi++_shared.cmake b/Modules/Platform/Android/ndk-stl-gabi++_shared.cmake
new file mode 100644
index 0000000..314c1e0
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gabi++_shared.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-gabi++)
+macro(__android_stl lang)
+  __android_stl_gabixx(${lang} libgabi++_shared.so)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gabi++_static.cmake b/Modules/Platform/Android/ndk-stl-gabi++_static.cmake
new file mode 100644
index 0000000..f4a1d3c
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gabi++_static.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-gabi++)
+macro(__android_stl lang)
+  __android_stl_gabixx(${lang} libgabi++_static.a)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gnustl.cmake b/Modules/Platform/Android/ndk-stl-gnustl.cmake
new file mode 100644
index 0000000..b3226ee
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gnustl.cmake
@@ -0,0 +1,9 @@
+# <ndk>/sources/cxx-stl/gnu-libstdc++/Android.mk
+set(_ANDROID_STL_RTTI 1)
+set(_ANDROID_STL_EXCEPTIONS 1)
+macro(__android_stl_gnustl lang filename)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/include" 1)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/libs/${CMAKE_ANDROID_ARCH_ABI}/include" 1)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/include/backward" 1)
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gnustl_shared.cmake b/Modules/Platform/Android/ndk-stl-gnustl_shared.cmake
new file mode 100644
index 0000000..f20cc4d
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gnustl_shared.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-gnustl)
+macro(__android_stl lang)
+  __android_stl_gnustl(${lang} libgnustl_shared.so)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-gnustl_static.cmake b/Modules/Platform/Android/ndk-stl-gnustl_static.cmake
new file mode 100644
index 0000000..af4cc2a
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-gnustl_static.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-gnustl)
+macro(__android_stl lang)
+  __android_stl_gnustl(${lang} libgnustl_static.a)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-none.cmake b/Modules/Platform/Android/ndk-stl-none.cmake
new file mode 100644
index 0000000..9049c91
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-none.cmake
@@ -0,0 +1,2 @@
+macro(__android_stl lang)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-stlport.cmake b/Modules/Platform/Android/ndk-stl-stlport.cmake
new file mode 100644
index 0000000..eab6b94
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-stlport.cmake
@@ -0,0 +1,7 @@
+# <ndk>/sources/cxx-stl/stlport/Android.mk
+set(_ANDROID_STL_RTTI 1)
+set(_ANDROID_STL_EXCEPTIONS 1)
+macro(__android_stl_stlport lang filename)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/stlport/stlport" 1)
+  __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/stlport/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-stlport_shared.cmake b/Modules/Platform/Android/ndk-stl-stlport_shared.cmake
new file mode 100644
index 0000000..2b5846b
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-stlport_shared.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-stlport)
+macro(__android_stl lang)
+  __android_stl_stlport(${lang} libstlport_shared.so)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-stlport_static.cmake b/Modules/Platform/Android/ndk-stl-stlport_static.cmake
new file mode 100644
index 0000000..bf60307
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-stlport_static.cmake
@@ -0,0 +1,4 @@
+include(Platform/Android/ndk-stl-stlport)
+macro(__android_stl lang)
+  __android_stl_stlport(${lang} libstlport_static.a)
+endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-system.cmake b/Modules/Platform/Android/ndk-stl-system.cmake
new file mode 100644
index 0000000..dd554fe
--- /dev/null
+++ b/Modules/Platform/Android/ndk-stl-system.cmake
@@ -0,0 +1,6 @@
+# <ndk>/android-ndk-r11c/sources/cxx-stl/system/Android.mk
+set(_ANDROID_STL_RTTI 0)
+set(_ANDROID_STL_EXCEPTIONS 0)
+macro(__android_stl lang)
+  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/system/include" 1)
+endmacro()
diff --git a/Modules/Platform/BlueGeneP-base.cmake b/Modules/Platform/BlueGeneP-base.cmake
index c0241e1..fe95b42 100644
--- a/Modules/Platform/BlueGeneP-base.cmake
+++ b/Modules/Platform/BlueGeneP-base.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 #
 # BlueGeneP base platform file.
diff --git a/Modules/Platform/BlueGeneP-dynamic-GNU-C.cmake b/Modules/Platform/BlueGeneP-dynamic-GNU-C.cmake
index bd4696b..3491870 100644
--- a/Modules/Platform/BlueGeneP-dynamic-GNU-C.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-GNU-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(GNU C)
diff --git a/Modules/Platform/BlueGeneP-dynamic-GNU-CXX.cmake b/Modules/Platform/BlueGeneP-dynamic-GNU-CXX.cmake
index 9c995dc..d3c946b 100644
--- a/Modules/Platform/BlueGeneP-dynamic-GNU-CXX.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-GNU-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(GNU CXX)
diff --git a/Modules/Platform/BlueGeneP-dynamic-GNU-Fortran.cmake b/Modules/Platform/BlueGeneP-dynamic-GNU-Fortran.cmake
index 19d6be8..9db75be 100644
--- a/Modules/Platform/BlueGeneP-dynamic-GNU-Fortran.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-GNU-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(GNU Fortran)
diff --git a/Modules/Platform/BlueGeneP-dynamic-XL-C.cmake b/Modules/Platform/BlueGeneP-dynamic-XL-C.cmake
index 2dbbbc0..f13b517 100644
--- a/Modules/Platform/BlueGeneP-dynamic-XL-C.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-XL-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(XL C)
diff --git a/Modules/Platform/BlueGeneP-dynamic-XL-CXX.cmake b/Modules/Platform/BlueGeneP-dynamic-XL-CXX.cmake
index 2bc5127..80c05a1 100644
--- a/Modules/Platform/BlueGeneP-dynamic-XL-CXX.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-XL-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(XL CXX)
diff --git a/Modules/Platform/BlueGeneP-dynamic-XL-Fortran.cmake b/Modules/Platform/BlueGeneP-dynamic-XL-Fortran.cmake
index 59da63d..9c295bd 100644
--- a/Modules/Platform/BlueGeneP-dynamic-XL-Fortran.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic-XL-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_dynamic_flags(XL Fortran)
diff --git a/Modules/Platform/BlueGeneP-dynamic.cmake b/Modules/Platform/BlueGeneP-dynamic.cmake
index 8f96f2f..daebab3 100644
--- a/Modules/Platform/BlueGeneP-dynamic.cmake
+++ b/Modules/Platform/BlueGeneP-dynamic.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(Platform/BlueGeneP-base)
 set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS TRUE)
diff --git a/Modules/Platform/BlueGeneP-static-GNU-C.cmake b/Modules/Platform/BlueGeneP-static-GNU-C.cmake
index 412a7a3..7c60794 100644
--- a/Modules/Platform/BlueGeneP-static-GNU-C.cmake
+++ b/Modules/Platform/BlueGeneP-static-GNU-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(GNU C)
diff --git a/Modules/Platform/BlueGeneP-static-GNU-CXX.cmake b/Modules/Platform/BlueGeneP-static-GNU-CXX.cmake
index 418f0d8..edceaad 100644
--- a/Modules/Platform/BlueGeneP-static-GNU-CXX.cmake
+++ b/Modules/Platform/BlueGeneP-static-GNU-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(GNU CXX)
diff --git a/Modules/Platform/BlueGeneP-static-GNU-Fortran.cmake b/Modules/Platform/BlueGeneP-static-GNU-Fortran.cmake
index 119195b..6b2265a 100644
--- a/Modules/Platform/BlueGeneP-static-GNU-Fortran.cmake
+++ b/Modules/Platform/BlueGeneP-static-GNU-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(GNU Fortran)
diff --git a/Modules/Platform/BlueGeneP-static-XL-C.cmake b/Modules/Platform/BlueGeneP-static-XL-C.cmake
index 1f20959..a990b5c 100644
--- a/Modules/Platform/BlueGeneP-static-XL-C.cmake
+++ b/Modules/Platform/BlueGeneP-static-XL-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(XL C)
diff --git a/Modules/Platform/BlueGeneP-static-XL-CXX.cmake b/Modules/Platform/BlueGeneP-static-XL-CXX.cmake
index f027a53..116c0bb 100644
--- a/Modules/Platform/BlueGeneP-static-XL-CXX.cmake
+++ b/Modules/Platform/BlueGeneP-static-XL-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(XL CXX)
diff --git a/Modules/Platform/BlueGeneP-static-XL-Fortran.cmake b/Modules/Platform/BlueGeneP-static-XL-Fortran.cmake
index 778d4bd..2bdb6d9 100644
--- a/Modules/Platform/BlueGeneP-static-XL-Fortran.cmake
+++ b/Modules/Platform/BlueGeneP-static-XL-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneP_set_static_flags(XL Fortran)
diff --git a/Modules/Platform/BlueGeneP-static.cmake b/Modules/Platform/BlueGeneP-static.cmake
index c4f5f21..3675ed2 100644
--- a/Modules/Platform/BlueGeneP-static.cmake
+++ b/Modules/Platform/BlueGeneP-static.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(Platform/BlueGeneP-base)
 set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS FALSE)
diff --git a/Modules/Platform/BlueGeneQ-base.cmake b/Modules/Platform/BlueGeneQ-base.cmake
index 9372166..5e56d8e 100644
--- a/Modules/Platform/BlueGeneQ-base.cmake
+++ b/Modules/Platform/BlueGeneQ-base.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 #
 # Blue Gene/Q base platform file.
@@ -110,7 +99,7 @@ macro(__BlueGeneQ_common_setup compiler_id lang)
   # to do the same thing as the MPI compilers, which add these flags.
   set(BGQ_SYSTEM_INCLUDES "")
   foreach(dir ${CMAKE_SYSTEM_INCLUDE_PATH})
-    set(BGQ_SYSTEM_INCLUDES "${BGQ_SYSTEM_INCLUDES} -I${dir}")
+    string(APPEND BGQ_SYSTEM_INCLUDES " -I${dir}")
   endforeach()
   set(CMAKE_C_COMPILE_OBJECT   "<CMAKE_C_COMPILER>   <DEFINES> ${BGQ_SYSTEM_INCLUDES} <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
   set(CMAKE_CXX_COMPILE_OBJECT "<CMAKE_CXX_COMPILER> <DEFINES> ${BGQ_SYSTEM_INCLUDES} <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
diff --git a/Modules/Platform/BlueGeneQ-dynamic-GNU-C.cmake b/Modules/Platform/BlueGeneQ-dynamic-GNU-C.cmake
index 102ac80..6758304 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-GNU-C.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-GNU-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(GNU C)
diff --git a/Modules/Platform/BlueGeneQ-dynamic-GNU-CXX.cmake b/Modules/Platform/BlueGeneQ-dynamic-GNU-CXX.cmake
index cd8ab24..5d40f9f 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-GNU-CXX.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-GNU-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(GNU CXX)
diff --git a/Modules/Platform/BlueGeneQ-dynamic-GNU-Fortran.cmake b/Modules/Platform/BlueGeneQ-dynamic-GNU-Fortran.cmake
index c029f0f..6105999 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-GNU-Fortran.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-GNU-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(GNU Fortran)
diff --git a/Modules/Platform/BlueGeneQ-dynamic-XL-C.cmake b/Modules/Platform/BlueGeneQ-dynamic-XL-C.cmake
index 0077313..f46fa95 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-XL-C.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-XL-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(XL C)
diff --git a/Modules/Platform/BlueGeneQ-dynamic-XL-CXX.cmake b/Modules/Platform/BlueGeneQ-dynamic-XL-CXX.cmake
index 0f43cb2..c463379 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-XL-CXX.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-XL-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(XL CXX)
diff --git a/Modules/Platform/BlueGeneQ-dynamic-XL-Fortran.cmake b/Modules/Platform/BlueGeneQ-dynamic-XL-Fortran.cmake
index 12e446e..a6ac03b 100644
--- a/Modules/Platform/BlueGeneQ-dynamic-XL-Fortran.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic-XL-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_dynamic(XL Fortran)
diff --git a/Modules/Platform/BlueGeneQ-dynamic.cmake b/Modules/Platform/BlueGeneQ-dynamic.cmake
index 0283900..9440a3e 100644
--- a/Modules/Platform/BlueGeneQ-dynamic.cmake
+++ b/Modules/Platform/BlueGeneQ-dynamic.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(Platform/BlueGeneQ-base)
 set(CMAKE_FIND_LIBRARY_SUFFIXES ".so" ".a")
diff --git a/Modules/Platform/BlueGeneQ-static-GNU-C.cmake b/Modules/Platform/BlueGeneQ-static-GNU-C.cmake
index 70c84ba..5fdc25c 100644
--- a/Modules/Platform/BlueGeneQ-static-GNU-C.cmake
+++ b/Modules/Platform/BlueGeneQ-static-GNU-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(GNU C)
diff --git a/Modules/Platform/BlueGeneQ-static-GNU-CXX.cmake b/Modules/Platform/BlueGeneQ-static-GNU-CXX.cmake
index 8f991de..ad7c092 100644
--- a/Modules/Platform/BlueGeneQ-static-GNU-CXX.cmake
+++ b/Modules/Platform/BlueGeneQ-static-GNU-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(GNU CXX)
diff --git a/Modules/Platform/BlueGeneQ-static-GNU-Fortran.cmake b/Modules/Platform/BlueGeneQ-static-GNU-Fortran.cmake
index 24dd9e7..f32d1d4 100644
--- a/Modules/Platform/BlueGeneQ-static-GNU-Fortran.cmake
+++ b/Modules/Platform/BlueGeneQ-static-GNU-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(GNU Fortran)
diff --git a/Modules/Platform/BlueGeneQ-static-XL-C.cmake b/Modules/Platform/BlueGeneQ-static-XL-C.cmake
index 5555a68..465128f 100644
--- a/Modules/Platform/BlueGeneQ-static-XL-C.cmake
+++ b/Modules/Platform/BlueGeneQ-static-XL-C.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(XL C)
diff --git a/Modules/Platform/BlueGeneQ-static-XL-CXX.cmake b/Modules/Platform/BlueGeneQ-static-XL-CXX.cmake
index 07c3c3d..abd4ebf 100644
--- a/Modules/Platform/BlueGeneQ-static-XL-CXX.cmake
+++ b/Modules/Platform/BlueGeneQ-static-XL-CXX.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(XL CXX)
diff --git a/Modules/Platform/BlueGeneQ-static-XL-Fortran.cmake b/Modules/Platform/BlueGeneQ-static-XL-Fortran.cmake
index 6f99933..c7fbb44 100644
--- a/Modules/Platform/BlueGeneQ-static-XL-Fortran.cmake
+++ b/Modules/Platform/BlueGeneQ-static-XL-Fortran.cmake
@@ -1,16 +1,5 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 __BlueGeneQ_setup_static(XL Fortran)
diff --git a/Modules/Platform/BlueGeneQ-static.cmake b/Modules/Platform/BlueGeneQ-static.cmake
index 30b530d..79cd391 100644
--- a/Modules/Platform/BlueGeneQ-static.cmake
+++ b/Modules/Platform/BlueGeneQ-static.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2010 Todd Gamblin <tgamblin at llnl.gov>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 include(Platform/BlueGeneQ-base)
 set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
diff --git a/Modules/Platform/CYGWIN-CXX.cmake b/Modules/Platform/CYGWIN-Determine-CXX.cmake
similarity index 100%
rename from Modules/Platform/CYGWIN-CXX.cmake
rename to Modules/Platform/CYGWIN-Determine-CXX.cmake
diff --git a/Modules/Platform/CYGWIN-GNU.cmake b/Modules/Platform/CYGWIN-GNU.cmake
index 1a46c10..d08dc81 100644
--- a/Modules/Platform/CYGWIN-GNU.cmake
+++ b/Modules/Platform/CYGWIN-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__CYGWIN_COMPILER_GNU)
@@ -19,7 +9,7 @@ endif()
 set(__CYGWIN_COMPILER_GNU 1)
 
 # TODO: Is -Wl,--enable-auto-import now always default?
-set(CMAKE_EXE_LINKER_FLAGS_INIT "-Wl,--enable-auto-import")
+string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " -Wl,--enable-auto-import")
 set(CMAKE_CREATE_WIN32_EXE  "-mwindows")
 
 set(CMAKE_GNULD_IMAGE_VERSION
diff --git a/Modules/Platform/Darwin-Absoft-Fortran.cmake b/Modules/Platform/Darwin-Absoft-Fortran.cmake
index dc62b0d..8caa202 100644
--- a/Modules/Platform/Darwin-Absoft-Fortran.cmake
+++ b/Modules/Platform/Darwin-Absoft-Fortran.cmake
@@ -1,16 +1,5 @@
-#=============================================================================
-# Copyright 2011 Kitware, Inc.
-# Copyright 2013 OpenGamma Ltd. <graham at opengamma.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# 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.
 
diff --git a/Modules/Platform/Darwin-Clang.cmake b/Modules/Platform/Darwin-Clang.cmake
index 61a5e0c..a6661a8 100644
--- a/Modules/Platform/Darwin-Clang.cmake
+++ b/Modules/Platform/Darwin-Clang.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__DARWIN_COMPILER_CLANG)
diff --git a/Modules/Platform/Darwin-CXX.cmake b/Modules/Platform/Darwin-Determine-CXX.cmake
similarity index 100%
rename from Modules/Platform/Darwin-CXX.cmake
rename to Modules/Platform/Darwin-Determine-CXX.cmake
diff --git a/Modules/Platform/Darwin-GNU-Fortran.cmake b/Modules/Platform/Darwin-GNU-Fortran.cmake
index 6724f9b..568d79b 100644
--- a/Modules/Platform/Darwin-GNU-Fortran.cmake
+++ b/Modules/Platform/Darwin-GNU-Fortran.cmake
@@ -1,16 +1,5 @@
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-# Copyright 2013 OpenGamma Ltd. <graham at opengamma.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 include(Platform/Darwin-GNU)
 __darwin_compiler_gnu(Fortran)
diff --git a/Modules/Platform/Darwin-GNU.cmake b/Modules/Platform/Darwin-GNU.cmake
index 87d1d23..9f9ef01 100644
--- a/Modules/Platform/Darwin-GNU.cmake
+++ b/Modules/Platform/Darwin-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__DARWIN_COMPILER_GNU)
diff --git a/Modules/Platform/Darwin-Initialize.cmake b/Modules/Platform/Darwin-Initialize.cmake
index 91c2cf3..39374e1 100644
--- a/Modules/Platform/Darwin-Initialize.cmake
+++ b/Modules/Platform/Darwin-Initialize.cmake
@@ -90,7 +90,7 @@ elseif("${CMAKE_GENERATOR}" MATCHES Xcode
       endif()
     endforeach()
 
-    if(NOT CMAKE_OSX_DEPLOYMENT_TARGET AND _CURRENT_OSX_VERSION VERSION_LESS _CMAKE_OSX_DEPLOYMENT_TARGET)
+    if(NOT CMAKE_CROSSCOMPILING AND NOT CMAKE_OSX_DEPLOYMENT_TARGET AND _CURRENT_OSX_VERSION VERSION_LESS _CMAKE_OSX_DEPLOYMENT_TARGET)
       set(CMAKE_OSX_DEPLOYMENT_TARGET ${_CURRENT_OSX_VERSION} CACHE STRING
         "Minimum OS X version to target for deployment (at runtime); newer APIs weak linked. Set to empty string for default value." FORCE)
     endif()
@@ -125,8 +125,10 @@ if(CMAKE_OSX_SYSROOT)
       set(_CMAKE_OSX_SYSROOT_ORIG "")
     endif()
     set(_CMAKE_OSX_SYSROOT_PATH "${CMAKE_OSX_SYSROOT}")
-  else()
-    # Transform the sdk name into a path.
+  endif()
+
+  if(CMAKE_OSX_SYSROOT)
+    # Transform the (maybe unversioned) sysroot into a versioned path.
     execute_process(
       COMMAND xcodebuild -sdk ${CMAKE_OSX_SYSROOT} -version Path
       OUTPUT_VARIABLE _stdout
diff --git a/Modules/Platform/Darwin-Intel-Fortran.cmake b/Modules/Platform/Darwin-Intel-Fortran.cmake
index a604bb6..2299da9 100644
--- a/Modules/Platform/Darwin-Intel-Fortran.cmake
+++ b/Modules/Platform/Darwin-Intel-Fortran.cmake
@@ -1,15 +1,5 @@
-#=============================================================================
-# Copyright 2013 OpenGamma Ltd. <graham at opengamma.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 include(Platform/Darwin-Intel)
 __darwin_compiler_intel(Fortran)
diff --git a/Modules/Platform/Darwin-Intel.cmake b/Modules/Platform/Darwin-Intel.cmake
index 42f1154..dd33cec 100644
--- a/Modules/Platform/Darwin-Intel.cmake
+++ b/Modules/Platform/Darwin-Intel.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2014 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__DARWIN_COMPILER_INTEL)
diff --git a/Modules/Platform/Darwin-NAG-Fortran.cmake b/Modules/Platform/Darwin-NAG-Fortran.cmake
index e3ac9b5..8d3e741 100644
--- a/Modules/Platform/Darwin-NAG-Fortran.cmake
+++ b/Modules/Platform/Darwin-NAG-Fortran.cmake
@@ -1,16 +1,5 @@
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-# Copyright 2013 OpenGamma Ltd. <graham at opengamma.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
+# 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.
 
diff --git a/Modules/Platform/GHS-MULTI-Initialize.cmake b/Modules/Platform/GHS-MULTI-Initialize.cmake
index 6e6b4ff..fcda6f6 100644
--- a/Modules/Platform/GHS-MULTI-Initialize.cmake
+++ b/Modules/Platform/GHS-MULTI-Initialize.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 #Setup Greenhills MULTI specific compilation information
 
diff --git a/Modules/Platform/GHS-MULTI.cmake b/Modules/Platform/GHS-MULTI.cmake
index 211cf3e..60a15c4 100644
--- a/Modules/Platform/GHS-MULTI.cmake
+++ b/Modules/Platform/GHS-MULTI.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 
diff --git a/Modules/Platform/Generic-ADSP-C.cmake b/Modules/Platform/Generic-ADSP-C.cmake
index 4b9ed9d..de1cee2 100644
--- a/Modules/Platform/Generic-ADSP-C.cmake
+++ b/Modules/Platform/Generic-ADSP-C.cmake
@@ -4,10 +4,10 @@ include(Platform/Generic-ADSP-Common)
 
 set(CMAKE_C_OUTPUT_EXTENSION ".doj")
 
-set(CMAKE_C_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_C_FLAGS_MINSIZEREL_INIT "")
-set(CMAKE_C_FLAGS_RELEASE_INIT "")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "")
+string(APPEND CMAKE_C_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " ")
+string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " ")
+string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " ")
 
 set(CMAKE_C_CREATE_STATIC_LIBRARY
     "<CMAKE_C_COMPILER> -build-lib -proc ${ADSP_PROCESSOR} -si-revision ${ADSP_PROCESSOR_SILICIUM_REVISION} -o <TARGET> <CMAKE_C_LINK_FLAGS> <OBJECTS>")
diff --git a/Modules/Platform/Generic-ADSP-CXX.cmake b/Modules/Platform/Generic-ADSP-CXX.cmake
index 9673aef..0cde8f2 100644
--- a/Modules/Platform/Generic-ADSP-CXX.cmake
+++ b/Modules/Platform/Generic-ADSP-CXX.cmake
@@ -2,10 +2,10 @@ include(Platform/Generic-ADSP-Common)
 
 set(CMAKE_CXX_OUTPUT_EXTENSION ".doj")
 
-set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "")
-set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "")
+string(APPEND CMAKE_CXX_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " ")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " ")
+string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " ")
 
 set(CMAKE_CXX_CREATE_STATIC_LIBRARY
      "<CMAKE_CXX_COMPILER> -build-lib -proc ${ADSP_PROCESSOR} -si-revision ${ADSP_PROCESSOR_SILICIUM_REVISION} -o <TARGET> <CMAKE_CXX_LINK_FLAGS> <OBJECTS>")
diff --git a/Modules/Platform/Generic-SDCC-C.cmake b/Modules/Platform/Generic-SDCC-C.cmake
index a1ca812..bbefe19 100644
--- a/Modules/Platform/Generic-SDCC-C.cmake
+++ b/Modules/Platform/Generic-SDCC-C.cmake
@@ -30,7 +30,7 @@ set(CMAKE_AR "${SDCCLIB_EXECUTABLE}" CACHE FILEPATH "The sdcc librarian" FORCE)
 
 # CMAKE_C_FLAGS_INIT and CMAKE_EXE_LINKER_FLAGS_INIT should be set in a CMAKE_SYSTEM_PROCESSOR file
 if(NOT DEFINED CMAKE_C_FLAGS_INIT)
-  set(CMAKE_C_FLAGS_INIT "-mmcs51 --model-small")
+  string(APPEND CMAKE_C_FLAGS_INIT " -mmcs51 --model-small")
 endif()
 
 if(NOT DEFINED CMAKE_EXE_LINKER_FLAGS_INIT)
diff --git a/Modules/Platform/HP-UX-GNU-CXX.cmake b/Modules/Platform/HP-UX-GNU-CXX.cmake
index 689bed0..ac72560 100644
--- a/Modules/Platform/HP-UX-GNU-CXX.cmake
+++ b/Modules/Platform/HP-UX-GNU-CXX.cmake
@@ -1,2 +1,3 @@
 include(Platform/HP-UX-GNU)
 __hpux_compiler_gnu(CXX)
+unset(CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN)
diff --git a/Modules/Platform/HP-UX-GNU.cmake b/Modules/Platform/HP-UX-GNU.cmake
index 6c71784..7ac804b 100644
--- a/Modules/Platform/HP-UX-GNU.cmake
+++ b/Modules/Platform/HP-UX-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__HPUX_COMPILER_GNU)
@@ -26,4 +16,5 @@ macro(__hpux_compiler_gnu lang)
   set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,+h")
 
   set(CMAKE_${lang}_LINK_FLAGS "-Wl,+s,+nodefaultrpath")
+  unset(CMAKE_${lang}_COMPILE_OPTIONS_VISIBILITY)
 endmacro()
diff --git a/Modules/Platform/HP-UX-HP-CXX.cmake b/Modules/Platform/HP-UX-HP-CXX.cmake
index 6d90191..d37d2b0 100644
--- a/Modules/Platform/HP-UX-HP-CXX.cmake
+++ b/Modules/Platform/HP-UX-HP-CXX.cmake
@@ -8,7 +8,7 @@ set(CMAKE_CXX_CREATE_ASSEMBLY_SOURCE
   "rm -f `basename \"<SOURCE>\" | sed 's/\\.[^./]*$$//'`.o"
   )
 
-set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
-set(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "+O3 -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELEASE_INIT "+O2 -DNDEBUG")
-set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-g")
+string(APPEND CMAKE_CXX_FLAGS_DEBUG_INIT " -g")
+string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " +O3 -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " +O2 -DNDEBUG")
+string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " -g")
diff --git a/Modules/Platform/HP-UX-HP.cmake b/Modules/Platform/HP-UX-HP.cmake
index 3935c31..b301d17 100644
--- a/Modules/Platform/HP-UX-HP.cmake
+++ b/Modules/Platform/HP-UX-HP.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__HPUX_COMPILER_HP)
@@ -27,7 +17,7 @@ macro(__hpux_compiler_hp lang)
   set(CMAKE_SHARED_LIBRARY_RUNTIME_${lang}_FLAG_SEP ":")
   set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,+h")
 
-  set(CMAKE_${lang}_FLAGS_INIT "")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
 
   set(CMAKE_${lang}_LINK_FLAGS "-Wl,+s,+nodefaultrpath")
 endmacro()
diff --git a/Modules/Platform/Linux-CXX.cmake b/Modules/Platform/Linux-Determine-CXX.cmake
similarity index 100%
rename from Modules/Platform/Linux-CXX.cmake
rename to Modules/Platform/Linux-Determine-CXX.cmake
diff --git a/Modules/Platform/Linux-GNU.cmake b/Modules/Platform/Linux-GNU.cmake
index 0e254c6..6878254 100644
--- a/Modules/Platform/Linux-GNU.cmake
+++ b/Modules/Platform/Linux-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__LINUX_COMPILER_GNU)
diff --git a/Modules/Platform/Linux-Intel-Fortran.cmake b/Modules/Platform/Linux-Intel-Fortran.cmake
index 0c9523c..d8e94d0 100644
--- a/Modules/Platform/Linux-Intel-Fortran.cmake
+++ b/Modules/Platform/Linux-Intel-Fortran.cmake
@@ -1,4 +1,4 @@
 include(Platform/Linux-Intel)
 __linux_compiler_intel(Fortran)
-set(CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS "${CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS} -nofor_main")
+string(APPEND CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS " -nofor_main")
 set(CMAKE_SHARED_LIBRARY_LINK_Fortran_FLAGS "")
diff --git a/Modules/Platform/Linux-Intel.cmake b/Modules/Platform/Linux-Intel.cmake
index 20fddb4..85a0772 100644
--- a/Modules/Platform/Linux-Intel.cmake
+++ b/Modules/Platform/Linux-Intel.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__LINUX_COMPILER_INTEL)
diff --git a/Modules/Platform/Linux-PGI.cmake b/Modules/Platform/Linux-PGI.cmake
index baa2248..a407e43 100644
--- a/Modules/Platform/Linux-PGI.cmake
+++ b/Modules/Platform/Linux-PGI.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__LINUX_COMPILER_PGI)
diff --git a/Modules/Platform/Linux-PathScale.cmake b/Modules/Platform/Linux-PathScale.cmake
index d230ab2..6070606 100644
--- a/Modules/Platform/Linux-PathScale.cmake
+++ b/Modules/Platform/Linux-PathScale.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__LINUX_COMPILER_PATHSCALE)
diff --git a/Modules/Platform/Linux.cmake b/Modules/Platform/Linux.cmake
index e40a74f..1f8c1b4 100644
--- a/Modules/Platform/Linux.cmake
+++ b/Modules/Platform/Linux.cmake
@@ -50,8 +50,9 @@ set(CMAKE_LIBRARY_ARCHITECTURE_REGEX "[a-z0-9_]+(-[a-z0-9_]+)?-linux-gnu[a-z0-9_
 
 include(Platform/UnixPaths)
 
-# Debian has lib64 paths only for compatibility so they should not be
+# Debian has lib32 and lib64 paths only for compatibility so they should not be
 # searched.
 if(NOT CMAKE_CROSSCOMPILING AND EXISTS "/etc/debian_version")
+  set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS FALSE)
   set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS FALSE)
 endif()
diff --git a/Modules/Platform/OpenBSD.cmake b/Modules/Platform/OpenBSD.cmake
index 7ac6c7e..6466a0a 100644
--- a/Modules/Platform/OpenBSD.cmake
+++ b/Modules/Platform/OpenBSD.cmake
@@ -18,6 +18,7 @@ endif()
 set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_OPENBSD_VERSIONING 1)
 
 # OpenBSD has no multilib
+set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS FALSE)
 set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS FALSE)
 
 # OpenBSD policy requires that shared libraries be installed without
diff --git a/Modules/Platform/SCO_SV.cmake b/Modules/Platform/SCO_SV.cmake
index ddd9600..1cb4b38 100644
--- a/Modules/Platform/SCO_SV.cmake
+++ b/Modules/Platform/SCO_SV.cmake
@@ -1,2 +1,3 @@
 set(CMAKE_DL_LIBS "")
+set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-h,")
 include(Platform/UnixPaths)
diff --git a/Modules/Platform/SunOS-GNU.cmake b/Modules/Platform/SunOS-GNU.cmake
index 7169056..485f235 100644
--- a/Modules/Platform/SunOS-GNU.cmake
+++ b/Modules/Platform/SunOS-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__SUNOS_COMPILER_GNU)
diff --git a/Modules/Platform/SunOS-PathScale.cmake b/Modules/Platform/SunOS-PathScale.cmake
index 1afe56a..25ead80 100644
--- a/Modules/Platform/SunOS-PathScale.cmake
+++ b/Modules/Platform/SunOS-PathScale.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2016 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__SUNOS_COMPILER_PATHSCALE)
diff --git a/Modules/Platform/UnixPaths.cmake b/Modules/Platform/UnixPaths.cmake
index 20ee1d1..b216d03 100644
--- a/Modules/Platform/UnixPaths.cmake
+++ b/Modules/Platform/UnixPaths.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Block multiple inclusion because "CMakeCInformation.cmake" includes
 # "Platform/${CMAKE_SYSTEM_NAME}" even though the generic module
@@ -93,5 +83,6 @@ list(APPEND CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES
   /usr/include
   )
 
-# Enable use of lib64 search path variants by default.
+# Enable use of lib32 and lib64 search path variants by default.
+set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS TRUE)
 set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS TRUE)
diff --git a/Modules/Platform/Windows-Clang.cmake b/Modules/Platform/Windows-Clang.cmake
index da19a3d..bcfda93 100644
--- a/Modules/Platform/Windows-Clang.cmake
+++ b/Modules/Platform/Windows-Clang.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2001-2013 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__WINDOWS_CLANG)
diff --git a/Modules/Platform/Windows-CXX.cmake b/Modules/Platform/Windows-Determine-CXX.cmake
similarity index 100%
rename from Modules/Platform/Windows-CXX.cmake
rename to Modules/Platform/Windows-Determine-CXX.cmake
diff --git a/Modules/Platform/Windows-Embarcadero.cmake b/Modules/Platform/Windows-Embarcadero.cmake
index 102e3a6..f8e1c9e 100644
--- a/Modules/Platform/Windows-Embarcadero.cmake
+++ b/Modules/Platform/Windows-Embarcadero.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__WINDOWS_EMBARCADERO)
@@ -64,15 +54,11 @@ set(CMAKE_CREATE_CONSOLE_EXE "${_tC}" )
 set (CMAKE_BUILD_TYPE Debug CACHE STRING
      "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel.")
 
-set (CMAKE_EXE_LINKER_FLAGS_INIT "${_tM} -lS:1048576 -lSc:4098 -lH:1048576 -lHc:8192 ")
-set (CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT "-v")
-set (CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT "-v")
-set (CMAKE_SHARED_LINKER_FLAGS_INIT ${CMAKE_EXE_LINKER_FLAGS_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT ${CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO_INIT ${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_INIT ${CMAKE_SHARED_LINKER_FLAGS_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_DEBUG_INIT ${CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO_INIT ${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO_INIT})
+foreach(t EXE SHARED MODULE)
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_INIT " ${_tM} -lS:1048576 -lSc:4098 -lH:1048576 -lHc:8192 ")
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_DEBUG_INIT " -v")
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_RELWITHDEBINFO_INIT " -v")
+endforeach()
 
 # The Borland link tool does not support multiple concurrent
 # invocations within a single working directory.
@@ -132,10 +118,10 @@ macro(__embarcadero_language lang)
     )
 
   # Initial configuration flags.
-  set(CMAKE_${lang}_FLAGS_INIT "${_tM}")
-  set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-Od -v")
-  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-O1 -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-O2 -DNDEBUG")
-  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-Od")
+  string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_tM}")
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -Od -v")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -O1 -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -O2 -DNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -Od")
   set(CMAKE_${lang}_STANDARD_LIBRARIES_INIT "import32.lib")
 endmacro()
diff --git a/Modules/Platform/Windows-GNU.cmake b/Modules/Platform/Windows-GNU.cmake
index d8a423e..22daa62 100644
--- a/Modules/Platform/Windows-GNU.cmake
+++ b/Modules/Platform/Windows-GNU.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__WINDOWS_GNU)
diff --git a/Modules/Platform/Windows-Intel-Fortran.cmake b/Modules/Platform/Windows-Intel-Fortran.cmake
index 1b93db8..3981a09 100644
--- a/Modules/Platform/Windows-Intel-Fortran.cmake
+++ b/Modules/Platform/Windows-Intel-Fortran.cmake
@@ -4,8 +4,8 @@ set(_COMPILE_Fortran " /fpp")
 set(CMAKE_Fortran_MODDIR_FLAG "-module:")
 set(CMAKE_Fortran_STANDARD_LIBRARIES_INIT "user32.lib")
 __windows_compiler_intel(Fortran)
-set (CMAKE_Fortran_FLAGS_INIT "/W1 /nologo /fpp /libs:dll /threads")
-set (CMAKE_Fortran_FLAGS_DEBUG_INIT "/Od /debug:full /dbglibs")
-set (CMAKE_Fortran_FLAGS_MINSIZEREL_INIT "/O1 /DNDEBUG")
-set (CMAKE_Fortran_FLAGS_RELEASE_INIT "/O2 /DNDEBUG")
-set (CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT "/O2 /debug:full /DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_INIT " /W1 /nologo /fpp /libs:dll /threads")
+string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " /Od /debug:full /dbglibs")
+string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " /O1 /DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " /O2 /DNDEBUG")
+string(APPEND CMAKE_Fortran_FLAGS_RELWITHDEBINFO_INIT " /O2 /debug:full /DNDEBUG")
diff --git a/Modules/Platform/Windows-Intel.cmake b/Modules/Platform/Windows-Intel.cmake
index 34e6b37..ba31001 100644
--- a/Modules/Platform/Windows-Intel.cmake
+++ b/Modules/Platform/Windows-Intel.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2002-2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__WINDOWS_INTEL)
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index 6c254ed..d72ec66 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2001-2012 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # This module is shared by multiple languages; use include blocker.
 if(__WINDOWS_MSVC)
@@ -166,10 +156,12 @@ if(WINCE)
   endforeach()
 
   set(CMAKE_C_STANDARD_LIBRARIES_INIT "coredll.lib ole32.lib oleaut32.lib uuid.lib commctrl.lib")
-  set(CMAKE_EXE_LINKER_FLAGS_INIT "${CMAKE_EXE_LINKER_FLAGS_INIT} /NODEFAULTLIB:libc.lib /NODEFAULTLIB:oldnames.lib")
+  foreach(t EXE SHARED MODULE)
+    string(APPEND CMAKE_${t}_LINKER_FLAGS_INIT " /NODEFAULTLIB:libc.lib /NODEFAULTLIB:oldnames.lib")
+  endforeach()
 
   if (MSVC_VERSION LESS 1600)
-    set(CMAKE_C_STANDARD_LIBRARIES_INIT "${CMAKE_C_STANDARD_LIBRARIES_INIT} corelibc.lib")
+    string(APPEND CMAKE_C_STANDARD_LIBRARIES_INIT " corelibc.lib")
   endif ()
 elseif(WINDOWS_PHONE OR WINDOWS_STORE)
   set(_PLATFORM_DEFINES "/DWIN32")
@@ -190,7 +182,7 @@ else()
   if(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM")
     set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib")
   elseif(MSVC_VERSION GREATER 1310)
-    if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*")
+    if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)")
       # Clang/C2 in MSVC14 Update 1 seems to not support -fsantinize (yet?)
       # set(_RTC1 "-fsantinize=memory,safe-stack")
       set(_FLAGS_CXX " -frtti -fexceptions")
@@ -235,9 +227,6 @@ elseif(MSVC_CXX_ARCHITECTURE_ID)
 elseif(MSVC_Fortran_ARCHITECTURE_ID)
   set(_MACHINE_ARCH_FLAG "/machine:${MSVC_Fortran_ARCHITECTURE_ID}")
 endif()
-set(CMAKE_EXE_LINKER_FLAGS_INIT "${CMAKE_EXE_LINKER_FLAGS_INIT} ${_MACHINE_ARCH_FLAG}")
-set(CMAKE_STATIC_LINKER_FLAGS_INIT "${CMAKE_STATIC_LINKER_FLAGS_INIT} ${_MACHINE_ARCH_FLAG}")
-unset(_MACHINE_ARCH_FLAG)
 
 # add /debug and /INCREMENTAL:YES to DEBUG and RELWITHDEBINFO also add pdbtype
 # on versions that support it
@@ -250,30 +239,22 @@ if(NOT WINDOWS_PHONE AND NOT WINDOWS_STORE)
   endif()
 endif()
 
-if (CMAKE_COMPILER_SUPPORTS_PDBTYPE)
-  set (CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT "/debug /pdbtype:sept ${MSVC_INCREMENTAL_YES_FLAG}")
-  set (CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT "/debug /pdbtype:sept ${MSVC_INCREMENTAL_YES_FLAG}")
-else ()
-  set (CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT "/debug ${MSVC_INCREMENTAL_YES_FLAG}")
-  set (CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT "/debug ${MSVC_INCREMENTAL_YES_FLAG}")
-endif ()
-# for release and minsize release default to no incremental linking
-set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL_INIT "/INCREMENTAL:NO")
-set(CMAKE_EXE_LINKER_FLAGS_RELEASE_INIT "/INCREMENTAL:NO")
-
-# copy the EXE_LINKER flags to SHARED and MODULE linker flags
-# shared linker flags
-set (CMAKE_SHARED_LINKER_FLAGS_INIT ${CMAKE_EXE_LINKER_FLAGS_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT ${CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO_INIT ${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_RELEASE_INIT ${CMAKE_EXE_LINKER_FLAGS_RELEASE_INIT})
-set (CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL_INIT ${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL_INIT})
-# module linker flags
-set (CMAKE_MODULE_LINKER_FLAGS_INIT ${CMAKE_SHARED_LINKER_FLAGS_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_DEBUG_INIT ${CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO_INIT ${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_RELEASE_INIT ${CMAKE_EXE_LINKER_FLAGS_RELEASE_INIT})
-set (CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL_INIT ${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL_INIT})
+foreach(t EXE SHARED MODULE)
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_INIT " ${_MACHINE_ARCH_FLAG}")
+  if (CMAKE_COMPILER_SUPPORTS_PDBTYPE)
+    string(APPEND CMAKE_${t}_LINKER_FLAGS_DEBUG_INIT " /debug /pdbtype:sept ${MSVC_INCREMENTAL_YES_FLAG}")
+    string(APPEND CMAKE_${t}_LINKER_FLAGS_RELWITHDEBINFO_INIT " /debug /pdbtype:sept ${MSVC_INCREMENTAL_YES_FLAG}")
+  else ()
+    string(APPEND CMAKE_${t}_LINKER_FLAGS_DEBUG_INIT " /debug ${MSVC_INCREMENTAL_YES_FLAG}")
+    string(APPEND CMAKE_${t}_LINKER_FLAGS_RELWITHDEBINFO_INIT " /debug ${MSVC_INCREMENTAL_YES_FLAG}")
+  endif ()
+  # for release and minsize release default to no incremental linking
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_MINSIZEREL_INIT " /INCREMENTAL:NO")
+  string(APPEND CMAKE_${t}_LINKER_FLAGS_RELEASE_INIT " /INCREMENTAL:NO")
+endforeach()
+
+string(APPEND CMAKE_STATIC_LINKER_FLAGS_INIT " ${_MACHINE_ARCH_FLAG}")
+unset(_MACHINE_ARCH_FLAG)
 
 macro(__windows_compiler_msvc lang)
   if(NOT MSVC_VERSION LESS 1400)
@@ -298,20 +279,23 @@ macro(__windows_compiler_msvc lang)
   set(CMAKE_${lang}_LINK_EXECUTABLE
     "${_CMAKE_VS_LINK_EXE}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR>${_PLATFORM_LINK_FLAGS} <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
 
-  if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*")
-    # note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects
-    # that include MS's own headers. CMake itself is affected project too.
-    set(CMAKE_${lang}_FLAGS_INIT "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}")
-    set(CMAKE_${lang}_FLAGS_DEBUG_INIT "-D_DEBUG /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
-    set(CMAKE_${lang}_FLAGS_RELEASE_INIT "/MD -O2 -DNDEBUG")
-    set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "/MD -gline-tables-only -O2 -fno-inline -DNDEBUG")
-    set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "/MD -DNDEBUG") # TODO: Add '-Os' once VS generator maps it properly for Clang
-  else()
-    set(CMAKE_${lang}_FLAGS_INIT "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS /W3${_FLAGS_${lang}}")
-    set(CMAKE_${lang}_FLAGS_DEBUG_INIT "/D_DEBUG /MDd /Zi /Ob0 /Od ${_RTC1}")
-    set(CMAKE_${lang}_FLAGS_RELEASE_INIT "/MD /O2 /Ob2 /DNDEBUG")
-    set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "/MD /Zi /O2 /Ob1 /DNDEBUG")
-    set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "/MD /O1 /Ob1 /DNDEBUG")
+  if("x${lang}" STREQUAL "xC" OR
+      "x${lang}" STREQUAL "xCXX")
+    if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)")
+      # note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects
+      # that include MS's own headers. CMake itself is affected project too.
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}")
+      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -D_DEBUG /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
+      string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD -O2 -DNDEBUG")
+      string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD -gline-tables-only -O2 -fno-inline -DNDEBUG")
+      string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD -DNDEBUG") # TODO: Add '-Os' once VS generator maps it properly for Clang
+    else()
+      string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS /W3${_FLAGS_${lang}}")
+      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /D_DEBUG /MDd /Zi /Ob0 /Od ${_RTC1}")
+      string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD /O2 /Ob2 /DNDEBUG")
+      string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD /Zi /O2 /Ob1 /DNDEBUG")
+      string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD /O1 /Ob1 /DNDEBUG")
+    endif()
   endif()
   set(CMAKE_${lang}_LINKER_SUPPORTS_PDB ON)
   set(CMAKE_NINJA_DEPTYPE_${lang} msvc)
@@ -320,7 +304,7 @@ macro(__windows_compiler_msvc lang)
     set(CMAKE_RC_COMPILER_INIT rc)
   endif()
   if(NOT CMAKE_RC_FLAGS_INIT)
-    set(CMAKE_RC_FLAGS_INIT "${_PLATFORM_DEFINES} ${_PLATFORM_DEFINES_${lang}}")
+    string(APPEND CMAKE_RC_FLAGS_INIT " ${_PLATFORM_DEFINES} ${_PLATFORM_DEFINES_${lang}}")
   endif()
 
   enable_language(RC)
diff --git a/Modules/Platform/Windows-OpenWatcom-C.cmake b/Modules/Platform/Windows-OpenWatcom-C.cmake
new file mode 100644
index 0000000..ce9bc45
--- /dev/null
+++ b/Modules/Platform/Windows-OpenWatcom-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-OpenWatcom)
diff --git a/Modules/Platform/Windows-OpenWatcom-CXX.cmake b/Modules/Platform/Windows-OpenWatcom-CXX.cmake
new file mode 100644
index 0000000..ce9bc45
--- /dev/null
+++ b/Modules/Platform/Windows-OpenWatcom-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-OpenWatcom)
diff --git a/Modules/Platform/Windows-OpenWatcom.cmake b/Modules/Platform/Windows-OpenWatcom.cmake
new file mode 100644
index 0000000..d38d616
--- /dev/null
+++ b/Modules/Platform/Windows-OpenWatcom.cmake
@@ -0,0 +1,129 @@
+# 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(__WINDOWS_OPENWATCOM)
+  return()
+endif()
+set(__WINDOWS_OPENWATCOM 1)
+
+set(CMAKE_LIBRARY_PATH_FLAG "libpath ")
+set(CMAKE_LINK_LIBRARY_FLAG "library ")
+set(CMAKE_LINK_LIBRARY_FILE_FLAG "library")
+
+if(CMAKE_VERBOSE_MAKEFILE)
+  set(CMAKE_WCL_QUIET)
+  set(CMAKE_WLINK_QUIET)
+  set(CMAKE_LIB_QUIET)
+else()
+  set(CMAKE_WCL_QUIET "-zq")
+  set(CMAKE_WLINK_QUIET "option quiet")
+  set(CMAKE_LIB_QUIET "-q")
+endif()
+
+string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " ")
+set(CMAKE_CREATE_WIN32_EXE "system nt_win" )
+set(CMAKE_CREATE_CONSOLE_EXE "system nt" )
+string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " system nt_dll")
+string(APPEND CMAKE_MODULE_LINKER_FLAGS_INIT " system nt_dll")
+foreach(type SHARED MODULE EXE)
+  string(APPEND CMAKE_${type}_LINKER_FLAGS_DEBUG_INIT " debug all opt map")
+  string(APPEND CMAKE_${type}_LINKER_FLAGS_RELWITHDEBINFO_INIT " debug all opt map")
+endforeach()
+
+set(CMAKE_C_COMPILE_OPTIONS_DLL "-bd") # Note: This variable is a ';' separated list
+set(CMAKE_SHARED_LIBRARY_C_FLAGS "-bd") # ... while this is a space separated string.
+
+set(CMAKE_RC_COMPILER "rc" )
+
+set(CMAKE_BUILD_TYPE_INIT Debug)
+
+# single/multi-threaded                 /-bm
+# static/DLL run-time libraries         /-br
+# default is setup for multi-threaded + DLL run-time libraries
+string(APPEND CMAKE_C_FLAGS_INIT " -bt=nt -w3 -dWIN32 -br -bm")
+string(APPEND CMAKE_CXX_FLAGS_INIT " -bt=nt -xs -w3 -dWIN32 -br -bm")
+foreach(lang C CXX)
+  string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -d2")
+  string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -s -os -d0 -dNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -s -ot -d0 -dNDEBUG")
+  string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -s -ot -d1 -dNDEBUG")
+endforeach()
+
+foreach(type CREATE_SHARED_LIBRARY CREATE_SHARED_MODULE LINK_EXECUTABLE)
+  set(CMAKE_C_${type}_USE_WATCOM_QUOTE 1)
+  set(CMAKE_CXX_${type}_USE_WATCOM_QUOTE 1)
+endforeach()
+
+set(CMAKE_C_CREATE_IMPORT_LIBRARY
+  "wlib -c -q -n -b <TARGET_IMPLIB> +<TARGET_QUOTED>")
+set(CMAKE_CXX_CREATE_IMPORT_LIBRARY ${CMAKE_C_CREATE_IMPORT_LIBRARY})
+
+set(CMAKE_C_LINK_EXECUTABLE
+    "wlink ${CMAKE_START_TEMP_FILE} ${CMAKE_WLINK_QUIET} name <TARGET> <LINK_FLAGS> file {<OBJECTS>} <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
+
+
+set(CMAKE_CXX_LINK_EXECUTABLE ${CMAKE_C_LINK_EXECUTABLE})
+
+# compile a C++ file into an object file
+set(CMAKE_CXX_COMPILE_OBJECT
+    "<CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<OBJECT> -c -cc++ <SOURCE>${CMAKE_END_TEMP_FILE}")
+
+# compile a C file into an object file
+set(CMAKE_C_COMPILE_OBJECT
+    "<CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<OBJECT> -c -cc <SOURCE>${CMAKE_END_TEMP_FILE}")
+
+# preprocess a C source file
+set(CMAKE_C_CREATE_PREPROCESSED_SOURCE
+    "<CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<PREPROCESSED_SOURCE> -pl -cc <SOURCE>${CMAKE_END_TEMP_FILE}")
+
+# preprocess a C++ source file
+set(CMAKE_CXX_CREATE_PREPROCESSED_SOURCE
+    "<CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<PREPROCESSED_SOURCE> -pl -cc++ <SOURCE>${CMAKE_END_TEMP_FILE}")
+
+set(CMAKE_CXX_CREATE_SHARED_LIBRARY
+ "wlink ${CMAKE_START_TEMP_FILE} ${CMAKE_WLINK_QUIET} name <TARGET> <LINK_FLAGS> option implib=<TARGET_IMPLIB> file {<OBJECTS>} <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
+string(REPLACE " option implib=<TARGET_IMPLIB>" ""
+  CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_LIBRARY}")
+
+# create a C shared library
+set(CMAKE_C_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY})
+
+# create a C shared module
+set(CMAKE_C_CREATE_SHARED_MODULE ${CMAKE_CXX_CREATE_SHARED_MODULE})
+
+# create a C++ static library
+set(CMAKE_CXX_CREATE_STATIC_LIBRARY  "wlib ${CMAKE_LIB_QUIET} -c -n -b <TARGET_QUOTED> <LINK_FLAGS> <OBJECTS> ")
+
+# create a C static library
+set(CMAKE_C_CREATE_STATIC_LIBRARY ${CMAKE_CXX_CREATE_STATIC_LIBRARY})
+
+if(NOT _CMAKE_WATCOM_VERSION)
+  set(_CMAKE_WATCOM_VERSION 1)
+  if(CMAKE_C_COMPILER_VERSION)
+    set(_compiler_version ${CMAKE_C_COMPILER_VERSION})
+    set(_compiler_id ${CMAKE_C_COMPILER_ID})
+  else()
+    set(_compiler_version ${CMAKE_CXX_COMPILER_VERSION})
+    set(_compiler_id ${CMAKE_CXX_COMPILER_ID})
+  endif()
+  set(WATCOM16)
+  set(WATCOM17)
+  set(WATCOM18)
+  set(WATCOM19)
+  if("${_compiler_id}" STREQUAL "OpenWatcom")
+    if("${_compiler_version}" VERSION_LESS 1.7)
+      set(WATCOM16 1)
+    endif()
+    if("${_compiler_version}" VERSION_EQUAL 1.7)
+      set(WATCOM17 1)
+    endif()
+    if("${_compiler_version}" VERSION_EQUAL 1.8)
+      set(WATCOM18 1)
+    endif()
+    if("${_compiler_version}" VERSION_EQUAL 1.9)
+      set(WATCOM19 1)
+    endif()
+  endif()
+endif()
diff --git a/Modules/Platform/Windows-Watcom-C.cmake b/Modules/Platform/Windows-Watcom-C.cmake
new file mode 100644
index 0000000..44a008b
--- /dev/null
+++ b/Modules/Platform/Windows-Watcom-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-OpenWatcom-C)
diff --git a/Modules/Platform/Windows-Watcom-CXX.cmake b/Modules/Platform/Windows-Watcom-CXX.cmake
new file mode 100644
index 0000000..63d109b
--- /dev/null
+++ b/Modules/Platform/Windows-Watcom-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-OpenWatcom-CXX)
diff --git a/Modules/Platform/Windows-wcl386.cmake b/Modules/Platform/Windows-wcl386.cmake
deleted file mode 100644
index 3bc5444..0000000
--- a/Modules/Platform/Windows-wcl386.cmake
+++ /dev/null
@@ -1,119 +0,0 @@
-set(CMAKE_LIBRARY_PATH_FLAG "libpath ")
-set(CMAKE_LINK_LIBRARY_FLAG "library ")
-set(CMAKE_LINK_LIBRARY_FILE_FLAG "library")
-
-if(CMAKE_VERBOSE_MAKEFILE)
-  set(CMAKE_WCL_QUIET)
-  set(CMAKE_WLINK_QUIET)
-  set(CMAKE_LIB_QUIET)
-else()
-  set(CMAKE_WCL_QUIET "-zq")
-  set(CMAKE_WLINK_QUIET "option quiet")
-  set(CMAKE_LIB_QUIET "-q")
-endif()
-
-set(CMAKE_EXE_LINKER_FLAGS_INIT)
-set(CMAKE_CREATE_WIN32_EXE "system nt_win" )
-set(CMAKE_CREATE_CONSOLE_EXE "system nt" )
-set(CMAKE_SHARED_LINKER_FLAGS_INIT "system nt_dll")
-set(CMAKE_MODULE_LINKER_FLAGS_INIT "system nt_dll")
-foreach(type SHARED MODULE EXE)
-  set(CMAKE_${type}_LINKER_FLAGS_DEBUG_INIT "debug all opt map")
-  set(CMAKE_${type}_LINKER_FLAGS_RELWITHDEBINFO_INIT "debug all opt map")
-endforeach()
-
-set(CMAKE_C_COMPILE_OPTIONS_DLL "-bd") # Note: This variable is a ';' separated list
-set(CMAKE_SHARED_LIBRARY_C_FLAGS "-bd") # ... while this is a space separated string.
-
-set(CMAKE_RC_COMPILER "rc" )
-
-set(CMAKE_BUILD_TYPE_INIT Debug)
-
-# single/multi-threaded                 /-bm
-# static/DLL run-time libraries         /-br
-# default is setup for multi-threaded + DLL run-time libraries
-set (CMAKE_C_FLAGS_INIT "-bt=nt -w3 -dWIN32 -br -bm")
-set (CMAKE_CXX_FLAGS_INIT "-bt=nt -xs -w3 -dWIN32 -br -bm")
-foreach(lang C CXX)
-  set (CMAKE_${lang}_FLAGS_DEBUG_INIT "-d2")
-  set (CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "-s -os -d0 -dNDEBUG")
-  set (CMAKE_${lang}_FLAGS_RELEASE_INIT "-s -ot -d0 -dNDEBUG")
-  set (CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "-s -ot -d1 -dNDEBUG")
-endforeach()
-
-foreach(type CREATE_SHARED_LIBRARY CREATE_SHARED_MODULE LINK_EXECUTABLE)
-  set(CMAKE_C_${type}_USE_WATCOM_QUOTE 1)
-  set(CMAKE_CXX_${type}_USE_WATCOM_QUOTE 1)
-endforeach()
-
-set(CMAKE_C_CREATE_IMPORT_LIBRARY
-  "wlib -c -q -n -b <TARGET_IMPLIB> +<TARGET_QUOTED>")
-set(CMAKE_CXX_CREATE_IMPORT_LIBRARY ${CMAKE_C_CREATE_IMPORT_LIBRARY})
-
-set(CMAKE_C_LINK_EXECUTABLE
-    "wlink ${CMAKE_START_TEMP_FILE} ${CMAKE_WLINK_QUIET} name <TARGET> <LINK_FLAGS> file {<OBJECTS>} <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
-
-
-set(CMAKE_CXX_LINK_EXECUTABLE ${CMAKE_C_LINK_EXECUTABLE})
-
-# compile a C++ file into an object file
-set(CMAKE_CXX_COMPILE_OBJECT
-    "<CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<OBJECT> -c -cc++ <SOURCE>${CMAKE_END_TEMP_FILE}")
-
-# compile a C file into an object file
-set(CMAKE_C_COMPILE_OBJECT
-    "<CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<OBJECT> -c -cc <SOURCE>${CMAKE_END_TEMP_FILE}")
-
-# preprocess a C source file
-set(CMAKE_C_CREATE_PREPROCESSED_SOURCE
-    "<CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<PREPROCESSED_SOURCE> -pl -cc <SOURCE>${CMAKE_END_TEMP_FILE}")
-
-# preprocess a C++ source file
-set(CMAKE_CXX_CREATE_PREPROCESSED_SOURCE
-    "<CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_WCL_QUIET} -d+ <DEFINES> <INCLUDES> <FLAGS> -fo<PREPROCESSED_SOURCE> -pl -cc++ <SOURCE>${CMAKE_END_TEMP_FILE}")
-
-set(CMAKE_CXX_CREATE_SHARED_LIBRARY
- "wlink ${CMAKE_START_TEMP_FILE} ${CMAKE_WLINK_QUIET} name <TARGET> <LINK_FLAGS> option implib=<TARGET_IMPLIB> file {<OBJECTS>} <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
-string(REPLACE " option implib=<TARGET_IMPLIB>" ""
-  CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_LIBRARY}")
-
-# create a C shared library
-set(CMAKE_C_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY})
-
-# create a C shared module
-set(CMAKE_C_CREATE_SHARED_MODULE ${CMAKE_CXX_CREATE_SHARED_MODULE})
-
-# create a C++ static library
-set(CMAKE_CXX_CREATE_STATIC_LIBRARY  "wlib ${CMAKE_LIB_QUIET} -c -n -b <TARGET_QUOTED> <LINK_FLAGS> <OBJECTS> ")
-
-# create a C static library
-set(CMAKE_C_CREATE_STATIC_LIBRARY ${CMAKE_CXX_CREATE_STATIC_LIBRARY})
-
-if(NOT _CMAKE_WATCOM_VERSION)
-  set(_CMAKE_WATCOM_VERSION 1)
-  if(CMAKE_C_COMPILER_VERSION)
-    set(_compiler_version ${CMAKE_C_COMPILER_VERSION})
-    set(_compiler_id ${CMAKE_C_COMPILER_ID})
-  else()
-    set(_compiler_version ${CMAKE_CXX_COMPILER_VERSION})
-    set(_compiler_id ${CMAKE_CXX_COMPILER_ID})
-  endif()
-  set(WATCOM16)
-  set(WATCOM17)
-  set(WATCOM18)
-  set(WATCOM19)
-  if("${_compiler_id}" STREQUAL "OpenWatcom")
-    if("${_compiler_version}" VERSION_LESS 1.7)
-      set(WATCOM16 1)
-    endif()
-    if("${_compiler_version}" VERSION_EQUAL 1.7)
-      set(WATCOM17 1)
-    endif()
-    if("${_compiler_version}" VERSION_EQUAL 1.8)
-      set(WATCOM18 1)
-    endif()
-    if("${_compiler_version}" VERSION_EQUAL 1.9)
-      set(WATCOM19 1)
-    endif()
-  endif()
-endif()
diff --git a/Modules/Platform/WindowsPaths.cmake b/Modules/Platform/WindowsPaths.cmake
index eafa8fa..71cc609 100644
--- a/Modules/Platform/WindowsPaths.cmake
+++ b/Modules/Platform/WindowsPaths.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # Block multiple inclusion because "CMakeCInformation.cmake" includes
 # "Platform/${CMAKE_SYSTEM_NAME}" even though the generic module
diff --git a/Modules/ProcessorCount.cmake b/Modules/ProcessorCount.cmake
index 2c5d5ae..772a615 100644
--- a/Modules/ProcessorCount.cmake
+++ b/Modules/ProcessorCount.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # ProcessorCount
 # --------------
@@ -41,19 +44,6 @@
 # instruction, but that again requires compiler support or compiling assembler
 # code.
 
-#=============================================================================
-# Copyright 2010-2011 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 function(ProcessorCount var)
   # Unknown:
   set(count 0)
diff --git a/Modules/Qt4ConfigDependentSettings.cmake b/Modules/Qt4ConfigDependentSettings.cmake
index 03fb844..e21ecf4 100644
--- a/Modules/Qt4ConfigDependentSettings.cmake
+++ b/Modules/Qt4ConfigDependentSettings.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Qt4ConfigDependentSettings
 # --------------------------
@@ -6,20 +9,6 @@
 #
 # This file is included by FindQt4.cmake, don't include it directly.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 ###############################################
 #
 #       configuration/system dependent settings
diff --git a/Modules/Qt4Macros.cmake b/Modules/Qt4Macros.cmake
index 3b0a6cc..0279d1c 100644
--- a/Modules/Qt4Macros.cmake
+++ b/Modules/Qt4Macros.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Qt4Macros
 # ---------
@@ -6,20 +9,6 @@
 #
 # This file is included by FindQt4.cmake, don't include it directly.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-
 ######################################
 #
 #       Macros for building Qt files
@@ -441,14 +430,14 @@ macro(QT4_CREATE_TRANSLATION _qm_files)
        set(_ts_pro ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${_ts_name}_lupdate.pro)
        set(_pro_srcs)
        foreach(_pro_src ${_my_sources})
-         set(_pro_srcs "${_pro_srcs} \\\n  \"${_pro_src}\"")
+         string(APPEND _pro_srcs " \\\n  \"${_pro_src}\"")
        endforeach()
        set(_pro_includes)
        get_directory_property(_inc_DIRS INCLUDE_DIRECTORIES)
        list(REMOVE_DUPLICATES _inc_DIRS)
        foreach(_pro_include ${_inc_DIRS})
          get_filename_component(_abs_include "${_pro_include}" ABSOLUTE)
-         set(_pro_includes "${_pro_includes} \\\n  \"${_abs_include}\"")
+         string(APPEND _pro_includes " \\\n  \"${_abs_include}\"")
        endforeach()
        file(WRITE ${_ts_pro} "SOURCES =${_pro_srcs}\nINCLUDEPATH =${_pro_includes}\n")
      endif()
diff --git a/Modules/SelectLibraryConfigurations.cmake b/Modules/SelectLibraryConfigurations.cmake
index d710856..dce6f99 100644
--- a/Modules/SelectLibraryConfigurations.cmake
+++ b/Modules/SelectLibraryConfigurations.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # SelectLibraryConfigurations
 # ---------------------------
@@ -24,20 +27,6 @@
 # take only the release value, or the debug value if the release one is
 # not set.
 
-#=============================================================================
-# Copyright 2009 Will Dicharry <wdicharry at stellarscience.com>
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # This macro was adapted from the FindQt4 CMake module and is maintained by Will
 # Dicharry <wdicharry at stellarscience.com>.
 
diff --git a/Modules/SquishTestScript.cmake b/Modules/SquishTestScript.cmake
index d648749..cfdfaec 100644
--- a/Modules/SquishTestScript.cmake
+++ b/Modules/SquishTestScript.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # SquishTestScript
 # ----------------
@@ -14,19 +17,6 @@
 # and finally stops the squish server.  If any of these steps fail
 # (including if the tests do not pass) then a fatal error is raised.
 
-#=============================================================================
-# Copyright 2008-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # print out the variable that we are using
 message(STATUS "squish_aut='${squish_aut}'")
 message(STATUS "squish_aut_dir='${squish_aut_dir}'")
diff --git a/Modules/SystemInformation.cmake b/Modules/SystemInformation.cmake
index fa85071..5ecc39a 100644
--- a/Modules/SystemInformation.cmake
+++ b/Modules/SystemInformation.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 cmake_minimum_required(VERSION ${CMAKE_VERSION})
 project(DumpInformation)
diff --git a/Modules/TestBigEndian.cmake b/Modules/TestBigEndian.cmake
index fdc3adb..085be22 100644
--- a/Modules/TestBigEndian.cmake
+++ b/Modules/TestBigEndian.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestBigEndian
 # -------------
@@ -11,19 +14,6 @@
 #   TEST_BIG_ENDIAN(VARIABLE)
 #   VARIABLE - variable to store the result to
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(TEST_BIG_ENDIAN VARIABLE)
   if(NOT DEFINED HAVE_${VARIABLE})
     message(STATUS "Check if the system is big endian")
diff --git a/Modules/TestCXXAcceptsFlag.cmake b/Modules/TestCXXAcceptsFlag.cmake
index c814187..10019ec 100644
--- a/Modules/TestCXXAcceptsFlag.cmake
+++ b/Modules/TestCXXAcceptsFlag.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestCXXAcceptsFlag
 # ------------------
@@ -15,19 +18,6 @@
 # ``<variable>``
 #  variable to store the result
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 macro(CHECK_CXX_ACCEPTS_FLAG FLAGS  VARIABLE)
   if(NOT DEFINED ${VARIABLE})
     message(STATUS "Checking to see if CXX compiler accepts flag ${FLAGS}")
diff --git a/Modules/TestForANSIForScope.cmake b/Modules/TestForANSIForScope.cmake
index 78fff9f..7d2aad6 100644
--- a/Modules/TestForANSIForScope.cmake
+++ b/Modules/TestForANSIForScope.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestForANSIForScope
 # -------------------
@@ -11,19 +14,6 @@
 #
 #   CMAKE_NO_ANSI_FOR_SCOPE - holds result
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT DEFINED CMAKE_ANSI_FOR_SCOPE)
   message(STATUS "Check for ANSI scope")
   try_compile(CMAKE_ANSI_FOR_SCOPE  ${CMAKE_BINARY_DIR}
diff --git a/Modules/TestForANSIStreamHeaders.cmake b/Modules/TestForANSIStreamHeaders.cmake
index c13000b..e890c67 100644
--- a/Modules/TestForANSIStreamHeaders.cmake
+++ b/Modules/TestForANSIStreamHeaders.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestForANSIStreamHeaders
 # ------------------------
@@ -11,19 +14,6 @@
 #
 #   CMAKE_NO_ANSI_STREAM_HEADERS - defined by the results
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CheckIncludeFileCXX.cmake)
 
 if(NOT CMAKE_NO_ANSI_STREAM_HEADERS)
diff --git a/Modules/TestForSSTREAM.cmake b/Modules/TestForSSTREAM.cmake
index fe18ea2..0bfbfbb 100644
--- a/Modules/TestForSSTREAM.cmake
+++ b/Modules/TestForSSTREAM.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestForSSTREAM
 # --------------
@@ -10,19 +13,6 @@
 #
 #   CMAKE_NO_ANSI_STRING_STREAM - defined by the results
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT DEFINED CMAKE_HAS_ANSI_STRING_STREAM)
   message(STATUS "Check for sstream")
   try_compile(CMAKE_HAS_ANSI_STRING_STREAM  ${CMAKE_BINARY_DIR}
diff --git a/Modules/TestForSTDNamespace.cmake b/Modules/TestForSTDNamespace.cmake
index 0d90774..3ae80c7 100644
--- a/Modules/TestForSTDNamespace.cmake
+++ b/Modules/TestForSTDNamespace.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # TestForSTDNamespace
 # -------------------
@@ -10,19 +13,6 @@
 #
 #   CMAKE_NO_STD_NAMESPACE - defined by the results
 
-#=============================================================================
-# Copyright 2002-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if(NOT DEFINED CMAKE_STD_NAMESPACE)
   message(STATUS "Check for STD namespace")
   try_compile(CMAKE_STD_NAMESPACE  ${CMAKE_BINARY_DIR}
diff --git a/Modules/UseEcos.cmake b/Modules/UseEcos.cmake
index 3bd92ca..be1dfd1 100644
--- a/Modules/UseEcos.cmake
+++ b/Modules/UseEcos.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseEcos
 # -------
@@ -25,19 +28,6 @@
 #
 #   ECOS_ADD_TARGET_LIB
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # first check that ecosconfig is available
 find_program(ECOSCONFIG_EXECUTABLE NAMES ecosconfig)
 if(NOT ECOSCONFIG_EXECUTABLE)
diff --git a/Modules/UseJava.cmake b/Modules/UseJava.cmake
index 7b3416e..6b34c8f 100644
--- a/Modules/UseJava.cmake
+++ b/Modules/UseJava.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseJava
 # -------
@@ -217,6 +220,19 @@
 # This command installs the TARGET_NAME files to the given DESTINATION.
 # It should be called in the same scope as add_jar() or it will fail.
 #
+# Target Properties:
+#
+# ::
+#
+#    The install_jar() function sets the INSTALL_DESTINATION target property
+#    on jars so installed. This property holds the DESTINATION as described
+#    above, and is used by install_jar_exports(). You can get this property
+#    with the
+#       get_property(TARGET <target_name> PROPERTY INSTALL_DESTINATION)
+#    command.
+#
+#
+#
 # ::
 #
 #  install_jni_symlink(target_name destination)
@@ -228,6 +244,24 @@
 #
 # ::
 #
+#  install_jar_exports(TARGETS jar1 [jar2 ...]
+#                      FILE export_filename
+#                      DESTINATION destination [COMPONENT component])
+#
+# This command installs a target export file export_filename for the named jar
+# targets to the given DESTINATION. Its function is similar to that of
+# install(EXPORTS).
+#
+# ::
+#
+#  export_jars(TARGETS jar1 [jar2 ...]
+#              FILE export_filename)
+#
+# This command writes a target export file export_filename for the named jar
+# targets. Its function is similar to that of export().
+#
+# ::
+#
 #  create_javadoc(<VAR>
 #                 PACKAGES pkg1 [pkg2 ...]
 #                 [SOURCEPATH <sourcepath>]
@@ -369,21 +403,6 @@
 #    Sets the directory where the header files will be generated. Same behavior as option
 #    '-d' of javah tool. If not specified, ${CMAKE_CURRENT_BINARY_DIR} is used as output directory.
 
-#=============================================================================
-# Copyright 2013 OpenGamma Ltd. <graham at opengamma.com>
-# Copyright 2010-2011 Andreas schneider <asn at redhat.com>
-# Copyright 2010-2013 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 
 function (__java_copy_file src dest comment)
@@ -396,7 +415,29 @@ function (__java_copy_file src dest comment)
         COMMENT ${comment})
 endfunction ()
 
+function(__java_lcat VAR)
+    foreach(_line ${ARGN})
+        set(${VAR} "${${VAR}}${_line}\n")
+    endforeach()
+
+    set(${VAR} "${${VAR}}" PARENT_SCOPE)
+endfunction()
+
+function(__java_export_jar VAR TARGET PATH)
+    get_target_property(_jarpath ${TARGET} JAR_FILE)
+    get_filename_component(_jarname ${_jarpath} NAME)
+    __java_lcat(${VAR}
+      "# Create imported target ${TARGET}"
+      "add_custom_target(${TARGET})"
+      "set_target_properties(${TARGET} PROPERTIES"
+      "  JAR_FILE \"${PATH}/${_jarname}\")"
+      ""
+    )
+    set(${VAR} "${${VAR}}" PARENT_SCOPE)
+endfunction()
+
 # define helper scripts
+set(_JAVA_EXPORT_TARGETS_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/javaTargets.cmake.in)
 set(_JAVA_CLASS_FILELIST_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/UseJavaClassFilelist.cmake)
 set(_JAVA_SYMLINK_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/UseJavaSymlinks.cmake)
 
@@ -435,6 +476,8 @@ function(add_jar _TARGET_NAME)
 
     if (NOT DEFINED _add_jar_OUTPUT_DIR)
         set(_add_jar_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR})
+    else()
+        get_filename_component(_add_jar_OUTPUT_DIR ${_add_jar_OUTPUT_DIR} ABSOLUTE)
     endif()
 
     if (_add_jar_ENTRY_POINT)
@@ -467,7 +510,7 @@ function(add_jar _TARGET_NAME)
     endif()
 
     foreach (JAVA_INCLUDE_DIR ${CMAKE_JAVA_INCLUDE_PATH})
-       set(CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_PATH_FINAL}${CMAKE_JAVA_INCLUDE_FLAG_SEP}${JAVA_INCLUDE_DIR}")
+       string(APPEND CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_FLAG_SEP}${JAVA_INCLUDE_DIR}")
     endforeach()
 
     set(CMAKE_JAVA_CLASS_OUTPUT_PATH "${_add_jar_OUTPUT_DIR}${CMAKE_FILES_DIRECTORY}/${_TARGET_NAME}.dir")
@@ -539,7 +582,7 @@ function(add_jar _TARGET_NAME)
         if (TARGET ${_JAVA_INCLUDE_JAR})
             get_target_property(_JAVA_JAR_PATH ${_JAVA_INCLUDE_JAR} JAR_FILE)
             if (_JAVA_JAR_PATH)
-                set(CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_PATH_FINAL}${CMAKE_JAVA_INCLUDE_FLAG_SEP}${_JAVA_JAR_PATH}")
+                string(APPEND CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_FLAG_SEP}${_JAVA_JAR_PATH}")
                 list(APPEND CMAKE_JAVA_INCLUDE_PATH ${_JAVA_JAR_PATH})
                 list(APPEND _JAVA_DEPENDS ${_JAVA_INCLUDE_JAR})
                 list(APPEND _JAVA_COMPILE_DEPENDS ${_JAVA_INCLUDE_JAR})
@@ -547,18 +590,13 @@ function(add_jar _TARGET_NAME)
                 message(SEND_ERROR "add_jar: INCLUDE_JARS target ${_JAVA_INCLUDE_JAR} is not a jar")
             endif ()
         else ()
-            set(CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_PATH_FINAL}${CMAKE_JAVA_INCLUDE_FLAG_SEP}${_JAVA_INCLUDE_JAR}")
+            string(APPEND CMAKE_JAVA_INCLUDE_PATH_FINAL "${CMAKE_JAVA_INCLUDE_FLAG_SEP}${_JAVA_INCLUDE_JAR}")
             list(APPEND CMAKE_JAVA_INCLUDE_PATH "${_JAVA_INCLUDE_JAR}")
             list(APPEND _JAVA_DEPENDS "${_JAVA_INCLUDE_JAR}")
             list(APPEND _JAVA_COMPILE_DEPENDS "${_JAVA_INCLUDE_JAR}")
         endif ()
     endforeach()
 
-    # create an empty java_class_filelist
-    if (NOT EXISTS ${CMAKE_JAVA_CLASS_OUTPUT_PATH}/java_class_filelist)
-        file(WRITE ${CMAKE_JAVA_CLASS_OUTPUT_PATH}/java_class_filelist "")
-    endif()
-
     if (_JAVA_COMPILE_FILES OR _JAVA_COMPILE_FILELISTS)
         set (_JAVA_SOURCES_FILELISTS)
 
@@ -598,6 +636,11 @@ function(add_jar _TARGET_NAME)
             DEPENDS ${CMAKE_JAVA_CLASS_OUTPUT_PATH}/java_compiled_${_TARGET_NAME}
             WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
         )
+    else ()
+        # create an empty java_class_filelist
+        if (NOT EXISTS ${CMAKE_JAVA_CLASS_OUTPUT_PATH}/java_class_filelist)
+            file(WRITE ${CMAKE_JAVA_CLASS_OUTPUT_PATH}/java_class_filelist "")
+        endif()
     endif ()
 
     # create the jar file
@@ -716,6 +759,13 @@ function(INSTALL_JAR _TARGET_NAME)
         PROPERTY
             INSTALL_FILES
     )
+    set_property(
+        TARGET
+            ${_TARGET_NAME}
+        PROPERTY
+            INSTALL_DESTINATION
+            ${_DESTINATION}
+    )
 
     if (__FILES)
         install(
@@ -1288,3 +1338,94 @@ function (create_javah)
       set (${_create_javah_GENERATED_FILES} ${_output_files} PARENT_SCOPE)
     endif()
 endfunction()
+
+function(export_jars)
+    # Parse and validate arguments
+    cmake_parse_arguments(_export_jars
+      ""
+      "FILE"
+      "TARGETS"
+      ${ARGN}
+    )
+    if (NOT _export_jars_FILE)
+      message(SEND_ERROR "export_jars: FILE must be specified.")
+    endif()
+    if (NOT _export_jars_TARGETS)
+      message(SEND_ERROR "export_jars: TARGETS must be specified.")
+    endif()
+
+    # Set content of generated exports file
+    string(REPLACE ";" " " __targets__ "${_export_jars_TARGETS}")
+    set(__targetdefs__ "")
+    foreach(_target ${_export_jars_TARGETS})
+        get_target_property(_jarpath ${_target} JAR_FILE)
+        get_filename_component(_jarpath ${_jarpath} PATH)
+        __java_export_jar(__targetdefs__ ${_target} "${_jarpath}")
+    endforeach()
+
+    # Generate exports file
+    configure_file(
+      ${_JAVA_EXPORT_TARGETS_SCRIPT}
+      ${_export_jars_FILE}
+      @ONLY
+    )
+endfunction()
+
+function(install_jar_exports)
+    # Parse and validate arguments
+    cmake_parse_arguments(_install_jar_exports
+      ""
+      "FILE;DESTINATION;COMPONENT"
+      "TARGETS"
+      ${ARGN}
+    )
+    if (NOT _install_jar_exports_FILE)
+      message(SEND_ERROR "install_jar_exports: FILE must be specified.")
+    endif()
+    if (NOT _install_jar_exports_DESTINATION)
+      message(SEND_ERROR "install_jar_exports: DESTINATION must be specified.")
+    endif()
+    if (NOT _install_jar_exports_TARGETS)
+      message(SEND_ERROR "install_jar_exports: TARGETS must be specified.")
+    endif()
+
+    if (_install_jar_exports_COMPONENT)
+      set (_COMPONENT COMPONENT ${_install_jar_exports_COMPONENT})
+    endif()
+
+    # Determine relative path from installed export file to install prefix
+    if(IS_ABSOLUTE ${_install_jar_exports_DESTINATION})
+      file(RELATIVE_PATH _relpath
+        ${_install_jar_exports_DESTINATION}
+        ${CMAKE_INSTALL_PREFIX}
+      )
+    else()
+      file(RELATIVE_PATH _relpath
+        ${CMAKE_INSTALL_PREFIX}/${_install_jar_exports_DESTINATION}
+        ${CMAKE_INSTALL_PREFIX}
+      )
+    endif()
+
+    # Set up unique location for generated exports file
+    string(SHA256 _hash "${_install_jar_exports_DESTINATION}")
+    set(_tmpdir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/JavaExports/${_hash})
+
+    # Set content of generated exports file
+    string(REPLACE ";" " " __targets__ "${_install_jar_exports_TARGETS}")
+    set(__targetdefs__ "set(_prefix \${CMAKE_CURRENT_LIST_DIR}/${_relpath})\n\n")
+    foreach(_target ${_install_jar_exports_TARGETS})
+        get_target_property(_dir ${_target} INSTALL_DESTINATION)
+        __java_export_jar(__targetdefs__ ${_target} "\${_prefix}/${_dir}")
+    endforeach()
+    __java_lcat(__targetdefs__ "\nunset(_prefix)")
+
+    # Generate and install exports file
+    configure_file(
+      ${_JAVA_EXPORT_TARGETS_SCRIPT}
+      ${_tmpdir}/${_install_jar_exports_FILE}
+      @ONLY
+    )
+    install(FILES ${_tmpdir}/${_install_jar_exports_FILE}
+            DESTINATION ${_install_jar_exports_DESTINATION}
+            ${_COMPONENT})
+endfunction()
diff --git a/Modules/UseJavaClassFilelist.cmake b/Modules/UseJavaClassFilelist.cmake
index e8e6f01..c2f9afa 100644
--- a/Modules/UseJavaClassFilelist.cmake
+++ b/Modules/UseJavaClassFilelist.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseJavaClassFilelist
 # --------------------
@@ -10,19 +13,6 @@
 # a jar file.  This avoids including cmake files which get created in
 # the binary directory.
 
-#=============================================================================
-# Copyright 2010-2011 Andreas schneider <asn at redhat.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (CMAKE_JAVA_CLASS_OUTPUT_PATH)
     if (EXISTS "${CMAKE_JAVA_CLASS_OUTPUT_PATH}")
 
diff --git a/Modules/UseJavaSymlinks.cmake b/Modules/UseJavaSymlinks.cmake
index 90ffdd5..358b9ef 100644
--- a/Modules/UseJavaSymlinks.cmake
+++ b/Modules/UseJavaSymlinks.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseJavaSymlinks
 # ---------------
@@ -8,19 +11,6 @@
 #
 # Helper script for UseJava.cmake
 
-#=============================================================================
-# Copyright 2010-2011 Andreas schneider <asn at redhat.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 if (UNIX AND _JAVA_TARGET_OUTPUT_LINK)
     if (_JAVA_TARGET_OUTPUT_NAME)
         find_program(LN_EXECUTABLE
diff --git a/Modules/UsePkgConfig.cmake b/Modules/UsePkgConfig.cmake
index 6a38502..28618eb 100644
--- a/Modules/UsePkgConfig.cmake
+++ b/Modules/UsePkgConfig.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UsePkgConfig
 # ------------
@@ -17,19 +20,6 @@
 # will be empty when the function returns, otherwise they will contain
 # the respective information
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 find_program(PKGCONFIG_EXECUTABLE NAMES pkg-config )
 
 macro(PKGCONFIG _package _include_DIR _link_DIR _link_FLAGS _cflags)
diff --git a/Modules/UseQt4.cmake b/Modules/UseQt4.cmake
index cba22af..c8eab77 100644
--- a/Modules/UseQt4.cmake
+++ b/Modules/UseQt4.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseQt4
 # ------
@@ -8,19 +11,6 @@
 # already been loaded.  See FindQt.cmake for information on how to load
 # Qt 4 into your CMake project.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 add_definitions(${QT_DEFINITIONS})
 set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<NOT:$<CONFIG:Debug>>:QT_NO_DEBUG>)
 
diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake
index d757f65..d242f87 100644
--- a/Modules/UseSWIG.cmake
+++ b/Modules/UseSWIG.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UseSWIG
 # -------
@@ -44,20 +47,6 @@
 #    set_source_files_properties( ${swig_generated_file_fullname}
 #                                 PROPERTIES COMPILE_FLAGS "-bla")
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2009 Mathieu Malaterre <mathieu.malaterre at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 set(SWIG_CXX_EXTENSION "cxx")
 set(SWIG_EXTRA_LIBRARIES "")
 
@@ -163,15 +152,15 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
     "${swig_outdir}/${swig_source_file_name_we}")
   # add the language into the name of the file (i.e. TCL_wrap)
   # this allows for the same .i file to be wrapped into different languages
-  set(swig_generated_file_fullname
-    "${swig_generated_file_fullname}${SWIG_MODULE_${name}_LANGUAGE}_wrap")
+  string(APPEND swig_generated_file_fullname
+    "${SWIG_MODULE_${name}_LANGUAGE}_wrap")
 
   if(swig_source_file_cplusplus)
-    set(swig_generated_file_fullname
-      "${swig_generated_file_fullname}.${SWIG_CXX_EXTENSION}")
+    string(APPEND swig_generated_file_fullname
+      ".${SWIG_CXX_EXTENSION}")
   else()
-    set(swig_generated_file_fullname
-      "${swig_generated_file_fullname}.c")
+    string(APPEND swig_generated_file_fullname
+      ".c")
   endif()
 
   #message("Full path to source file: ${swig_source_file_fullname}")
diff --git a/Modules/Use_wxWindows.cmake b/Modules/Use_wxWindows.cmake
index d3025ac..bd8cc01 100644
--- a/Modules/Use_wxWindows.cmake
+++ b/Modules/Use_wxWindows.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # Use_wxWindows
 # -------------
@@ -28,20 +31,6 @@
 #
 #    *before* you include this file.
 
-#=============================================================================
-# Copyright 2003-2009 Kitware, Inc.
-# Copyright 2003      Jan Woetzel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # -----------------------------------------------------
 # 16.Feb.2004: changed INCLUDE to FIND_PACKAGE to read from users own non-system CMAKE_MODULE_PATH (Jan Woetzel JW)
 # 07/2006: rewrite as FindwxWidgets.cmake, kept for backward compatibility JW
@@ -68,7 +57,7 @@ if(WXWINDOWS_FOUND)
     link_libraries(${WXWINDOWS_LIBRARIES})
   endif()
   if (CMAKE_WXWINDOWS_CXX_FLAGS)
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_WXWINDOWS_CXX_FLAGS}")
+    string(APPEND CMAKE_CXX_FLAGS " ${CMAKE_WXWINDOWS_CXX_FLAGS}")
   endif()
   if(WXWINDOWS_DEFINITIONS)
     add_definitions(${WXWINDOWS_DEFINITIONS})
diff --git a/Modules/UsewxWidgets.cmake b/Modules/UsewxWidgets.cmake
index b3633a6..a50d03d 100644
--- a/Modules/UsewxWidgets.cmake
+++ b/Modules/UsewxWidgets.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # UsewxWidgets
 # ------------
@@ -34,20 +37,6 @@
 #
 #   Jan Woetzel <jw -at- mip.informatik.uni-kiel.de>
 
-#=============================================================================
-# Copyright 2004-2009 Kitware, Inc.
-# Copyright 2006      Jan Woetzel
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # debug message and logging.
 # comment these out for distribution
 if    (NOT LOGFILE )
@@ -90,7 +79,7 @@ if   (wxWidgets_FOUND)
   if   (wxWidgets_CXX_FLAGS)
     # Flags are expected to be a string here, not a list.
     string(REPLACE ";" " " wxWidgets_CXX_FLAGS_str "${wxWidgets_CXX_FLAGS}")
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${wxWidgets_CXX_FLAGS_str}")
+    string(APPEND CMAKE_CXX_FLAGS " ${wxWidgets_CXX_FLAGS_str}")
     MSG("wxWidgets_CXX_FLAGS=${wxWidgets_CXX_FLAGS_str}")
     unset(wxWidgets_CXX_FLAGS_str)
   endif()
diff --git a/Modules/VTKCompatibility.cmake b/Modules/VTKCompatibility.cmake
index b33bf2e..1b0815e 100644
--- a/Modules/VTKCompatibility.cmake
+++ b/Modules/VTKCompatibility.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2005-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(APPLE)
   set(CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
diff --git a/Modules/WriteBasicConfigVersionFile.cmake b/Modules/WriteBasicConfigVersionFile.cmake
index bf55eb9..20c769e 100644
--- a/Modules/WriteBasicConfigVersionFile.cmake
+++ b/Modules/WriteBasicConfigVersionFile.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # WriteBasicConfigVersionFile
 # ---------------------------
@@ -15,20 +18,6 @@
 #
 # Deprecated, see WRITE_BASIC_PACKAGE_VERSION_FILE(), it is identical.
 
-#=============================================================================
-# Copyright 2008-2011 Alexander Neundorf, <neundorf at kde.org>
-# Copyright 2004-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(CMakeParseArguments)
 
 function(WRITE_BASIC_CONFIG_VERSION_FILE _filename)
diff --git a/Modules/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake
index 2669a84..82e8fba 100644
--- a/Modules/WriteCompilerDetectionHeader.cmake
+++ b/Modules/WriteCompilerDetectionHeader.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #.rst:
 # WriteCompilerDetectionHeader
 # ----------------------------
@@ -212,19 +215,6 @@
 #       CompatSupport_DEPRECATED=
 #   )
 
-#=============================================================================
-# Copyright 2014 Stephen Kelly <steveire at gmail.com>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeCompilerIdDetection.cmake)
 
@@ -282,9 +272,9 @@ function(write_compiler_detection_header
   set(_min_version 3.1.0) # Version which introduced this function
   if (_WCD_VERSION VERSION_LESS _min_version)
     set(err "VERSION compatibility for write_compiler_detection_header is set to ${_WCD_VERSION}, which is too low.")
-    set(err "${err}  It must be set to at least ${_min_version}.  ")
-    set(err "${err}  Either set the VERSION parameter to the write_compiler_detection_header function, or update")
-    set(err "${err} your minimum required CMake version with the cmake_minimum_required command.")
+    string(APPEND err "  It must be set to at least ${_min_version}.  ")
+    string(APPEND err "  Either set the VERSION parameter to the write_compiler_detection_header function, or update")
+    string(APPEND err " your minimum required CMake version with the cmake_minimum_required command.")
     message(FATAL_ERROR "${err}")
   endif()
 
@@ -349,11 +339,11 @@ function(write_compiler_detection_header
 ")
 
   if (_WCD_PROLOG)
-    set(file_content "${file_content}\n${_WCD_PROLOG}\n")
+    string(APPEND file_content "\n${_WCD_PROLOG}\n")
   endif()
 
   if (_need_hex_conversion)
-    set(file_content "${file_content}
+    string(APPEND file_content "
 #define ${prefix_arg}_DEC(X) (X)
 #define ${prefix_arg}_HEX(X) ( \\
     ((X)>>28 & 0xF) * 10000000 + \\
@@ -406,24 +396,24 @@ function(write_compiler_detection_header
     endforeach()
 
     if(_lang STREQUAL CXX)
-      set(file_content "${file_content}\n#ifdef __cplusplus\n")
+      string(APPEND file_content "\n#ifdef __cplusplus\n")
     else()
-      set(file_content "${file_content}\n#ifndef __cplusplus\n")
+      string(APPEND file_content "\n#ifndef __cplusplus\n")
     endif()
 
     compiler_id_detection(ID_CONTENT ${_lang} PREFIX ${prefix_arg}_
       ID_DEFINE
     )
 
-    set(file_content "${file_content}${ID_CONTENT}\n")
+    string(APPEND file_content "${ID_CONTENT}\n")
 
     set(pp_if "if")
     foreach(compiler ${target_compilers})
-      set(file_content "${file_content}\n#  ${pp_if} ${prefix_arg}_COMPILER_IS_${compiler}\n")
+      string(APPEND file_content "\n#  ${pp_if} ${prefix_arg}_COMPILER_IS_${compiler}\n")
 
       if(_WCD_OUTPUT_FILES_VAR)
         set(compile_file_name "${_WCD_OUTPUT_DIR}${prefix_arg}_COMPILER_INFO_${compiler}_${_lang}.h")
-        set(file_content "${file_content}\n#    include \"${compile_file_name}\"\n")
+        string(APPEND file_content "\n#    include \"${compile_file_name}\"\n")
       endif()
 
       if(_WCD_OUTPUT_FILES_VAR)
@@ -466,7 +456,7 @@ function(write_compiler_detection_header
       endforeach()
     endforeach()
     if(pp_if STREQUAL "elif")
-      set(file_content "${file_content}
+      string(APPEND file_content "
 #  else
 #    error Unsupported compiler
 #  endif\n")
@@ -477,7 +467,7 @@ function(write_compiler_detection_header
       set(def_name ${prefix_arg}_${feature_PP})
       if (feature STREQUAL c_restrict)
         set(def_value "${prefix_arg}_RESTRICT")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} restrict
 #  else
@@ -487,7 +477,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_constexpr)
         set(def_value "${prefix_arg}_CONSTEXPR")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} constexpr
 #  else
@@ -497,7 +487,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_final)
         set(def_value "${prefix_arg}_FINAL")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} final
 #  else
@@ -507,7 +497,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_override)
         set(def_value "${prefix_arg}_OVERRIDE")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} override
 #  else
@@ -521,11 +511,11 @@ function(write_compiler_detection_header
         set(static_assert_struct "template<bool> struct ${prefix_arg}StaticAssert;\ntemplate<> struct ${prefix_arg}StaticAssert<true>{};\n")
         set(def_standard "#    define ${def_value} static_assert(X, #X)\n#    define ${def_value_msg} static_assert(X, MSG)")
         set(def_alternative "${static_assert_struct}#    define ${def_value} sizeof(${prefix_arg}StaticAssert<X>)\n#    define ${def_value_msg} sizeof(${prefix_arg}StaticAssert<X>)")
-        set(file_content "${file_content}#  if ${def_name}\n${def_standard}\n#  else\n${def_alternative}\n#  endif\n\n")
+        string(APPEND file_content "#  if ${def_name}\n${def_standard}\n#  else\n${def_alternative}\n#  endif\n\n")
       endif()
       if (feature STREQUAL cxx_alignas)
         set(def_value "${prefix_arg}_ALIGNAS(X)")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} alignas(X)
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
@@ -539,7 +529,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_alignof)
         set(def_value "${prefix_arg}_ALIGNOF(X)")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} alignof(X)
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
@@ -551,7 +541,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_deleted_functions)
         set(def_value "${prefix_arg}_DELETED_FUNCTION")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} = delete
 #  else
@@ -561,7 +551,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_extern_templates)
         set(def_value "${prefix_arg}_EXTERN_TEMPLATE")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} extern
 #  else
@@ -571,7 +561,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_noexcept)
         set(def_value "${prefix_arg}_NOEXCEPT")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} noexcept
 #    define ${def_value}_EXPR(X) noexcept(X)
@@ -583,7 +573,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_nullptr)
         set(def_value "${prefix_arg}_NULLPTR")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} nullptr
 #  else
@@ -593,7 +583,7 @@ function(write_compiler_detection_header
       endif()
       if (feature STREQUAL cxx_thread_local)
         set(def_value "${prefix_arg}_THREAD_LOCAL")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  if ${def_name}
 #    define ${def_value} thread_local
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
@@ -608,7 +598,7 @@ function(write_compiler_detection_header
       if (feature STREQUAL cxx_attribute_deprecated)
         set(def_name ${prefix_arg}_${feature_PP})
         set(def_value "${prefix_arg}_DEPRECATED")
-        set(file_content "${file_content}
+        string(APPEND file_content "
 #  ifndef ${def_value}
 #    if ${def_name}
 #      define ${def_value} [[deprecated]]
@@ -628,7 +618,7 @@ function(write_compiler_detection_header
       endif()
     endforeach()
 
-    set(file_content "${file_content}#endif\n")
+    string(APPEND file_content "#endif\n")
 
   endforeach()
 
@@ -637,7 +627,7 @@ function(write_compiler_detection_header
       foreach(_lang ${_langs})
         if(compiler_file_content_${compiler}_${_lang})
           set(CMAKE_CONFIGURABLE_FILE_CONTENT "${compiler_file_content_}")
-          set(CMAKE_CONFIGURABLE_FILE_CONTENT "${CMAKE_CONFIGURABLE_FILE_CONTENT}${compiler_file_content_${compiler}_${_lang}}")
+          string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "${compiler_file_content_${compiler}_${_lang}}")
 
           set(compile_file_name "${_WCD_OUTPUT_DIR}${prefix_arg}_COMPILER_INFO_${compiler}_${_lang}.h")
           set(full_path "${main_file_dir}/${compile_file_name}")
@@ -653,9 +643,9 @@ function(write_compiler_detection_header
   endif()
 
   if (_WCD_EPILOG)
-    set(file_content "${file_content}\n${_WCD_EPILOG}\n")
+    string(APPEND file_content "\n${_WCD_EPILOG}\n")
   endif()
-  set(file_content "${file_content}\n#endif")
+  string(APPEND file_content "\n#endif")
 
   set(CMAKE_CONFIGURABLE_FILE_CONTENT ${file_content})
   configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
diff --git a/Modules/ecos_clean.cmake b/Modules/ecos_clean.cmake
index 37a1f93..21126f6 100644
--- a/Modules/ecos_clean.cmake
+++ b/Modules/ecos_clean.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2007-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 file(GLOB _files ${ECOS_DIR}/*)
 
diff --git a/Modules/exportheader.cmake.in b/Modules/exportheader.cmake.in
index 7cfbcbd..9dd75bf 100644
--- a/Modules/exportheader.cmake.in
+++ b/Modules/exportheader.cmake.in
@@ -38,5 +38,5 @@
 #    define @NO_DEPRECATED_MACRO_NAME@
 #  endif
 #endif
-
+ at CUSTOM_CONTENT@
 #endif
diff --git a/Modules/javaTargets.cmake.in b/Modules/javaTargets.cmake.in
new file mode 100644
index 0000000..c5f9c78
--- /dev/null
+++ b/Modules/javaTargets.cmake.in
@@ -0,0 +1,39 @@
+cmake_minimum_required(VERSION 2.8)
+cmake_policy(PUSH)
+cmake_policy(VERSION 2.8)
+
+#----------------------------------------------------------------
+# Generated CMake Java target import file.
+#----------------------------------------------------------------
+
+# Protect against multiple inclusion, which would fail when already imported targets are added once more.
+set(_targetsDefined)
+set(_targetsNotDefined)
+set(_expectedTargets)
+foreach(_expectedTarget @__targets__@)
+  list(APPEND _expectedTargets ${_expectedTarget})
+  if(TARGET ${_expectedTarget})
+    list(APPEND _targetsDefined ${_expectedTarget})
+  else()
+    list(APPEND _targetsNotDefined ${_expectedTarget})
+  endif()
+endforeach()
+if("%${_targetsDefined}" STREQUAL "%${_expectedTargets}")
+  unset(_targetsDefined)
+  unset(_targetsNotDefined)
+  unset(_expectedTargets)
+  cmake_policy(POP)
+  return()
+endif()
+if(NOT "${_targetsDefined}" STREQUAL "")
+  message(FATAL_ERROR
+    "Some (but not all) targets in this export set were already defined.\n"
+    "Targets Defined: ${_targetsDefined}\n"
+    "Targets not yet defined: ${_targetsNotDefined}\n")
+endif()
+unset(_targetsDefined)
+unset(_targetsNotDefined)
+unset(_expectedTargets)
+
+ at __targetdefs__@
+cmake_policy(POP)
diff --git a/Modules/kde3uic.cmake b/Modules/kde3uic.cmake
index 4ad364b..b1f73d5 100644
--- a/Modules/kde3uic.cmake
+++ b/Modules/kde3uic.cmake
@@ -1,17 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 # used internally by KDE3Macros.cmake
 # neundorf at kde.org
diff --git a/Source/.cvsignore b/Source/.cvsignore
deleted file mode 100644
index 31e286c..0000000
--- a/Source/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-ccommand___Win32_Debug
-Debug
-cmake___Win32_Debug
-ctest___Win32_Debug
-CMakeSetup.map
diff --git a/Source/.gitattributes b/Source/.gitattributes
index bd25ea8..5002b2a 100644
--- a/Source/.gitattributes
+++ b/Source/.gitattributes
@@ -3,3 +3,5 @@ cm_sha2.*        whitespace=indent-with-non-tab
 
 # Preserve indentation style in generated code.
 cmListFileLexer.c       whitespace=-tab-in-indent,-indent-with-non-tab
+cmFortranLexer.cxx      whitespace=-tab-in-indent,-indent-with-non-tab
+cmFortranLexer.h        whitespace=-tab-in-indent,-indent-with-non-tab
diff --git a/Source/CMakeInstallDestinations.cmake b/Source/CMakeInstallDestinations.cmake
index 2f9d95a..023f6c0 100644
--- a/Source/CMakeInstallDestinations.cmake
+++ b/Source/CMakeInstallDestinations.cmake
@@ -1,27 +1,32 @@
 # Keep formatting here consistent with bootstrap script expectations.
 if(BEOS)
+  set(CMAKE_BIN_DIR_DEFAULT "bin") # HAIKU
   set(CMAKE_DATA_DIR_DEFAULT "share/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}") # HAIKU
   set(CMAKE_MAN_DIR_DEFAULT "documentation/man") # HAIKU
   set(CMAKE_DOC_DIR_DEFAULT "documentation/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}") # HAIKU
   set(CMAKE_XDGDATA_DIR_DEFAULT "share") # HAIKU
 elseif(CYGWIN)
+  set(CMAKE_BIN_DIR_DEFAULT "bin") # CYGWIN
   set(CMAKE_DATA_DIR_DEFAULT "share/cmake-${CMake_VERSION}") # CYGWIN
   set(CMAKE_DOC_DIR_DEFAULT "share/doc/cmake-${CMake_VERSION}") # CYGWIN
   set(CMAKE_MAN_DIR_DEFAULT "share/man") # CYGWIN
   set(CMAKE_XDGDATA_DIR_DEFAULT "share") # CYGWIN
 else()
+  set(CMAKE_BIN_DIR_DEFAULT "bin") # OTHER
   set(CMAKE_DATA_DIR_DEFAULT "share/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}") # OTHER
   set(CMAKE_DOC_DIR_DEFAULT "doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}") # OTHER
   set(CMAKE_MAN_DIR_DEFAULT "man") # OTHER
   set(CMAKE_XDGDATA_DIR_DEFAULT "share") # OTHER
 endif()
 
+set(CMAKE_BIN_DIR_DESC "bin")
 set(CMAKE_DATA_DIR_DESC "data")
 set(CMAKE_DOC_DIR_DESC "docs")
 set(CMAKE_MAN_DIR_DESC "man pages")
 set(CMAKE_XDGDATA_DIR_DESC "XDG specific files")
 
 foreach(v
+    CMAKE_BIN_DIR
     CMAKE_DATA_DIR
     CMAKE_DOC_DIR
     CMAKE_MAN_DIR
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index 3223831..ec49481 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 include(CheckIncludeFile)
 # Check if we can build support for ELF parsing.
 if(CMAKE_CXX_PLATFORM_ID MATCHES "OpenBSD")
@@ -45,9 +37,21 @@ endif()
 
 set(EXECUTABLE_OUTPUT_PATH ${CMake_BIN_DIR})
 
-# ensure Unicode friendly APIs are used on Windows
 if(WIN32)
+  # ensure Unicode friendly APIs are used on Windows
   add_definitions(-DUNICODE -D_UNICODE)
+
+  # minimize windows.h content
+  add_definitions(-DWIN32_LEAN_AND_MEAN)
+endif()
+
+# configure the .dox.in file
+if(CMake_BUILD_DEVELOPER_REFERENCE)
+  configure_file(
+    "${CMake_SOURCE_DIR}/Source/dir.dox.in"
+    "${CMake_BINARY_DIR}/Source/dir.dox"
+    @ONLY
+    )
 endif()
 
 # configure the .h file
@@ -154,6 +158,7 @@ endif()
 #
 set(SRCS
   cmArchiveWrite.cxx
+  cmBase32.cxx
   cmBootstrapCommands1.cxx
   cmBootstrapCommands2.cxx
   cmCacheManager.cxx
@@ -208,10 +213,14 @@ set(SRCS
   cmExprLexer.cxx
   cmExprParser.cxx
   cmExprParserHelper.cxx
+  cmExportBuildAndroidMKGenerator.h
+  cmExportBuildAndroidMKGenerator.cxx
   cmExportBuildFileGenerator.h
   cmExportBuildFileGenerator.cxx
   cmExportFileGenerator.h
   cmExportFileGenerator.cxx
+  cmExportInstallAndroidMKGenerator.h
+  cmExportInstallAndroidMKGenerator.cxx
   cmExportInstallFileGenerator.h
   cmExportInstallFileGenerator.cxx
   cmExportTryCompileFileGenerator.h
@@ -238,6 +247,8 @@ set(SRCS
   cmFileLockPool.h
   cmFileLockResult.cxx
   cmFileLockResult.h
+  cmFilePathUuid.cxx
+  cmFilePathUuid.h
   cmFileTimeComparison.cxx
   cmFileTimeComparison.h
   cmFortranLexer.cxx
@@ -305,6 +316,8 @@ set(SRCS
   cmMakefileExecutableTargetGenerator.cxx
   cmMakefileLibraryTargetGenerator.cxx
   cmMakefileUtilityTargetGenerator.cxx
+  cmMessenger.cxx
+  cmMessenger.h
   cmOSXBundleGenerator.cxx
   cmOSXBundleGenerator.h
   cmOutputConverter.cxx
@@ -364,6 +377,7 @@ set(SRCS
   cmake.cxx
   cmake.h
 
+  cm_auto_ptr.hxx
   cm_get_date.h
   cm_get_date.c
   cm_sha2.h
@@ -474,6 +488,8 @@ if (WIN32)
       cmGlobalVisualStudio12Generator.cxx
       cmGlobalVisualStudio14Generator.h
       cmGlobalVisualStudio14Generator.cxx
+      cmGlobalVisualStudio15Generator.h
+      cmGlobalVisualStudio15Generator.cxx
       cmGlobalVisualStudioGenerator.cxx
       cmGlobalVisualStudioGenerator.h
       cmIDEFlagTable.h
@@ -529,11 +545,14 @@ set(SRCS ${SRCS}
   cmNinjaUtilityTargetGenerator.h
   )
 
+# Temporary variable for tools targets
+set(_tools)
+
 if(WIN32 AND NOT CYGWIN)
   set_source_files_properties(cmcldeps.cxx PROPERTIES COMPILE_DEFINITIONS _WIN32_WINNT=0x0501)
   add_executable(cmcldeps cmcldeps.cxx ${MANIFEST_FILE})
+  list(APPEND _tools cmcldeps)
   target_link_libraries(cmcldeps CMakeLib)
-  install(TARGETS cmcldeps DESTINATION bin)
 endif()
 
 foreach(v CURL_CA_BUNDLE CURL_CA_PATH)
@@ -562,6 +581,7 @@ target_link_libraries(CMakeLib cmsys
   ${CMAKE_TAR_LIBRARIES} ${CMAKE_COMPRESS_LIBRARIES}
   ${CMAKE_CURL_LIBRARIES}
   ${CMAKE_JSONCPP_LIBRARIES}
+  ${CMAKE_LIBUV_LIBRARIES}
   ${CMake_KWIML_LIBRARIES}
   )
 
@@ -717,7 +737,9 @@ if(APPLE)
     CPack/cmCPackBundleGenerator.cxx
     CPack/cmCPackDragNDropGenerator.cxx
     CPack/cmCPackOSXX11Generator.cxx
+    CPack/cmCPackPKGGenerator.cxx
     CPack/cmCPackPackageMakerGenerator.cxx
+    CPack/cmCPackProductBuildGenerator.cxx
     )
 endif()
 
@@ -743,6 +765,7 @@ endif()
 
 if(APPLE)
   add_executable(cmakexbuild cmakexbuild.cxx)
+  list(APPEND _tools cmakexbuild)
   target_link_libraries(cmakexbuild CMakeLib)
   add_executable(OSXScriptLauncher
     CPack/OSXScriptLauncher.cxx)
@@ -752,14 +775,30 @@ endif()
 
 # Build CMake executable
 add_executable(cmake cmakemain.cxx cmcmd.cxx cmcmd.h ${MANIFEST_FILE})
+list(APPEND _tools cmake)
 target_link_libraries(cmake CMakeLib)
 
+if(CMake_ENABLE_SERVER_MODE)
+  add_library(CMakeServerLib
+    cmFileMonitor.cxx cmFileMonitor.h
+    cmServer.cxx cmServer.h
+    cmServerConnection.cxx cmServerConnection.h
+    cmServerProtocol.cxx cmServerProtocol.h
+    )
+  target_link_libraries(CMakeServerLib CMakeLib)
+  set_property(SOURCE cmcmd.cxx APPEND PROPERTY COMPILE_DEFINITIONS HAVE_SERVER_MODE=1)
+
+  target_link_libraries(cmake CMakeServerLib)
+endif()
+
 # Build CTest executable
 add_executable(ctest ctest.cxx ${MANIFEST_FILE})
+list(APPEND _tools ctest)
 target_link_libraries(ctest CTestLib)
 
 # Build CPack executable
 add_executable(cpack CPack/cpack.cxx ${MANIFEST_FILE})
+list(APPEND _tools cpack)
 target_link_libraries(cpack CPackLib)
 
 # Curses GUI
@@ -778,15 +817,12 @@ include (${CMake_SOURCE_DIR}/Source/LocalUserOptions.cmake OPTIONAL)
 
 # Install tools
 
-set(_tools cmake ctest cpack)
-
-if(APPLE)
-  list(APPEND _tools cmakexbuild)
-endif()
-
 foreach(_tool ${_tools})
   CMake_OPTIONAL_COMPONENT(${_tool})
-  install(TARGETS ${_tool} DESTINATION bin ${COMPONENT})
+  install(TARGETS ${_tool} DESTINATION ${CMAKE_BIN_DIR} ${COMPONENT})
 endforeach()
 
 install(FILES cmCPluginAPI.h DESTINATION ${CMAKE_DATA_DIR}/include)
+
+# Unset temporary variables
+unset(_tools)
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index 241cc8d..d8c77fc 100644
--- a/Source/CMakeVersion.cmake
+++ b/Source/CMakeVersion.cmake
@@ -1,5 +1,5 @@
 # CMake version number components.
 set(CMake_VERSION_MAJOR 3)
-set(CMake_VERSION_MINOR 6)
-set(CMake_VERSION_PATCH 2)
-#set(CMake_VERSION_RC 0)
+set(CMake_VERSION_MINOR 7)
+set(CMake_VERSION_PATCH 0)
+set(CMake_VERSION_RC 2)
diff --git a/Source/CMakeVersionCompute.cmake b/Source/CMakeVersionCompute.cmake
index 496d6cf..d9218d7 100644
--- a/Source/CMakeVersionCompute.cmake
+++ b/Source/CMakeVersionCompute.cmake
@@ -3,18 +3,27 @@ include(${CMake_SOURCE_DIR}/Source/CMakeVersion.cmake)
 
 # Releases define a small patch level.
 if("${CMake_VERSION_PATCH}" VERSION_LESS 20000000)
+  set(CMake_VERSION_IS_DIRTY 0)
   set(CMake_VERSION_IS_RELEASE 1)
   set(CMake_VERSION_SOURCE "")
 else()
+  set(CMake_VERSION_IS_DIRTY 0) # may be set to 1 by CMakeVersionSource
   set(CMake_VERSION_IS_RELEASE 0)
   include(${CMake_SOURCE_DIR}/Source/CMakeVersionSource.cmake)
 endif()
 
 # Compute the full version string.
 set(CMake_VERSION ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH})
-if(CMake_VERSION_RC)
-  set(CMake_VERSION ${CMake_VERSION}-rc${CMake_VERSION_RC})
-endif()
 if(CMake_VERSION_SOURCE)
-  set(CMake_VERSION ${CMake_VERSION}-${CMake_VERSION_SOURCE})
+  set(CMake_VERSION_SUFFIX "${CMake_VERSION_SOURCE}")
+elseif(CMake_VERSION_RC)
+  set(CMake_VERSION_SUFFIX "rc${CMake_VERSION_RC}")
+else()
+  set(CMake_VERSION_SUFFIX "")
+endif()
+if(CMake_VERSION_SUFFIX)
+  set(CMake_VERSION ${CMake_VERSION}-${CMake_VERSION_SUFFIX})
+endif()
+if(CMake_VERSION_IS_DIRTY)
+  set(CMake_VERSION ${CMake_VERSION}-dirty)
 endif()
diff --git a/Source/CMakeVersionSource.cmake b/Source/CMakeVersionSource.cmake
index 888f557..5ea1de3 100644
--- a/Source/CMakeVersionSource.cmake
+++ b/Source/CMakeVersionSource.cmake
@@ -23,15 +23,8 @@ if(EXISTS ${CMake_SOURCE_DIR}/.git/HEAD)
         WORKING_DIRECTORY ${CMake_SOURCE_DIR}
         )
       if(dirty)
-        set(CMake_VERSION_SOURCE "${CMake_VERSION_SOURCE}-dirty")
+        set(CMake_VERSION_IS_DIRTY 1)
       endif()
     endif()
   endif()
-elseif(EXISTS ${CMake_SOURCE_DIR}/CVS/Repository)
-  file(READ ${CMake_SOURCE_DIR}/CVS/Repository repo)
-  set(branch "")
-  if("${repo}" MATCHES "\\.git/([^\r\n]*)")
-    set(branch "${CMAKE_MATCH_1}")
-  endif()
-  set(CMake_VERSION_SOURCE "cvs${branch}")
 endif()
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
index c1ff526..ee46d86 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
@@ -1,32 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackIFWGenerator.h"
 
-#include <CPack/cmCPackComponentGroup.h>
-#include <CPack/cmCPackLog.h>
-
-#include <cmsys/Directory.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <cmsys/SystemTools.hxx>
-
-#include <cmGeneratedFileStream.h>
-#include <cmGlobalGenerator.h>
-#include <cmMakefile.h>
-#include <cmSystemTools.h>
-#include <cmTimestamp.h>
-#include <cmVersionConfig.h>
-#include <cmXMLWriter.h>
+#include "CPack/cmCPackComponentGroup.h"
+#include "CPack/cmCPackGenerator.h"
+#include "CPack/cmCPackLog.h"
+#include "cmCPackIFWInstaller.h"
+#include "cmCPackIFWPackage.h"
+#include "cmCPackIFWRepository.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+#include "cmTimestamp.h"
+#include "cmVersionConfig.h"
+#include "cmXMLWriter.h"
+
+#include <sstream>
+#include <utility>
 
 cmCPackIFWGenerator::cmCPackIFWGenerator()
 {
@@ -101,8 +90,9 @@ int cmCPackIFWGenerator::PackageFiles()
     int retVal = 1;
     cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate repository"
                     << std::endl);
-    bool res = cmSystemTools::RunSingleCommand(
-      ifwCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+    bool res = cmSystemTools::RunSingleCommand(ifwCmd.c_str(), &output,
+                                               &output, &retVal, CM_NULLPTR,
+                                               this->GeneratorVerbose, 0);
     if (!res || retVal) {
       cmGeneratedFileStream ofs(ifwTmpFile.c_str());
       ofs << "# Run command: " << ifwCmd << std::endl
@@ -130,6 +120,19 @@ int cmCPackIFWGenerator::PackageFiles()
   {
     std::string ifwCmd = BinCreator;
     ifwCmd += " -c " + this->toplevel + "/config/config.xml";
+
+    if (!Installer.Resources.empty()) {
+      ifwCmd += " -r ";
+      std::vector<std::string>::iterator it = Installer.Resources.begin();
+      std::string path = this->toplevel + "/resources/";
+      ifwCmd += path + *it;
+      ++it;
+      while (it != Installer.Resources.end()) {
+        ifwCmd += "," + path + *it;
+        ++it;
+      }
+    }
+
     ifwCmd += " -p " + this->toplevel + "/packages";
 
     if (!PkgsDirsVector.empty()) {
@@ -178,8 +181,9 @@ int cmCPackIFWGenerator::PackageFiles()
     std::string output;
     int retVal = 1;
     cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate package" << std::endl);
-    bool res = cmSystemTools::RunSingleCommand(
-      ifwCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+    bool res = cmSystemTools::RunSingleCommand(ifwCmd.c_str(), &output,
+                                               &output, &retVal, CM_NULLPTR,
+                                               this->GeneratorVerbose, 0);
     if (!res || retVal) {
       cmGeneratedFileStream ofs(ifwTmpFile.c_str());
       ofs << "# Run command: " << ifwCmd << std::endl
@@ -345,18 +349,21 @@ cmCPackComponent* cmCPackIFWGenerator::GetComponent(
   const std::string& projectName, const std::string& componentName)
 {
   ComponentsMap::iterator cit = Components.find(componentName);
-  if (cit != Components.end())
+  if (cit != Components.end()) {
     return &(cit->second);
+  }
 
   cmCPackComponent* component =
     cmCPackGenerator::GetComponent(projectName, componentName);
-  if (!component)
+  if (!component) {
     return component;
+  }
 
   std::string name = GetComponentPackageName(component);
   PackagesMap::iterator pit = Packages.find(name);
-  if (pit != Packages.end())
+  if (pit != Packages.end()) {
     return component;
+  }
 
   cmCPackIFWPackage* package = &Packages[name];
   package->Name = name;
@@ -387,13 +394,15 @@ cmCPackComponentGroup* cmCPackIFWGenerator::GetComponentGroup(
 {
   cmCPackComponentGroup* group =
     cmCPackGenerator::GetComponentGroup(projectName, groupName);
-  if (!group)
+  if (!group) {
     return group;
+  }
 
   std::string name = GetGroupPackageName(group);
   PackagesMap::iterator pit = Packages.find(name);
-  if (pit != Packages.end())
+  if (pit != Packages.end()) {
     return group;
+  }
 
   cmCPackIFWPackage* package = &Packages[name];
   package->Name = name;
@@ -462,8 +471,9 @@ std::string cmCPackIFWGenerator::GetGroupPackageName(
   cmCPackComponentGroup* group) const
 {
   std::string name;
-  if (!group)
+  if (!group) {
     return name;
+  }
   if (cmCPackIFWPackage* package = GetGroupPackage(group)) {
     return package->Name;
   }
@@ -488,8 +498,9 @@ std::string cmCPackIFWGenerator::GetComponentPackageName(
   cmCPackComponent* component) const
 {
   std::string name;
-  if (!component)
+  if (!component) {
     return name;
+  }
   if (cmCPackIFWPackage* package = GetComponentPackage(component)) {
     return package->Name;
   }
@@ -519,7 +530,7 @@ cmCPackIFWPackage* cmCPackIFWGenerator::GetGroupPackage(
 {
   std::map<cmCPackComponentGroup*, cmCPackIFWPackage*>::const_iterator pit =
     GroupPackages.find(group);
-  return pit != GroupPackages.end() ? pit->second : 0;
+  return pit != GroupPackages.end() ? pit->second : CM_NULLPTR;
 }
 
 cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
@@ -527,15 +538,16 @@ cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
 {
   std::map<cmCPackComponent*, cmCPackIFWPackage*>::const_iterator pit =
     ComponentPackages.find(component);
-  return pit != ComponentPackages.end() ? pit->second : 0;
+  return pit != ComponentPackages.end() ? pit->second : CM_NULLPTR;
 }
 
 cmCPackIFWRepository* cmCPackIFWGenerator::GetRepository(
   const std::string& repositoryName)
 {
   RepositoriesMap::iterator rit = Repositories.find(repositoryName);
-  if (rit != Repositories.end())
+  if (rit != Repositories.end()) {
     return &(rit->second);
+  }
 
   cmCPackIFWRepository* repository = &Repositories[repositoryName];
   repository->Name = repositoryName;
@@ -548,7 +560,7 @@ cmCPackIFWRepository* cmCPackIFWGenerator::GetRepository(
     }
   } else {
     Repositories.erase(repositoryName);
-    repository = 0;
+    repository = CM_NULLPTR;
     cmCPackLogger(cmCPackLog::LOG_WARNING, "Invalid repository \""
                     << repositoryName << "\""
                     << " configuration. Repository will be skipped."
@@ -559,7 +571,7 @@ cmCPackIFWRepository* cmCPackIFWGenerator::GetRepository(
 
 void cmCPackIFWGenerator::WriteGeneratedByToStrim(cmXMLWriter& xout)
 {
-  std::stringstream comment;
+  std::ostringstream comment;
   comment << "Generated by CPack " << CMake_VERSION << " IFW generator "
           << "for QtIFW ";
   if (IsVersionLess("2.0")) {
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.h b/Source/CPack/IFW/cmCPackIFWGenerator.h
index 2b35749..88a3741 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.h
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.h
@@ -1,23 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackIFWGenerator_h
 #define cmCPackIFWGenerator_h
 
-#include <CPack/cmCPackGenerator.h>
+#include <cmConfigure.h>
 
+#include "CPack/cmCPackComponentGroup.h"
+#include "CPack/cmCPackGenerator.h"
 #include "cmCPackIFWInstaller.h"
 #include "cmCPackIFWPackage.h"
 #include "cmCPackIFWRepository.h"
+#include "cmTypeMacro.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmXMLWriter;
 
@@ -46,7 +44,7 @@ public:
   /**
    * Destruct IFW generator
    */
-  virtual ~cmCPackIFWGenerator();
+  ~cmCPackIFWGenerator() CM_OVERRIDE;
 
   /**
    * Compare \a version with QtIFW framework version
@@ -70,18 +68,18 @@ protected:
    * @brief Initialize generator
    * @return 0 on failure
    */
-  virtual int InitializeInternal();
-  virtual int PackageFiles();
-  virtual const char* GetPackagingInstallPrefix();
+  int InitializeInternal() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetPackagingInstallPrefix() CM_OVERRIDE;
 
   /**
    * @brief Extension of binary installer
    * @return Executable suffix or value from default implementation
    */
-  virtual const char* GetOutputExtension();
+  const char* GetOutputExtension() CM_OVERRIDE;
 
-  virtual std::string GetComponentInstallDirNameSuffix(
-    const std::string& componentName);
+  std::string GetComponentInstallDirNameSuffix(
+    const std::string& componentName) CM_OVERRIDE;
 
   /**
    * @brief Get Component
@@ -92,8 +90,8 @@ protected:
    *
    * @return Pointer to component
    */
-  virtual cmCPackComponent* GetComponent(const std::string& projectName,
-                                         const std::string& componentName);
+  cmCPackComponent* GetComponent(const std::string& projectName,
+                                 const std::string& componentName) CM_OVERRIDE;
 
   /**
    * @brief Get group of component
@@ -104,12 +102,13 @@ protected:
    *
    * @return Pointer to component group
    */
-  virtual cmCPackComponentGroup* GetComponentGroup(
-    const std::string& projectName, const std::string& groupName);
+  cmCPackComponentGroup* GetComponentGroup(
+    const std::string& projectName, const std::string& groupName) CM_OVERRIDE;
 
-  enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const;
-  virtual bool SupportsAbsoluteDestination() const;
-  virtual bool SupportsComponentInstallation() const;
+  enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const
+    CM_OVERRIDE;
+  bool SupportsAbsoluteDestination() const CM_OVERRIDE;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
 protected:
   // Methods
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
index dfc509b..d9ac909 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -1,23 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackIFWInstaller.h"
 
+#include "CPack/cmCPackGenerator.h"
+#include "CPack/cmCPackLog.h"
 #include "cmCPackIFWGenerator.h"
+#include "cmCPackIFWPackage.h"
+#include "cmCPackIFWRepository.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+#include "cmXMLParser.h"
+#include "cmXMLWriter.h"
 
-#include <CPack/cmCPackLog.h>
-
-#include <cmGeneratedFileStream.h>
-#include <cmXMLWriter.h>
+#include <cmConfigure.h>
+#include <utility>
 
 #ifdef cmCPackLogger
 #undef cmCPackLogger
@@ -33,13 +29,13 @@
   } while (0)
 
 cmCPackIFWInstaller::cmCPackIFWInstaller()
-  : Generator(0)
+  : Generator(CM_NULLPTR)
 {
 }
 
 const char* cmCPackIFWInstaller::GetOption(const std::string& op) const
 {
-  return Generator ? Generator->GetOption(op) : 0;
+  return Generator ? Generator->GetOption(op) : CM_NULLPTR;
 }
 
 bool cmCPackIFWInstaller::IsOn(const std::string& op) const
@@ -194,8 +190,70 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
         this->GetOption("CPACK_IFW_PACKAGE_CONTROL_SCRIPT")) {
     ControlScript = optIFW_CONTROL_SCRIPT;
   }
+
+  // Resources
+  if (const char* optIFW_PACKAGE_RESOURCES =
+        this->GetOption("CPACK_IFW_PACKAGE_RESOURCES")) {
+    Resources.clear();
+    cmSystemTools::ExpandListArgument(optIFW_PACKAGE_RESOURCES, Resources);
+  }
 }
 
+/** \class cmCPackIFWResourcesParser
+ * \brief Helper class that parse resources form .qrc (Qt)
+ */
+class cmCPackIFWResourcesParser : public cmXMLParser
+{
+public:
+  cmCPackIFWResourcesParser(cmCPackIFWInstaller* i)
+    : installer(i)
+    , file(false)
+  {
+    path = i->Directory + "/resources";
+  }
+
+  bool ParseResource(size_t r)
+  {
+    hasFiles = false;
+    hasErrors = false;
+
+    basePath = cmSystemTools::GetFilenamePath(installer->Resources[r].data());
+
+    ParseFile(installer->Resources[r].data());
+
+    return hasFiles && !hasErrors;
+  }
+
+  cmCPackIFWInstaller* installer;
+  bool file, hasFiles, hasErrors;
+  std::string path, basePath;
+
+protected:
+  void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE
+  {
+    file = name == "file" ? true : false;
+    if (file) {
+      hasFiles = true;
+    }
+  }
+
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+  {
+    if (file) {
+      std::string content(data, data + length);
+      content = cmSystemTools::TrimWhitespace(content);
+      std::string source = basePath + "/" + content;
+      std::string destination = path + "/" + content;
+      if (!cmSystemTools::CopyFileIfDifferent(source.data(),
+                                              destination.data())) {
+        hasErrors = true;
+      }
+    }
+  }
+
+  void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
+};
+
 void cmCPackIFWInstaller::GenerateInstallerFile()
 {
   // Lazy directory initialization
@@ -311,6 +369,26 @@ void cmCPackIFWInstaller::GenerateInstallerFile()
     xout.Element("ControlScript", name);
   }
 
+  // Resources (copy to resources dir)
+  if (!Resources.empty()) {
+    std::vector<std::string> resources;
+    cmCPackIFWResourcesParser parser(this);
+    for (size_t i = 0; i < Resources.size(); i++) {
+      if (parser.ParseResource(i)) {
+        std::string name = cmSystemTools::GetFilenameName(Resources[i]);
+        std::string path = Directory + "/resources/" + name;
+        cmsys::SystemTools::CopyFileIfDifferent(Resources[i].data(),
+                                                path.data());
+        resources.push_back(name);
+      } else {
+        cmCPackLogger(cmCPackLog::LOG_WARNING, "Can't copy resources from \""
+                        << Resources[i] << "\". Resource will be skipped."
+                        << std::endl);
+      }
+    }
+    Resources = resources;
+  }
+
   xout.EndElement();
   xout.EndDocument();
 }
@@ -343,6 +421,7 @@ void cmCPackIFWInstaller::GeneratePackageFiles()
 
 void cmCPackIFWInstaller::WriteGeneratedByToStrim(cmXMLWriter& xout)
 {
-  if (Generator)
+  if (Generator) {
     Generator->WriteGeneratedByToStrim(xout);
+  }
 }
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.h b/Source/CPack/IFW/cmCPackIFWInstaller.h
index 3170116..eba9bec 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.h
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.h
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackIFWInstaller_h
 #define cmCPackIFWInstaller_h
 
-#include <cmStandardIncludes.h>
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
+#include <vector>
 
-class cmCPackIFWPackage;
 class cmCPackIFWGenerator;
+class cmCPackIFWPackage;
 class cmCPackIFWRepository;
 class cmXMLWriter;
 
@@ -90,6 +84,9 @@ public:
   /// Filename for a custom installer control script
   std::string ControlScript;
 
+  /// List of resources to include in the installer binary
+  std::vector<std::string> Resources;
+
 public:
   // Internal implementation
 
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
index ad153d1..4d46120 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.cxx
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -1,24 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackIFWPackage.h"
 
+#include "CPack/cmCPackComponentGroup.h"
+#include "CPack/cmCPackGenerator.h"
+#include "CPack/cmCPackLog.h"
 #include "cmCPackIFWGenerator.h"
+#include "cmCPackIFWInstaller.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+#include "cmTimestamp.h"
+#include "cmXMLWriter.h"
 
-#include <CPack/cmCPackLog.h>
-
-#include <cmGeneratedFileStream.h>
-#include <cmTimestamp.h>
-#include <cmXMLWriter.h>
+#include <cmConfigure.h>
+#include <map>
+#include <sstream>
+#include <stddef.h>
 
 //----------------------------------------------------------------- Logger ---
 #ifdef cmCPackLogger
@@ -71,8 +68,9 @@ cmCPackIFWPackage::DependenceStruct::DependenceStruct(
 
 std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
 {
-  if (Compare.Type == CompareNone)
+  if (Compare.Type == CompareNone) {
     return Name;
+  }
 
   std::string result = Name;
 
@@ -95,15 +93,15 @@ std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
 
 //------------------------------------------------------ cmCPackIFWPackage ---
 cmCPackIFWPackage::cmCPackIFWPackage()
-  : Generator(0)
-  , Installer(0)
+  : Generator(CM_NULLPTR)
+  , Installer(CM_NULLPTR)
 {
 }
 
 const char* cmCPackIFWPackage::GetOption(const std::string& op) const
 {
-  const char* option = Generator ? Generator->GetOption(op) : 0;
-  return option && *option ? option : 0;
+  const char* option = Generator ? Generator->GetOption(op) : CM_NULLPTR;
+  return option && *option ? option : CM_NULLPTR;
 }
 
 bool cmCPackIFWPackage::IsOn(const std::string& op) const
@@ -128,8 +126,9 @@ bool cmCPackIFWPackage::IsVersionEqual(const char* version)
 
 std::string cmCPackIFWPackage::GetComponentName(cmCPackComponent* component)
 {
-  if (!component)
+  if (!component) {
     return "";
+  }
   const char* option =
     GetOption("CPACK_IFW_COMPONENT_" +
               cmsys::SystemTools::UpperCase(component->Name) + "_NAME");
@@ -144,6 +143,7 @@ void cmCPackIFWPackage::DefaultConfiguration()
   ReleaseDate = "";
   Script = "";
   Licenses.clear();
+  UserInterfaces.clear();
   SortingPriority = "";
   Default = "";
   Essential = "";
@@ -189,8 +189,9 @@ int cmCPackIFWPackage::ConfigureFromOptions()
 
 int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
 {
-  if (!component)
+  if (!component) {
     return 0;
+  }
 
   // Restore defaul configuration
   DefaultConfiguration();
@@ -219,6 +220,12 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
     Script = option;
   }
 
+  // User interfaces
+  if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) {
+    UserInterfaces.clear();
+    cmSystemTools::ExpandListArgument(option, UserInterfaces);
+  }
+
   // CMake dependencies
   if (!component->Dependencies.empty()) {
     std::vector<cmCPackComponent*>::iterator dit;
@@ -284,8 +291,9 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
 
 int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
 {
-  if (!group)
+  if (!group) {
     return 0;
+  }
 
   // Restore defaul configuration
   DefaultConfiguration();
@@ -311,6 +319,12 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
     Script = option;
   }
 
+  // User interfaces
+  if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) {
+    UserInterfaces.clear();
+    cmSystemTools::ExpandListArgument(option, UserInterfaces);
+  }
+
   // Licenses
   if (const char* option = this->GetOption(prefix + "LICENSES")) {
     Licenses.clear();
@@ -406,6 +420,23 @@ void cmCPackIFWPackage::GeneratePackageFile()
     xout.Element("Script", name);
   }
 
+  // User Interfaces (copy to meta dir)
+  std::vector<std::string> userInterfaces = UserInterfaces;
+  for (size_t i = 0; i < userInterfaces.size(); i++) {
+    std::string name = cmSystemTools::GetFilenameName(userInterfaces[i]);
+    std::string path = Directory + "/meta/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(userInterfaces[i].data(),
+                                            path.data());
+    userInterfaces[i] = name;
+  }
+  if (!userInterfaces.empty()) {
+    xout.StartElement("UserInterfaces");
+    for (size_t i = 0; i < userInterfaces.size(); i++) {
+      xout.Element("UserInterface", userInterfaces[i]);
+    }
+    xout.EndElement();
+  }
+
   // Dependencies
   std::set<DependenceStruct> compDepSet;
   for (std::set<DependenceStruct*>::iterator ait = AlienDependencies.begin();
@@ -418,7 +449,7 @@ void cmCPackIFWPackage::GeneratePackageFile()
   }
   // Write dependencies
   if (!compDepSet.empty()) {
-    std::stringstream dependencies;
+    std::ostringstream dependencies;
     std::set<DependenceStruct>::iterator it = compDepSet.begin();
     dependencies << it->NameWithCompare();
     ++it;
@@ -474,6 +505,7 @@ void cmCPackIFWPackage::GeneratePackageFile()
 
 void cmCPackIFWPackage::WriteGeneratedByToStrim(cmXMLWriter& xout)
 {
-  if (Generator)
+  if (Generator) {
     Generator->WriteGeneratedByToStrim(xout);
+  }
 }
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h
index 55b07ec..d1af2bd 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.h
+++ b/Source/CPack/IFW/cmCPackIFWPackage.h
@@ -1,24 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackIFWPackage_h
 #define cmCPackIFWPackage_h
 
-#include <cmStandardIncludes.h>
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <set>
+#include <string>
+#include <vector>
 
 class cmCPackComponent;
 class cmCPackComponentGroup;
-class cmCPackIFWInstaller;
 class cmCPackIFWGenerator;
+class cmCPackIFWInstaller;
 class cmXMLWriter;
 
 /** \class cmCPackIFWPackage
@@ -95,6 +89,9 @@ public:
   /// List of license agreements to be accepted by the installing user
   std::vector<std::string> Licenses;
 
+  /// List of pages to load
+  std::vector<std::string> UserInterfaces;
+
   /// Priority of the component in the tree
   std::string SortingPriority;
 
diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx
index 45b47cd..8d50e30 100644
--- a/Source/CPack/IFW/cmCPackIFWRepository.cxx
+++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx
@@ -1,24 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackIFWRepository.h"
 
+#include "CPack/cmCPackGenerator.h"
 #include "cmCPackIFWGenerator.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+#include "cmXMLParser.h"
+#include "cmXMLWriter.h"
 
-#include <CPack/cmCPackLog.h>
-
-#include <cmGeneratedFileStream.h>
-#include <cmXMLParser.h>
-#include <cmXMLWriter.h>
+#include <cmConfigure.h>
+#include <stddef.h>
 
 #ifdef cmCPackLogger
 #undef cmCPackLogger
@@ -35,7 +27,7 @@
 
 cmCPackIFWRepository::cmCPackIFWRepository()
   : Update(None)
-  , Generator(0)
+  , Generator(CM_NULLPTR)
 {
 }
 
@@ -45,16 +37,16 @@ bool cmCPackIFWRepository::IsValid() const
 
   switch (Update) {
     case None:
-      valid = Url.empty() ? false : true;
+      valid = !Url.empty();
       break;
     case Add:
-      valid = Url.empty() ? false : true;
+      valid = !Url.empty();
       break;
     case Remove:
-      valid = Url.empty() ? false : true;
+      valid = !Url.empty();
       break;
     case Replace:
-      valid = (OldUrl.empty() || NewUrl.empty()) ? false : true;
+      valid = !OldUrl.empty() && !NewUrl.empty();
       break;
   }
 
@@ -63,7 +55,7 @@ bool cmCPackIFWRepository::IsValid() const
 
 const char* cmCPackIFWRepository::GetOption(const std::string& op) const
 {
-  return Generator ? Generator->GetOption(op) : 0;
+  return Generator ? Generator->GetOption(op) : CM_NULLPTR;
 }
 
 bool cmCPackIFWRepository::IsOn(const std::string& op) const
@@ -89,8 +81,9 @@ bool cmCPackIFWRepository::IsVersionEqual(const char* version)
 bool cmCPackIFWRepository::ConfigureFromOptions()
 {
   // Name;
-  if (Name.empty())
+  if (Name.empty()) {
     return false;
+  }
 
   std::string prefix =
     "CPACK_IFW_REPOSITORY_" + cmsys::SystemTools::UpperCase(Name) + "_";
@@ -176,7 +169,7 @@ public:
   bool patched;
 
 protected:
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     xout.StartElement(name);
     StartFragment(atts);
@@ -191,26 +184,29 @@ protected:
     }
   }
 
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "Updates" && !patched) {
       repository->WriteRepositoryUpdates(xout);
       patched = true;
     }
     xout.EndElement();
-    if (patched)
+    if (patched) {
       return;
+    }
     if (name == "Checksum") {
       repository->WriteRepositoryUpdates(xout);
       patched = true;
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     std::string content(data, data + length);
-    if (content == "" || content == " " || content == "  " || content == "\n")
+    if (content == "" || content == " " || content == "  " ||
+        content == "\n") {
       return;
+    }
     xout.Content(content);
   }
 };
@@ -244,11 +240,7 @@ bool cmCPackIFWRepository::PatchUpdatesXml()
 
   fout.Close();
 
-  if (!cmSystemTools::RenameFile(updatesPatchXml.data(), updatesXml.data())) {
-    return false;
-  }
-
-  return true;
+  return cmSystemTools::RenameFile(updatesPatchXml.data(), updatesXml.data());
 }
 
 void cmCPackIFWRepository::WriteRepositoryConfig(cmXMLWriter& xout)
@@ -336,6 +328,7 @@ void cmCPackIFWRepository::WriteRepositoryUpdates(cmXMLWriter& xout)
 
 void cmCPackIFWRepository::WriteGeneratedByToStrim(cmXMLWriter& xout)
 {
-  if (Generator)
+  if (Generator) {
     Generator->WriteGeneratedByToStrim(xout);
+  }
 }
diff --git a/Source/CPack/IFW/cmCPackIFWRepository.h b/Source/CPack/IFW/cmCPackIFWRepository.h
index 5ffb775..36f46da 100644
--- a/Source/CPack/IFW/cmCPackIFWRepository.h
+++ b/Source/CPack/IFW/cmCPackIFWRepository.h
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackIFWRepository_h
 #define cmCPackIFWRepository_h
 
-#include <cmStandardIncludes.h>
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 class cmCPackIFWGenerator;
 class cmXMLWriter;
diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx
index 19204a2..6eb4a6c 100644
--- a/Source/CPack/OSXScriptLauncher.cxx
+++ b/Source/CPack/OSXScriptLauncher.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include <cmsys/FStream.hxx>
 #include <cmsys/Process.h>
 #include <cmsys/SystemTools.hxx>
@@ -72,7 +63,7 @@ int main(int argc, char* argv[])
 
   std::string scriptDirectory =
     cmsys::SystemTools::GetFilenamePath(fullScriptPath);
-  ofs << fullScriptPath.c_str() << std::endl;
+  ofs << fullScriptPath << std::endl;
   std::vector<const char*> args;
   args.push_back(fullScriptPath.c_str());
   int cc;
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index 8777296..5320449 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackWIXGenerator.h"
 
 #include <CPack/cmCPackComponentGroup.h>
@@ -18,6 +8,7 @@
 #include <cmGeneratedFileStream.h>
 #include <cmInstalledFile.h>
 #include <cmSystemTools.h>
+#include <cmUuid.h>
 
 #include "cmWIXDirectoriesSourceWriter.h"
 #include "cmWIXFeaturesSourceWriter.h"
@@ -34,6 +25,7 @@
 
 cmCPackWIXGenerator::cmCPackWIXGenerator()
   : Patch(0)
+  , ComponentGuidType(cmWIXSourceWriter::WIX_GENERATED_GUID)
 {
 }
 
@@ -90,7 +82,7 @@ bool cmCPackWIXGenerator::RunCandleCommand(std::string const& sourceFile,
     return false;
   }
 
-  std::stringstream command;
+  std::ostringstream command;
   command << QuotePath(executable);
   command << " -nologo";
   command << " -arch " << GetArchitecture();
@@ -115,7 +107,7 @@ bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles)
     return false;
   }
 
-  std::stringstream command;
+  std::ostringstream command;
   command << QuotePath(executable);
   command << " -nologo";
   command << " -out " << QuotePath(packageFileNames.at(0));
@@ -233,6 +225,12 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
     }
   }
 
+  // if install folder is supposed to be set absolutely, the default
+  // component guid "*" cannot be used
+  if (cmSystemTools::IsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) {
+    this->ComponentGuidType = cmWIXSourceWriter::CMAKE_GENERATED_GUID;
+  }
+
   return true;
 }
 
@@ -254,7 +252,7 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
 
   std::set<std::string> usedBaseNames;
 
-  std::stringstream objectFiles;
+  std::ostringstream objectFiles;
   for (size_t i = 0; i < this->WixSources.size(); ++i) {
     std::string const& sourceFilename = this->WixSources[i];
 
@@ -265,7 +263,7 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
     std::string uniqueBaseName = baseName;
 
     while (usedBaseNames.find(uniqueBaseName) != usedBaseNames.end()) {
-      std::stringstream tmp;
+      std::ostringstream tmp;
       tmp << baseName << ++counter;
       uniqueBaseName = tmp.str();
     }
@@ -316,7 +314,9 @@ void cmCPackWIXGenerator::CreateWiXVariablesIncludeFile()
 {
   std::string includeFilename = this->CPackTopLevel + "/cpack_variables.wxi";
 
-  cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
+  cmWIXSourceWriter includeFile(this->Logger, includeFilename,
+                                this->ComponentGuidType,
+                                cmWIXSourceWriter::INCLUDE_ELEMENT_ROOT);
 
   CopyDefinition(includeFile, "CPACK_WIX_PRODUCT_GUID");
   CopyDefinition(includeFile, "CPACK_WIX_UPGRADE_GUID");
@@ -337,7 +337,9 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
 {
   std::string includeFilename = this->CPackTopLevel + "/properties.wxi";
 
-  cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
+  cmWIXSourceWriter includeFile(this->Logger, includeFilename,
+                                this->ComponentGuidType,
+                                cmWIXSourceWriter::INCLUDE_ELEMENT_ROOT);
 
   std::string prefix = "CPACK_WIX_PROPERTY_";
   std::vector<std::string> options = GetOptions();
@@ -385,7 +387,9 @@ void cmCPackWIXGenerator::CreateWiXProductFragmentIncludeFile()
 {
   std::string includeFilename = this->CPackTopLevel + "/product_fragment.wxi";
 
-  cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
+  cmWIXSourceWriter includeFile(this->Logger, includeFilename,
+                                this->ComponentGuidType,
+                                cmWIXSourceWriter::INCLUDE_ELEMENT_ROOT);
 
   this->Patch->ApplyFragment("#PRODUCT", includeFile);
 }
@@ -403,7 +407,7 @@ void cmCPackWIXGenerator::AddDefinition(cmWIXSourceWriter& source,
                                         std::string const& name,
                                         std::string const& value)
 {
-  std::stringstream tmp;
+  std::ostringstream tmp;
   tmp << name << "=\"" << value << '"';
 
   source.AddProcessingInstruction(
@@ -412,13 +416,15 @@ void cmCPackWIXGenerator::AddDefinition(cmWIXSourceWriter& source,
 
 bool cmCPackWIXGenerator::CreateWiXSourceFiles()
 {
+  // if install folder is supposed to be set absolutely, the default
+  // component guid "*" cannot be used
   std::string directoryDefinitionsFilename =
     this->CPackTopLevel + "/directories.wxs";
 
   this->WixSources.push_back(directoryDefinitionsFilename);
 
   cmWIXDirectoriesSourceWriter directoryDefinitions(
-    this->Logger, directoryDefinitionsFilename);
+    this->Logger, directoryDefinitionsFilename, this->ComponentGuidType);
   directoryDefinitions.BeginElement("Fragment");
 
   std::string installRoot;
@@ -438,8 +444,8 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
 
   this->WixSources.push_back(fileDefinitionsFilename);
 
-  cmWIXFilesSourceWriter fileDefinitions(this->Logger,
-                                         fileDefinitionsFilename);
+  cmWIXFilesSourceWriter fileDefinitions(this->Logger, fileDefinitionsFilename,
+                                         this->ComponentGuidType);
 
   fileDefinitions.BeginElement("Fragment");
 
@@ -448,8 +454,8 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
 
   this->WixSources.push_back(featureDefinitionsFilename);
 
-  cmWIXFeaturesSourceWriter featureDefinitions(this->Logger,
-                                               featureDefinitionsFilename);
+  cmWIXFeaturesSourceWriter featureDefinitions(
+    this->Logger, featureDefinitionsFilename, this->ComponentGuidType);
 
   featureDefinitions.BeginElement("Fragment");
 
@@ -464,7 +470,14 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
     return false;
   }
 
-  featureDefinitions.AddAttribute("Title", cpackPackageName);
+  std::string featureTitle = cpackPackageName;
+  if (const char* title = GetOption("CPACK_WIX_ROOT_FEATURE_TITLE")) {
+    featureTitle = title;
+  }
+  featureDefinitions.AddAttribute("Title", featureTitle);
+  if (const char* desc = GetOption("CPACK_WIX_ROOT_FEATURE_DESCRIPTION")) {
+    featureDefinitions.AddAttribute("Description", desc);
+  }
   featureDefinitions.AddAttribute("Level", "1");
   this->Patch->ApplyFragment("#PRODUCTFEATURE", featureDefinitions);
 
@@ -559,6 +572,9 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
 
 std::string cmCPackWIXGenerator::GetProgramFilesFolderId() const
 {
+  if (cmSystemTools::IsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) {
+    return "";
+  }
   if (GetArchitecture() == "x86") {
     return "ProgramFilesFolder";
   } else {
@@ -602,7 +618,7 @@ bool cmCPackWIXGenerator::CreateFeatureHierarchy(
        i != ComponentGroups.end(); ++i) {
     cmCPackComponentGroup const& group = i->second;
     if (group.ParentGroup == 0) {
-      featureDefinitions.EmitFeatureForComponentGroup(group);
+      featureDefinitions.EmitFeatureForComponentGroup(group, *this->Patch);
     }
   }
 
@@ -612,7 +628,7 @@ bool cmCPackWIXGenerator::CreateFeatureHierarchy(
     cmCPackComponent const& component = i->second;
 
     if (!component.Group) {
-      featureDefinitions.EmitFeatureForComponent(component);
+      featureDefinitions.EmitFeatureForComponent(component, *this->Patch);
     }
   }
 
@@ -748,7 +764,8 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
 
   fileDefinitions.BeginElement("Component");
   fileDefinitions.AddAttribute("Id", componentId);
-  fileDefinitions.AddAttribute("Guid", "*");
+  fileDefinitions.AddAttribute(
+    "Guid", fileDefinitions.CreateGuidFromComponentId(componentId));
 
   this->Patch->ApplyFragment(componentId, fileDefinitions);
 
@@ -1019,7 +1036,7 @@ std::string cmCPackWIXGenerator::CreateNewIdForPath(std::string const& path)
     idPrefix = "H";
   }
 
-  std::stringstream result;
+  std::ostringstream result;
   result << idPrefix << "_" << identifier;
 
   size_t ambiguityCount = ++IdAmbiguityCounter[identifier];
@@ -1044,7 +1061,7 @@ std::string cmCPackWIXGenerator::CreateNewIdForPath(std::string const& path)
 std::string cmCPackWIXGenerator::CreateHashedId(
   std::string const& path, std::string const& normalizedFilename)
 {
-  cmsys::auto_ptr<cmCryptoHash> sha1 = cmCryptoHash::New("SHA1");
+  CM_AUTO_PTR<cmCryptoHash> sha1 = cmCryptoHash::New("SHA1");
   std::string hash = sha1->HashString(path.c_str());
 
   std::string identifier;
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.h b/Source/CPack/WiX/cmCPackWIXGenerator.h
index 9d3a522..fc0994c 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.h
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackWIXGenerator_h
 #define cmCPackWIXGenerator_h
 
@@ -162,6 +152,8 @@ private:
   std::string CPackTopLevel;
 
   cmWIXPatch* Patch;
+
+  cmWIXSourceWriter::GuidType ComponentGuidType;
 };
 
 #endif
diff --git a/Source/CPack/WiX/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx
index 043cdff..9f9b39c 100644
--- a/Source/CPack/WiX/cmWIXAccessControlList.cxx
+++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXAccessControlList.h"
 
 #include <CPack/cmCPackGenerator.h>
@@ -127,7 +117,7 @@ void cmWIXAccessControlList::EmitBooleanAttribute(std::string const& entry,
                                                   std::string const& name)
 {
   if (!this->IsBooleanAttribute(name)) {
-    std::stringstream message;
+    std::ostringstream message;
     message << "Unknown boolean attribute '" << name << "'";
     this->ReportError(entry, message.str());
   }
diff --git a/Source/CPack/WiX/cmWIXAccessControlList.h b/Source/CPack/WiX/cmWIXAccessControlList.h
index a1ac593..0a25ee5 100644
--- a/Source/CPack/WiX/cmWIXAccessControlList.h
+++ b/Source/CPack/WiX/cmWIXAccessControlList.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXAccessControlList_h
 #define cmWIXAccessControlList_h
 
diff --git a/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx
index 60ecae6..975dffb 100644
--- a/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx
@@ -1,20 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXDirectoriesSourceWriter.h"
 
 cmWIXDirectoriesSourceWriter::cmWIXDirectoriesSourceWriter(
-  cmCPackLog* logger, std::string const& filename)
-  : cmWIXSourceWriter(logger, filename)
+  cmCPackLog* logger, std::string const& filename, GuidType componentGuidType)
+  : cmWIXSourceWriter(logger, filename, componentGuidType)
 {
 }
 
@@ -52,8 +42,12 @@ size_t cmWIXDirectoriesSourceWriter::BeginInstallationPrefixDirectory(
   std::string const& programFilesFolderId,
   std::string const& installRootString)
 {
-  BeginElement("Directory");
-  AddAttribute("Id", programFilesFolderId);
+  size_t offset = 1;
+  if (!programFilesFolderId.empty()) {
+    BeginElement("Directory");
+    AddAttribute("Id", programFilesFolderId);
+    offset = 0;
+  }
 
   std::vector<std::string> installRoot;
 
@@ -69,7 +63,7 @@ size_t cmWIXDirectoriesSourceWriter::BeginInstallationPrefixDirectory(
     if (i == installRoot.size() - 1) {
       AddAttribute("Id", "INSTALL_ROOT");
     } else {
-      std::stringstream tmp;
+      std::ostringstream tmp;
       tmp << "INSTALL_PREFIX_" << i;
       AddAttribute("Id", tmp.str());
     }
@@ -77,7 +71,7 @@ size_t cmWIXDirectoriesSourceWriter::BeginInstallationPrefixDirectory(
     AddAttribute("Name", installRoot[i]);
   }
 
-  return installRoot.size();
+  return installRoot.size() - offset;
 }
 
 void cmWIXDirectoriesSourceWriter::EndInstallationPrefixDirectory(size_t size)
diff --git a/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.h b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.h
index 023f4b8..062efe3 100644
--- a/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXDirectoriesSourceWriter_h
 #define cmWIXDirectoriesSourceWriter_h
 
@@ -25,8 +15,8 @@
 class cmWIXDirectoriesSourceWriter : public cmWIXSourceWriter
 {
 public:
-  cmWIXDirectoriesSourceWriter(cmCPackLog* logger,
-                               std::string const& filename);
+  cmWIXDirectoriesSourceWriter(cmCPackLog* logger, std::string const& filename,
+                               GuidType componentGuidType);
 
   void EmitStartMenuFolder(std::string const& startMenuFolder);
 
diff --git a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
index 16dd0ab..79a9fdd 100644
--- a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
@@ -1,20 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXFeaturesSourceWriter.h"
 
 cmWIXFeaturesSourceWriter::cmWIXFeaturesSourceWriter(
-  cmCPackLog* logger, std::string const& filename)
-  : cmWIXSourceWriter(logger, filename)
+  cmCPackLog* logger, std::string const& filename, GuidType componentGuidType)
+  : cmWIXSourceWriter(logger, filename, componentGuidType)
 {
 }
 
@@ -24,7 +14,7 @@ void cmWIXFeaturesSourceWriter::CreateCMakePackageRegistryEntry(
   BeginElement("Component");
   AddAttribute("Id", "CM_PACKAGE_REGISTRY");
   AddAttribute("Directory", "TARGETDIR");
-  AddAttribute("Guid", "*");
+  AddAttribute("Guid", CreateGuidFromComponentId("CM_PACKAGE_REGISTRY"));
 
   std::string registryKey =
     std::string("Software\\Kitware\\CMake\\Packages\\") + package;
@@ -42,7 +32,7 @@ void cmWIXFeaturesSourceWriter::CreateCMakePackageRegistryEntry(
 }
 
 void cmWIXFeaturesSourceWriter::EmitFeatureForComponentGroup(
-  cmCPackComponentGroup const& group)
+  cmCPackComponentGroup const& group, cmWIXPatch& patch)
 {
   BeginElement("Feature");
   AddAttribute("Id", "CM_G_" + group.Name);
@@ -57,20 +47,22 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponentGroup(
   for (std::vector<cmCPackComponentGroup*>::const_iterator i =
          group.Subgroups.begin();
        i != group.Subgroups.end(); ++i) {
-    EmitFeatureForComponentGroup(**i);
+    EmitFeatureForComponentGroup(**i, patch);
   }
 
   for (std::vector<cmCPackComponent*>::const_iterator i =
          group.Components.begin();
        i != group.Components.end(); ++i) {
-    EmitFeatureForComponent(**i);
+    EmitFeatureForComponent(**i, patch);
   }
 
+  patch.ApplyFragment("CM_G_" + group.Name, *this);
+
   EndElement("Feature");
 }
 
 void cmWIXFeaturesSourceWriter::EmitFeatureForComponent(
-  cmCPackComponent const& component)
+  cmCPackComponent const& component, cmWIXPatch& patch)
 {
   BeginElement("Feature");
   AddAttribute("Id", "CM_C_" + component.Name);
@@ -86,6 +78,12 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponent(
     AddAttribute("Display", "hidden");
   }
 
+  if (component.IsDisabledByDefault) {
+    AddAttribute("Level", "2");
+  }
+
+  patch.ApplyFragment("CM_C_" + component.Name, *this);
+
   EndElement("Feature");
 }
 
diff --git a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.h b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.h
index ee9c17a..368b250 100644
--- a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXFeaturesSourceWriter_h
 #define cmWIXFeaturesSourceWriter_h
 
+#include "cmWIXPatch.h"
 #include "cmWIXSourceWriter.h"
 
 #include <CPack/cmCPackGenerator.h>
@@ -23,14 +14,17 @@
 class cmWIXFeaturesSourceWriter : public cmWIXSourceWriter
 {
 public:
-  cmWIXFeaturesSourceWriter(cmCPackLog* logger, std::string const& filename);
+  cmWIXFeaturesSourceWriter(cmCPackLog* logger, std::string const& filename,
+                            GuidType componentGuidType);
 
   void CreateCMakePackageRegistryEntry(std::string const& package,
                                        std::string const& upgradeGuid);
 
-  void EmitFeatureForComponentGroup(const cmCPackComponentGroup& group);
+  void EmitFeatureForComponentGroup(const cmCPackComponentGroup& group,
+                                    cmWIXPatch& patch);
 
-  void EmitFeatureForComponent(const cmCPackComponent& component);
+  void EmitFeatureForComponent(const cmCPackComponent& component,
+                               cmWIXPatch& patch);
 
   void EmitComponentRef(std::string const& id);
 };
diff --git a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
index 1341fa5..a471d26 100644
--- a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
@@ -1,28 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXFilesSourceWriter.h"
 
 #include "cmWIXAccessControlList.h"
 
 #include <cmInstalledFile.h>
 
+#include <cmSystemTools.h>
+#include <cmUuid.h>
+
 #include <sys/types.h>
 // include sys/stat.h after sys/types.h
 #include <sys/stat.h>
 
 cmWIXFilesSourceWriter::cmWIXFilesSourceWriter(cmCPackLog* logger,
-                                               std::string const& filename)
-  : cmWIXSourceWriter(logger, filename)
+                                               std::string const& filename,
+                                               GuidType componentGuidType)
+  : cmWIXSourceWriter(logger, filename, componentGuidType)
 {
 }
 
@@ -31,7 +25,7 @@ void cmWIXFilesSourceWriter::EmitShortcut(std::string const& id,
                                           std::string const& shortcutPrefix,
                                           size_t shortcutIndex)
 {
-  std::stringstream shortcutId;
+  std::ostringstream shortcutId;
   shortcutId << shortcutPrefix << id;
 
   if (shortcutIndex > 0) {
@@ -126,12 +120,14 @@ std::string cmWIXFilesSourceWriter::EmitComponentFile(
   std::string componentId = std::string("CM_C") + id;
   std::string fileId = std::string("CM_F") + id;
 
+  std::string guid = CreateGuidFromComponentId(componentId);
+
   BeginElement("DirectoryRef");
   AddAttribute("Id", directoryId);
 
   BeginElement("Component");
   AddAttribute("Id", componentId);
-  AddAttribute("Guid", "*");
+  AddAttribute("Guid", guid);
 
   if (installedFile) {
     if (installedFile->GetPropertyAsBool("CPACK_NEVER_OVERWRITE")) {
diff --git a/Source/CPack/WiX/cmWIXFilesSourceWriter.h b/Source/CPack/WiX/cmWIXFilesSourceWriter.h
index c577e5b..d7a642d 100644
--- a/Source/CPack/WiX/cmWIXFilesSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXFilesSourceWriter_h
 #define cmWIXFilesSourceWriter_h
 
@@ -26,7 +16,8 @@
 class cmWIXFilesSourceWriter : public cmWIXSourceWriter
 {
 public:
-  cmWIXFilesSourceWriter(cmCPackLog* logger, std::string const& filename);
+  cmWIXFilesSourceWriter(cmCPackLog* logger, std::string const& filename,
+                         GuidType componentGuidType);
 
   void EmitShortcut(std::string const& id, cmWIXShortcut const& shortcut,
                     std::string const& shortcutPrefix, size_t shortcutIndex);
diff --git a/Source/CPack/WiX/cmWIXPatch.cxx b/Source/CPack/WiX/cmWIXPatch.cxx
index c9d010e..7c48653 100644
--- a/Source/CPack/WiX/cmWIXPatch.cxx
+++ b/Source/CPack/WiX/cmWIXPatch.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXPatch.h"
 
 #include <CPack/cmCPackGenerator.h>
diff --git a/Source/CPack/WiX/cmWIXPatch.h b/Source/CPack/WiX/cmWIXPatch.h
index 57b74cd..a4c9e71 100644
--- a/Source/CPack/WiX/cmWIXPatch.h
+++ b/Source/CPack/WiX/cmWIXPatch.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXPatch_h
 #define cmWIXPatch_h
 
diff --git a/Source/CPack/WiX/cmWIXPatchParser.cxx b/Source/CPack/WiX/cmWIXPatchParser.cxx
index b750dcf..47f98d1 100644
--- a/Source/CPack/WiX/cmWIXPatchParser.cxx
+++ b/Source/CPack/WiX/cmWIXPatchParser.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXPatchParser.h"
 
 #include <CPack/cmCPackGenerator.h>
@@ -88,7 +78,7 @@ void cmWIXPatchParser::StartFragment(const char** attributes)
 
     if (key == "Id") {
       if (Fragments.find(value) != Fragments.end()) {
-        std::stringstream tmp;
+        std::ostringstream tmp;
         tmp << "Invalid reuse of 'CPackWixFragment' 'Id': " << value;
         ReportValidationError(tmp.str());
       }
diff --git a/Source/CPack/WiX/cmWIXPatchParser.h b/Source/CPack/WiX/cmWIXPatchParser.h
index f9b85bd..a2f0a3c 100644
--- a/Source/CPack/WiX/cmWIXPatchParser.h
+++ b/Source/CPack/WiX/cmWIXPatchParser.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackWIXPatchParser_h
 #define cmCPackWIXPatchParser_h
 
diff --git a/Source/CPack/WiX/cmWIXRichTextFormatWriter.cxx b/Source/CPack/WiX/cmWIXRichTextFormatWriter.cxx
index f3dbcb9..d819347 100644
--- a/Source/CPack/WiX/cmWIXRichTextFormatWriter.cxx
+++ b/Source/CPack/WiX/cmWIXRichTextFormatWriter.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXRichTextFormatWriter.h"
 
 #include <cmVersion.h>
diff --git a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
index acf1fa6..b535979 100644
--- a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
+++ b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXRichTextFormatWriter_h
 #define cmWIXRichTextFormatWriter_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include <cmsys/FStream.hxx>
diff --git a/Source/CPack/WiX/cmWIXShortcut.cxx b/Source/CPack/WiX/cmWIXShortcut.cxx
index 2685a23..e5dea94 100644
--- a/Source/CPack/WiX/cmWIXShortcut.cxx
+++ b/Source/CPack/WiX/cmWIXShortcut.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXShortcut.h"
 
 #include "cmWIXFilesSourceWriter.h"
diff --git a/Source/CPack/WiX/cmWIXShortcut.h b/Source/CPack/WiX/cmWIXShortcut.h
index 593ba34..cba3b34 100644
--- a/Source/CPack/WiX/cmWIXShortcut.h
+++ b/Source/CPack/WiX/cmWIXShortcut.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXShortcut_h
 #define cmWIXShortcut_h
 
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.cxx b/Source/CPack/WiX/cmWIXSourceWriter.cxx
index 2c0384e..a8b0d7c 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXSourceWriter.cxx
@@ -1,32 +1,26 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWIXSourceWriter.h"
 
 #include <CPack/cmCPackGenerator.h>
 
+#include <cmUuid.h>
+
 #include <windows.h>
 
 cmWIXSourceWriter::cmWIXSourceWriter(cmCPackLog* logger,
                                      std::string const& filename,
-                                     bool isIncludeFile)
+                                     GuidType componentGuidType,
+                                     RootElementType rootElementType)
   : Logger(logger)
   , File(filename.c_str())
   , State(DEFAULT)
   , SourceFilename(filename)
+  , ComponentGuidType(componentGuidType)
 {
   WriteXMLDeclaration();
 
-  if (isIncludeFile) {
+  if (rootElementType == INCLUDE_ELEMENT_ROOT) {
     BeginElement("Include");
   } else {
     BeginElement("Wix");
@@ -173,6 +167,19 @@ std::string cmWIXSourceWriter::CMakeEncodingToUtf8(std::string const& value)
 #endif
 }
 
+std::string cmWIXSourceWriter::CreateGuidFromComponentId(
+  std::string const& componentId)
+{
+  std::string guid = "*";
+  if (this->ComponentGuidType == CMAKE_GENERATED_GUID) {
+    std::string md5 = cmSystemTools::ComputeStringMD5(componentId);
+    cmUuid uuid;
+    std::vector<unsigned char> ns;
+    guid = uuid.FromMd5(ns, md5);
+  }
+  return guid;
+}
+
 void cmWIXSourceWriter::WriteXMLDeclaration()
 {
   File << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.h b/Source/CPack/WiX/cmWIXSourceWriter.h
index 4efc026..b5c06ab 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXSourceWriter.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWIXSourceWriter_h
 #define cmWIXSourceWriter_h
 
@@ -26,8 +16,21 @@
 class cmWIXSourceWriter
 {
 public:
+  enum GuidType
+  {
+    WIX_GENERATED_GUID,
+    CMAKE_GENERATED_GUID
+  };
+
+  enum RootElementType
+  {
+    WIX_ELEMENT_ROOT,
+    INCLUDE_ELEMENT_ROOT
+  };
+
   cmWIXSourceWriter(cmCPackLog* logger, std::string const& filename,
-                    bool isIncludeFile = false);
+                    GuidType componentGuidType,
+                    RootElementType rootElementType = WIX_ELEMENT_ROOT);
 
   ~cmWIXSourceWriter();
 
@@ -45,6 +48,8 @@ public:
   void AddAttributeUnlessEmpty(std::string const& key,
                                std::string const& value);
 
+  std::string CreateGuidFromComponentId(std::string const& componentId);
+
   static std::string CMakeEncodingToUtf8(std::string const& value);
 
 protected:
@@ -70,6 +75,8 @@ private:
   std::vector<std::string> Elements;
 
   std::string SourceFilename;
+
+  GuidType ComponentGuidType;
 };
 
 #endif
diff --git a/Source/CPack/cmCPack7zGenerator.cxx b/Source/CPack/cmCPack7zGenerator.cxx
index b01c216..f0c41a2 100644
--- a/Source/CPack/cmCPack7zGenerator.cxx
+++ b/Source/CPack/cmCPack7zGenerator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPack7zGenerator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPack7zGenerator::cmCPack7zGenerator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressNone, "7zip")
 {
diff --git a/Source/CPack/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h
index f5a323f..063b032 100644
--- a/Source/CPack/cmCPack7zGenerator.h
+++ b/Source/CPack/cmCPack7zGenerator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPack7zGenerator_h
 #define cmCPack7zGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPack7zGenerator
  * \brief A generator for 7z files
@@ -27,10 +21,10 @@ public:
    * Construct generator
    */
   cmCPack7zGenerator();
-  virtual ~cmCPack7zGenerator();
+  ~cmCPack7zGenerator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".7z"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".7z"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx
index 7db20a4..9d9cd66 100644
--- a/Source/CPack/cmCPackArchiveGenerator.cxx
+++ b/Source/CPack/cmCPackArchiveGenerator.cxx
@@ -1,28 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackArchiveGenerator.h"
 
+#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
-#include <errno.h>
 
-#include <cm_libarchive.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/SystemTools.hxx>
+#include <map>
+#include <ostream>
+#include <utility>
+#include <vector>
 
 cmCPackArchiveGenerator::cmCPackArchiveGenerator(cmArchiveWrite::Compress t,
                                                  std::string const& format)
@@ -68,7 +57,7 @@ int cmCPackArchiveGenerator::addOneComponentToArchive(
        ++fileIt) {
     std::string rp = filePrefix + *fileIt;
     cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file: " << rp << std::endl);
-    archive.Add(rp, 0, 0, false);
+    archive.Add(rp, 0, CM_NULLPTR, false);
     if (!archive) {
       cmCPackLogger(cmCPackLog::LOG_ERROR, "ERROR while packaging files: "
                       << archive.GetError() << std::endl);
@@ -87,17 +76,17 @@ int cmCPackArchiveGenerator::addOneComponentToArchive(
  */
 #define DECLARE_AND_OPEN_ARCHIVE(filename, archive)                           \
   cmGeneratedFileStream gf;                                                   \
-  gf.Open(filename.c_str(), false, true);                                     \
+  gf.Open((filename).c_str(), false, true);                                   \
   if (!GenerateHeader(&gf)) {                                                 \
     cmCPackLogger(cmCPackLog::LOG_ERROR,                                      \
                   "Problem to generate Header for archive < "                 \
-                    << filename << ">." << std::endl);                        \
+                    << (filename) << ">." << std::endl);                      \
     return 0;                                                                 \
   }                                                                           \
   cmArchiveWrite archive(gf, this->Compress, this->ArchiveFormat);            \
-  if (!archive) {                                                             \
+  if (!(archive)) {                                                           \
     cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem to create archive < "       \
-                    << filename << ">. ERROR =" << archive.GetError()         \
+                    << (filename) << ">. ERROR =" << (archive).GetError()     \
                     << std::endl);                                            \
     return 0;                                                                 \
   }
@@ -139,7 +128,7 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup)
     for (compIt = this->Components.begin(); compIt != this->Components.end();
          ++compIt) {
       // Does the component belong to a group?
-      if (compIt->second.Group == NULL) {
+      if (compIt->second.Group == CM_NULLPTR) {
         cmCPackLogger(
           cmCPackLog::LOG_VERBOSE, "Component <"
             << compIt->second.Name
@@ -231,10 +220,8 @@ int cmCPackArchiveGenerator::PackageFiles()
     // 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.
-    else {
-      return PackageComponents(componentPackageMethod ==
-                               ONE_PACKAGE_PER_COMPONENT);
-    }
+    return PackageComponents(componentPackageMethod ==
+                             ONE_PACKAGE_PER_COMPONENT);
   }
 
   // CASE 3 : NON COMPONENT package.
@@ -246,7 +233,7 @@ int cmCPackArchiveGenerator::PackageFiles()
     // Get the relative path to the file
     std::string rp =
       cmSystemTools::RelativePath(toplevel.c_str(), fileIt->c_str());
-    archive.Add(rp, 0, 0, false);
+    archive.Add(rp, 0, CM_NULLPTR, false);
     if (!archive) {
       cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem while adding file< "
                       << *fileIt << "> to archive <" << packageFileNames[0]
@@ -259,7 +246,7 @@ int cmCPackArchiveGenerator::PackageFiles()
   return 1;
 }
 
-int cmCPackArchiveGenerator::GenerateHeader(std::ostream*)
+int cmCPackArchiveGenerator::GenerateHeader(std::ostream* /*unused*/)
 {
   return 1;
 }
@@ -269,9 +256,5 @@ bool cmCPackArchiveGenerator::SupportsComponentInstallation() const
   // The Component installation support should only
   // be activated if explicitly requested by the user
   // (for backward compatibility reason)
-  if (IsOn("CPACK_ARCHIVE_COMPONENT_INSTALL")) {
-    return true;
-  } else {
-    return false;
-  }
+  return IsOn("CPACK_ARCHIVE_COMPONENT_INSTALL");
 }
diff --git a/Source/CPack/cmCPackArchiveGenerator.h b/Source/CPack/cmCPackArchiveGenerator.h
index 9eb38b1..e960a6a 100644
--- a/Source/CPack/cmCPackArchiveGenerator.h
+++ b/Source/CPack/cmCPackArchiveGenerator.h
@@ -1,21 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackArchiveGenerator_h
 #define cmCPackArchiveGenerator_h
 
-#include "cmCPackGenerator.h"
+#include <cmConfigure.h>
 
 #include "cmArchiveWrite.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
+
+#include <iosfwd>
+#include <string>
+
+class cmCPackComponent;
 
 /** \class cmCPackArchiveGenerator
  * \brief A generator base for libarchive generation.
@@ -32,14 +29,14 @@ public:
    * Construct generator
    */
   cmCPackArchiveGenerator(cmArchiveWrite::Compress, std::string const& format);
-  virtual ~cmCPackArchiveGenerator();
+  ~cmCPackArchiveGenerator() CM_OVERRIDE;
   // Used to add a header to the archive
   virtual int GenerateHeader(std::ostream* os);
   // component support
-  virtual bool SupportsComponentInstallation() const;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
 protected:
-  virtual int InitializeInternal();
+  int InitializeInternal() CM_OVERRIDE;
   /**
    * Add the files belonging to the specified component
    * to the provided (already opened) archive.
@@ -55,7 +52,7 @@ protected:
    * method will call either PackageComponents or
    * PackageComponentsAllInOne.
    */
-  int PackageFiles();
+  int PackageFiles() CM_OVERRIDE;
   /**
    * The method used to package files when component
    * install is used. This will create one
@@ -67,7 +64,7 @@ protected:
    * components will be put in a single installer.
    */
   int PackageComponentsAllInOne();
-  virtual const char* GetOutputExtension() = 0;
+  const char* GetOutputExtension() CM_OVERRIDE = 0;
   cmArchiveWrite::Compress Compress;
   std::string ArchiveFormat;
 };
diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx
index 1164021..61d0127 100644
--- a/Source/CPack/cmCPackBundleGenerator.cxx
+++ b/Source/CPack/cmCPackBundleGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackBundleGenerator.h"
 
 #include "cmCPackLog.h"
@@ -232,12 +222,12 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
       temp_sign_file_cmd << this->GetOption("CPACK_APPLE_BUNDLE_ID");
       temp_sign_file_cmd << " \"";
       temp_sign_file_cmd << bundle_path;
-      temp_sign_file_cmd << it->c_str() << "\"";
+      temp_sign_file_cmd << *it << "\"";
 
       if (!this->RunCommand(temp_sign_file_cmd, &output)) {
-        cmCPackLogger(cmCPackLog::LOG_ERROR, "Error signing file:"
-                        << bundle_path << it->c_str() << std::endl
-                        << output << std::endl);
+        cmCPackLogger(cmCPackLog::LOG_ERROR,
+                      "Error signing file:" << bundle_path << *it << std::endl
+                                            << output << std::endl);
 
         return 0;
       }
diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h
index 9cb2f0a..9ea4304 100644
--- a/Source/CPack/cmCPackBundleGenerator.h
+++ b/Source/CPack/cmCPackBundleGenerator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackBundleGenerator_h
 #define cmCPackBundleGenerator_h
 
@@ -29,12 +19,12 @@ public:
   virtual ~cmCPackBundleGenerator();
 
 protected:
-  virtual int InitializeInternal();
-  virtual const char* GetPackagingInstallPrefix();
+  int InitializeInternal() CM_OVERRIDE;
+  const char* GetPackagingInstallPrefix() CM_OVERRIDE;
   int ConstructBundle();
   int SignBundle(const std::string& src_dir);
-  int PackageFiles();
-  bool SupportsComponentInstallation() const;
+  int PackageFiles() CM_OVERRIDE;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
   std::string InstallPrefix;
 };
diff --git a/Source/CPack/cmCPackComponentGroup.cxx b/Source/CPack/cmCPackComponentGroup.cxx
index d262ac9..e39398a 100644
--- a/Source/CPack/cmCPackComponentGroup.cxx
+++ b/Source/CPack/cmCPackComponentGroup.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackComponentGroup.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/CPack/cmCPackComponentGroup.h b/Source/CPack/cmCPackComponentGroup.h
index 5361d95..f955daf 100644
--- a/Source/CPack/cmCPackComponentGroup.h
+++ b/Source/CPack/cmCPackComponentGroup.h
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackComponentGroup_h
 #define cmCPackComponentGroup_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
+
+#include <string>
+#include <vector>
 
 class cmCPackComponentGroup;
 
@@ -43,7 +36,7 @@ class cmCPackComponent
 {
 public:
   cmCPackComponent()
-    : Group(0)
+    : Group(CM_NULLPTR)
     , IsRequired(true)
     , IsHidden(false)
     , IsDisabledByDefault(false)
@@ -117,7 +110,7 @@ class cmCPackComponentGroup
 {
 public:
   cmCPackComponentGroup()
-    : ParentGroup(0)
+    : ParentGroup(CM_NULLPTR)
   {
   }
 
diff --git a/Source/CPack/cmCPackConfigure.h.in b/Source/CPack/cmCPackConfigure.h.in
index 3d7702e..8ac1661 100644
--- a/Source/CPack/cmCPackConfigure.h.in
+++ b/Source/CPack/cmCPackConfigure.h.in
@@ -1,11 +1,2 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
index 83af89e..e67811d 100644
--- a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
+++ b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackCygwinBinaryGenerator.h"
 
 #include "cmCPackLog.h"
diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.h b/Source/CPack/cmCPackCygwinBinaryGenerator.h
index 8de4bae..58e80bd 100644
--- a/Source/CPack/cmCPackCygwinBinaryGenerator.h
+++ b/Source/CPack/cmCPackCygwinBinaryGenerator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackCygwinBinaryGenerator_h
 #define cmCPackCygwinBinaryGenerator_h
 
diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.cxx b/Source/CPack/cmCPackCygwinSourceGenerator.cxx
index 5fcfaf4..92475d9 100644
--- a/Source/CPack/cmCPackCygwinSourceGenerator.cxx
+++ b/Source/CPack/cmCPackCygwinSourceGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackCygwinSourceGenerator.h"
 
 #include "cmCPackLog.h"
diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.h b/Source/CPack/cmCPackCygwinSourceGenerator.h
index 4aba8b9..896de1d 100644
--- a/Source/CPack/cmCPackCygwinSourceGenerator.h
+++ b/Source/CPack/cmCPackCygwinSourceGenerator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackCygwinSourceGenerator_h
 #define cmCPackCygwinSourceGenerator_h
 
diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx
index 1ad4152..36566a4 100644
--- a/Source/CPack/cmCPackDebGenerator.cxx
+++ b/Source/CPack/cmCPackDebGenerator.cxx
@@ -1,28 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackDebGenerator.h"
 
 #include "cmArchiveWrite.h"
+#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
 
 #include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
-
-#include <limits.h> // USHRT_MAX
+#include <limits.h>
+#include <map>
+#include <ostream>
+#include <set>
+#include <stdio.h>
+#include <string.h>
 #include <sys/stat.h>
+#include <utility>
 
 // NOTE:
 // A debian package .deb is simply an 'ar' archive. The only subtle difference
@@ -57,9 +52,9 @@ int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel,
   // Begin the archive for this pack
   std::string localToplevel(initialTopLevel);
   std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
-  std::string outputFileName(std::string(
-                               this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
-                             "-" + packageName + this->GetOutputExtension());
+  std::string outputFileName(
+    std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + "-" +
+    packageName + this->GetOutputExtension());
 
   localToplevel += "/" + packageName;
   /* replace the TEMP DIRECTORY with the component one */
@@ -133,7 +128,7 @@ int cmCPackDebGenerator::PackageComponents(bool ignoreGroup)
     for (compIt = this->Components.begin(); compIt != this->Components.end();
          ++compIt) {
       // Does the component belong to a group?
-      if (compIt->second.Group == NULL) {
+      if (compIt->second.Group == CM_NULLPTR) {
         cmCPackLogger(
           cmCPackLog::LOG_VERBOSE, "Component <"
             << compIt->second.Name
@@ -174,9 +169,9 @@ int cmCPackDebGenerator::PackageComponentsAllInOne(
   // The ALL GROUPS in ONE package case
   std::string localToplevel(initialTopLevel);
   std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
-  std::string outputFileName(std::string(
-                               this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
-                             this->GetOutputExtension());
+  std::string outputFileName(
+    std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
+    this->GetOutputExtension());
   // all GROUP in one vs all COMPONENT in one
   localToplevel += "/" + compInstDirName;
 
@@ -242,15 +237,11 @@ int cmCPackDebGenerator::PackageFiles()
     // 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.
-    else {
-      return PackageComponents(componentPackageMethod ==
-                               ONE_PACKAGE_PER_COMPONENT);
-    }
+    return PackageComponents(componentPackageMethod ==
+                             ONE_PACKAGE_PER_COMPONENT);
   }
   // CASE 3 : NON COMPONENT package.
-  else {
-    return PackageComponentsAllInOne("");
-  }
+  return PackageComponentsAllInOne("");
 }
 
 int cmCPackDebGenerator::createDeb()
@@ -423,6 +414,12 @@ int cmCPackDebGenerator::createDeb()
                     << debian_compression_type << std::endl);
   }
 
+  const char* debian_archive_type =
+    this->GetOption("GEN_CPACK_DEBIAN_ARCHIVE_TYPE");
+  if (!debian_archive_type) {
+    debian_archive_type = "paxr";
+  }
+
   std::string filename_data_tar =
     strGenWDIR + "/data.tar" + compression_suffix;
 
@@ -435,7 +432,8 @@ int cmCPackDebGenerator::createDeb()
                       << filename_data_tar << "\" for writing" << std::endl);
       return 0;
     }
-    cmArchiveWrite data_tar(fileStream_data_tar, tar_compression_type, "paxr");
+    cmArchiveWrite data_tar(fileStream_data_tar, tar_compression_type,
+                            debian_archive_type);
 
     // uid/gid should be the one of the root user, and this root user has
     // always uid/gid equal to 0.
@@ -539,7 +537,8 @@ int cmCPackDebGenerator::createDeb()
       return 0;
     }
     cmArchiveWrite control_tar(fileStream_control_tar,
-                               cmArchiveWrite::CompressGZip, "paxr");
+                               cmArchiveWrite::CompressGZip,
+                               debian_archive_type);
 
     // sets permissions and uid/gid for the files
     control_tar.SetUIDAndGID(0u, 0u);
@@ -675,11 +674,7 @@ int cmCPackDebGenerator::createDeb()
 
 bool cmCPackDebGenerator::SupportsComponentInstallation() const
 {
-  if (IsOn("CPACK_DEB_COMPONENT_INSTALL")) {
-    return true;
-  } else {
-    return false;
-  }
+  return IsOn("CPACK_DEB_COMPONENT_INSTALL");
 }
 
 std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
@@ -696,11 +691,10 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
   // the current COMPONENT belongs to.
   std::string groupVar =
     "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
-  if (NULL != GetOption(groupVar)) {
+  if (CM_NULLPTR != GetOption(groupVar)) {
     return std::string(GetOption(groupVar));
-  } else {
-    return componentName;
   }
+  return componentName;
 }
 
 // The following code is taken from OpenBSD ar:
@@ -744,14 +738,6 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
  * SUCH DAMAGE.
  */
 
-#include <sys/types.h>
-// include sys/stat.h after sys/types.h
-#include <sys/stat.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
 #define ARMAG "!<arch>\n" /* ar "magic number" */
 #define SARMAG 8          /* strlen(ARMAG); */
 
@@ -830,8 +816,9 @@ static int copy_ar(CF* cfp, off_t size)
   size_t nr, nw;
   char buf[8 * 1024];
 
-  if (sz == 0)
+  if (sz == 0) {
     return 0;
+  }
 
   FILE* from = cfp->rFile;
   FILE* to = cfp->wFile;
@@ -841,16 +828,20 @@ static int copy_ar(CF* cfp, off_t size)
                        : sizeof(buf),
                      from)) > 0) {
     sz -= nr;
-    for (size_t off = 0; off < nr; nr -= off, off += nw)
-      if ((nw = fwrite(buf + off, 1, nr, to)) < nr)
+    for (size_t off = 0; off < nr; nr -= off, off += nw) {
+      if ((nw = fwrite(buf + off, 1, nr, to)) < nr) {
         return -1;
+      }
+    }
   }
-  if (sz)
+  if (sz) {
     return -2;
+  }
 
   if (cfp->flags & WPAD && (size + ar_already_written) & 1 &&
-      fwrite(&pad, 1, 1, to) != 1)
+      fwrite(&pad, 1, 1, to) != 1) {
     return -4;
+  }
 
   return 0;
 }
@@ -878,11 +869,11 @@ static int put_arobj(CF* cfp, struct stat* sb)
   if (gid > USHRT_MAX) {
     gid = USHRT_MAX;
   }
-  if (lname > sizeof(hdr->ar_name) || strchr(name, ' '))
+  if (lname > sizeof(hdr->ar_name) || strchr(name, ' ')) {
     (void)sprintf(ar_hb, HDR1, AR_EFMT1, (int)lname, (long int)sb->st_mtime,
                   (unsigned)uid, (unsigned)gid, (unsigned)sb->st_mode,
                   (long long)sb->st_size + lname, ARFMAG);
-  else {
+  } else {
     lname = 0;
     (void)sprintf(ar_hb, HDR2, name, (long int)sb->st_mtime, (unsigned)uid,
                   (unsigned)gid, (unsigned)sb->st_mode, (long long)sb->st_size,
@@ -890,12 +881,14 @@ static int put_arobj(CF* cfp, struct stat* sb)
   }
   off_t size = sb->st_size;
 
-  if (fwrite(ar_hb, 1, sizeof(HDR), cfp->wFile) != sizeof(HDR))
+  if (fwrite(ar_hb, 1, sizeof(HDR), cfp->wFile) != sizeof(HDR)) {
     return -1;
+  }
 
   if (lname) {
-    if (fwrite(name, 1, lname, cfp->wFile) != lname)
+    if (fwrite(name, 1, lname, cfp->wFile) != lname) {
       return -2;
+    }
     ar_already_written = lname;
   }
   result = copy_ar(cfp, size);
@@ -914,18 +907,18 @@ static int ar_append(const char* archive,
 {
   int eval = 0;
   FILE* aFile = cmSystemTools::Fopen(archive, "wb+");
-  if (aFile != NULL) {
+  if (aFile != CM_NULLPTR) {
     fwrite(ARMAG, SARMAG, 1, aFile);
     if (fseek(aFile, 0, SEEK_END) != -1) {
       CF cf;
       struct stat sb;
       /* Read from disk, write to an archive; pad on write. */
-      SETCF(NULL, 0, aFile, archive, WPAD);
+      SETCF(CM_NULLPTR, CM_NULLPTR, aFile, archive, WPAD);
       for (std::vector<std::string>::const_iterator fileIt = files.begin();
            fileIt != files.end(); ++fileIt) {
         const char* filename = fileIt->c_str();
         FILE* file = cmSystemTools::Fopen(filename, "rb");
-        if (file == NULL) {
+        if (file == CM_NULLPTR) {
           eval = -1;
           continue;
         }
diff --git a/Source/CPack/cmCPackDebGenerator.h b/Source/CPack/cmCPackDebGenerator.h
index ff34ca5..f46ae5a 100644
--- a/Source/CPack/cmCPackDebGenerator.h
+++ b/Source/CPack/cmCPackDebGenerator.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackDebGenerator_h
 #define cmCPackDebGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
 
 /** \class cmCPackDebGenerator
  * \brief A generator for Debian packages
@@ -28,7 +24,7 @@ public:
    * Construct generator
    */
   cmCPackDebGenerator();
-  virtual ~cmCPackDebGenerator();
+  ~cmCPackDebGenerator() CM_OVERRIDE;
 
   static bool CanGenerate()
   {
@@ -45,7 +41,7 @@ public:
   }
 
 protected:
-  virtual int InitializeInternal();
+  int InitializeInternal() CM_OVERRIDE;
   /**
    * This method factors out the work done in component packaging case.
    */
@@ -62,11 +58,11 @@ protected:
    * components will be put in a single installer.
    */
   int PackageComponentsAllInOne(const std::string& compInstDirName);
-  virtual int PackageFiles();
-  virtual const char* GetOutputExtension() { return ".deb"; }
-  virtual bool SupportsComponentInstallation() const;
-  virtual std::string GetComponentInstallDirNameSuffix(
-    const std::string& componentName);
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".deb"; }
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
+  std::string GetComponentInstallDirNameSuffix(
+    const std::string& componentName) CM_OVERRIDE;
 
 private:
   int createDeb();
diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx
index f4379c1..bdf4076 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.cxx
+++ b/Source/CPack/cmCPackDragNDropGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackDragNDropGenerator.h"
 
 #include "cmCPackLog.h"
@@ -235,7 +225,7 @@ bool cmCPackDragNDropGenerator::CreateEmptyFile(std::ostringstream& target,
     return false;
   } else {
     // Seek to desired size - 1 byte
-    fout.seekp(size - 1, std::ios_base::beg);
+    fout.seekp(size - 1, std::ios::beg);
     char byte = 0;
     // Write one byte to ensure file grows
     fout.write(&byte, 1);
@@ -330,8 +320,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
   if (!cpack_dmg_disable_applications_symlink) {
     std::ostringstream application_link;
     application_link << staging.str() << "/Applications";
-    cmSystemTools::CreateSymlink("/Applications",
-                                 application_link.str().c_str());
+    cmSystemTools::CreateSymlink("/Applications", application_link.str());
   }
 
   // Optionally add a custom volume icon ...
@@ -755,7 +744,7 @@ std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
     // the current COMPONENT belongs to.
     std::string groupVar =
       "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
-    const char* _groupName = GetOption(groupVar.c_str());
+    const char* _groupName = GetOption(groupVar);
     if (_groupName) {
       std::string groupName = _groupName;
 
diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h
index 1392b21..f803ad9 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.h
+++ b/Source/CPack/cmCPackDragNDropGenerator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackDragNDropGenerator_h
 #define cmCPackDragNDropGenerator_h
 
@@ -29,17 +19,17 @@ public:
   virtual ~cmCPackDragNDropGenerator();
 
 protected:
-  virtual int InitializeInternal();
-  virtual const char* GetOutputExtension();
-  int PackageFiles();
-  bool SupportsComponentInstallation() const;
+  int InitializeInternal() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
   bool CopyFile(std::ostringstream& source, std::ostringstream& target);
   bool CreateEmptyFile(std::ostringstream& target, size_t size);
   bool RunCommand(std::ostringstream& command, std::string* output = 0);
 
   std::string GetComponentInstallDirNameSuffix(
-    const std::string& componentName);
+    const std::string& componentName) CM_OVERRIDE;
 
   int CreateDMG(const std::string& src_dir, const std::string& output_file);
 
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index f46d145..d4135ce 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -1,30 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackGenerator.h"
 
 #include "cmCPackComponentGroup.h"
 #include "cmCPackLog.h"
+#include "cmCryptoHash.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 #include "cmXMLSafe.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
 #include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
+#include <cmsys/RegularExpression.hxx>
 #include <list>
+#include <utility>
 
 #if defined(__HAIKU__)
 #include <FindDirectory.h>
@@ -34,14 +28,14 @@
 cmCPackGenerator::cmCPackGenerator()
 {
   this->GeneratorVerbose = cmSystemTools::OUTPUT_NONE;
-  this->MakefileMap = 0;
-  this->Logger = 0;
+  this->MakefileMap = CM_NULLPTR;
+  this->Logger = CM_NULLPTR;
   this->componentPackageMethod = ONE_PACKAGE_PER_GROUP;
 }
 
 cmCPackGenerator::~cmCPackGenerator()
 {
-  this->MakefileMap = 0;
+  this->MakefileMap = CM_NULLPTR;
 }
 
 void cmCPackGeneratorProgress(const char* msg, float prog, void* ptr)
@@ -67,7 +61,8 @@ int cmCPackGenerator::PrepareNames()
         cmCPackLog::LOG_ERROR, "CPACK_SET_DESTDIR is set to ON but the '"
           << Name << "' generator does NOT support it." << std::endl);
       return 0;
-    } else if (SETDESTDIR_SHOULD_NOT_BE_USED == SupportsSetDestdir()) {
+    }
+    if (SETDESTDIR_SHOULD_NOT_BE_USED == SupportsSetDestdir()) {
       cmCPackLogger(cmCPackLog::LOG_WARNING,
                     "CPACK_SET_DESTDIR is set to ON but it is "
                       << "usually a bad idea to do that with '" << Name
@@ -159,6 +154,14 @@ int cmCPackGenerator::PrepareNames()
         << std::endl);
     return 0;
   }
+  const char* algoSignature = this->GetOption("CPACK_PACKAGE_CHECKSUM");
+  if (algoSignature) {
+    if (cmCryptoHash::New(algoSignature).get() == CM_NULLPTR) {
+      cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot recognize algorithm: "
+                      << algoSignature << std::endl);
+      return 0;
+    }
+  }
 
   this->SetOptionIfNotSet("CPACK_REMOVE_TOPLEVEL_DIRECTORY", "1");
 
@@ -251,8 +254,9 @@ int cmCPackGenerator::InstallProjectViaInstallCommands(
       cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << *it << std::endl);
       std::string output;
       int retVal = 1;
-      bool resB = cmSystemTools::RunSingleCommand(
-        it->c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+      bool resB =
+        cmSystemTools::RunSingleCommand(it->c_str(), &output, &output, &retVal,
+                                        CM_NULLPTR, this->GeneratorVerbose, 0);
       if (!resB || retVal) {
         std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
         tmpFile += "/InstallOutput.log";
@@ -623,7 +627,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
         cm.AddCMakePaths();
         cm.SetProgressCallback(cmCPackGeneratorProgress, this);
         cmGlobalGenerator gg(&cm);
-        cmsys::auto_ptr<cmMakefile> mf(
+        CM_AUTO_PTR<cmMakefile> mf(
           new cmMakefile(&gg, cm.GetCurrentSnapshot()));
         if (!installSubDirectory.empty() && installSubDirectory != "/" &&
             installSubDirectory != ".") {
@@ -815,7 +819,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
           }
         }
 
-        if (NULL != mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
+        if (CM_NULLPTR !=
+            mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
           if (!absoluteDestFiles.empty()) {
             absoluteDestFiles += ";";
           }
@@ -829,7 +834,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
             std::string absoluteDestFileComponent =
               std::string("CPACK_ABSOLUTE_DESTINATION_FILES") + "_" +
               GetComponentInstallDirNameSuffix(installComponent);
-            if (NULL != this->GetOption(absoluteDestFileComponent)) {
+            if (CM_NULLPTR != this->GetOption(absoluteDestFileComponent)) {
               std::string absoluteDestFilesListComponent =
                 this->GetOption(absoluteDestFileComponent);
               absoluteDestFilesListComponent += ";";
@@ -974,6 +979,10 @@ int cmCPackGenerator::DoPackage()
     return 0;
   }
 
+  /* Prepare checksum algorithm*/
+  const char* algo = this->GetOption("CPACK_PACKAGE_CHECKSUM");
+  CM_AUTO_PTR<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : "");
+
   /*
    * Copy the generated packages to final destination
    *  - there may be several of them
@@ -986,8 +995,9 @@ int cmCPackGenerator::DoPackage()
   /* now copy package one by one */
   for (it = packageFileNames.begin(); it != packageFileNames.end(); ++it) {
     std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
+    std::string filename(cmSystemTools::GetFilenameName(*it));
     tempPackageFileName = it->c_str();
-    tmpPF += "/" + cmSystemTools::GetFilenameName(*it);
+    tmpPF += "/" + filename;
     const char* packageFileName = tmpPF.c_str();
     cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy final package(s): "
                     << (tempPackageFileName ? tempPackageFileName : "(NULL)")
@@ -1003,6 +1013,23 @@ int cmCPackGenerator::DoPackage()
     }
     cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- package: "
                     << packageFileName << " generated." << std::endl);
+
+    /* Generate checksum file */
+    if (crypto.get() != CM_NULLPTR) {
+      std::string hashFile(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
+      hashFile +=
+        "/" + filename.substr(0, filename.rfind(this->GetOutputExtension()));
+      hashFile += "." + cmSystemTools::LowerCase(algo);
+      cmsys::ofstream outF(hashFile.c_str());
+      if (!outF) {
+        cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create checksum file: "
+                        << hashFile << std::endl);
+        return 0;
+      }
+      outF << crypto->HashFile(packageFileName) << "  " << filename << "\n";
+      cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- checksum file: "
+                      << hashFile << " generated." << std::endl);
+    }
   }
 
   return 1;
@@ -1073,11 +1100,11 @@ const char* cmCPackGenerator::GetInstallPath()
     return this->InstallPath.c_str();
   }
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  const char* prgfiles = cmsys::SystemTools::GetEnv("ProgramFiles");
-  const char* sysDrive = cmsys::SystemTools::GetEnv("SystemDrive");
-  if (prgfiles) {
+  std::string prgfiles;
+  std::string sysDrive;
+  if (cmsys::SystemTools::GetEnv("ProgramFiles", prgfiles)) {
     this->InstallPath = prgfiles;
-  } else if (sysDrive) {
+  } else if (cmsys::SystemTools::GetEnv("SystemDrive", sysDrive)) {
     this->InstallPath = sysDrive;
     this->InstallPath += "/Program Files";
   } else {
@@ -1179,7 +1206,7 @@ int cmCPackGenerator::PrepareGroupingKind()
   std::string groupingType;
 
   // Second way to specify grouping
-  if (NULL != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
+  if (CM_NULLPTR != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
     groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING");
   }
 
@@ -1356,7 +1383,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
       component->Group = GetComponentGroup(projectName, groupName);
       component->Group->Components.push_back(component);
     } else {
-      component->Group = 0;
+      component->Group = CM_NULLPTR;
     }
 
     const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
@@ -1424,7 +1451,7 @@ cmCPackComponentGroup* cmCPackGenerator::GetComponentGroup(
       group->ParentGroup = GetComponentGroup(projectName, parentGroupName);
       group->ParentGroup->Subgroups.push_back(group);
     } else {
-      group->ParentGroup = 0;
+      group->ParentGroup = CM_NULLPTR;
     }
   }
   return group;
diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h
index ce93715..9232ffc 100644
--- a/Source/CPack/cmCPackGenerator.h
+++ b/Source/CPack/cmCPackGenerator.h
@@ -1,27 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackGenerator_h
 #define cmCPackGenerator_h
 
-#include "cmObject.h"
+#include <cmConfigure.h>
 
+#include "cmCPackComponentGroup.h"
+#include "cmObject.h"
 #include "cmSystemTools.h"
+#include "cmTypeMacro.h"
+
 #include <map>
+#include <sstream>
+#include <string>
 #include <vector>
 
-#include "cmCPackComponentGroup.h" // cmCPackComponent and friends
-// Forward declarations are insufficient since we use them in
-// std::map data members below...
+class cmCPackLog;
+class cmInstalledFile;
+class cmMakefile;
 
 #define cmCPackTypeMacro(klass, superclass)                                   \
   cmTypeMacro(klass, superclass);                                             \
@@ -46,10 +42,6 @@
 #endif
 #define cout no_cout_use_cmCPack_Log
 
-class cmMakefile;
-class cmCPackLog;
-class cmInstalledFile;
-
 /** \class cmCPackGenerator
  * \brief A superclass of all CPack Generators
  *
@@ -101,7 +93,7 @@ public:
    * Construct generator
    */
   cmCPackGenerator();
-  virtual ~cmCPackGenerator();
+  ~cmCPackGenerator() CM_OVERRIDE;
 
   //! Set and get the options
   void SetOption(const std::string& op, const char* value);
@@ -136,7 +128,7 @@ protected:
   cmInstalledFile const* GetInstalledFile(std::string const& name) const;
 
   virtual const char* GetOutputExtension() { return ".cpack"; }
-  virtual const char* GetOutputPostfix() { return 0; }
+  virtual const char* GetOutputPostfix() { return CM_NULLPTR; }
 
   /**
    * Prepare requested grouping kind from CPACK_xxx vars
diff --git a/Source/CPack/cmCPackGeneratorFactory.cxx b/Source/CPack/cmCPackGeneratorFactory.cxx
index b17f52e..2a0e65b 100644
--- a/Source/CPack/cmCPackGeneratorFactory.cxx
+++ b/Source/CPack/cmCPackGeneratorFactory.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackGeneratorFactory.h"
 
 #include "IFW/cmCPackIFWGenerator.h"
@@ -28,6 +18,7 @@
 #include "cmCPackDragNDropGenerator.h"
 #include "cmCPackOSXX11Generator.h"
 #include "cmCPackPackageMakerGenerator.h"
+#include "cmCPackProductBuildGenerator.h"
 #endif
 
 #ifdef __CYGWIN__
@@ -48,6 +39,9 @@
 #include "cmAlgorithms.h"
 #include "cmCPackLog.h"
 
+#include <ostream>
+#include <utility>
+
 cmCPackGeneratorFactory::cmCPackGeneratorFactory()
 {
   if (cmCPackTGZGenerator::CanGenerate()) {
@@ -122,6 +116,10 @@ cmCPackGeneratorFactory::cmCPackGeneratorFactory()
     this->RegisterGenerator("OSXX11", "Mac OSX X11 bundle",
                             cmCPackOSXX11Generator::CreateGenerator);
   }
+  if (cmCPackProductBuildGenerator::CanGenerate()) {
+    this->RegisterGenerator("productbuild", "Mac OSX pkg",
+                            cmCPackProductBuildGenerator::CreateGenerator);
+  }
 #endif
 #if !defined(_WIN32) && !defined(__QNXNTO__) && !defined(__BEOS__) &&         \
   !defined(__HAIKU__)
@@ -146,7 +144,7 @@ cmCPackGenerator* cmCPackGeneratorFactory::NewGenerator(
 {
   cmCPackGenerator* gen = this->NewGeneratorInternal(name);
   if (!gen) {
-    return 0;
+    return CM_NULLPTR;
   }
   this->Generators.push_back(gen);
   gen->SetLogger(this->Logger);
@@ -159,7 +157,7 @@ cmCPackGenerator* cmCPackGeneratorFactory::NewGeneratorInternal(
   cmCPackGeneratorFactory::t_GeneratorCreatorsMap::iterator it =
     this->GeneratorCreators.find(name);
   if (it == this->GeneratorCreators.end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return (it->second)();
 }
diff --git a/Source/CPack/cmCPackGeneratorFactory.h b/Source/CPack/cmCPackGeneratorFactory.h
index a55ec6e..145867e 100644
--- a/Source/CPack/cmCPackGeneratorFactory.h
+++ b/Source/CPack/cmCPackGeneratorFactory.h
@@ -1,22 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackGeneratorFactory_h
 #define cmCPackGeneratorFactory_h
 
+#include <cmConfigure.h>
+
 #include "cmObject.h"
+#include "cmTypeMacro.h"
+
+#include <map>
+#include <string>
+#include <vector>
 
-class cmCPackLog;
 class cmCPackGenerator;
+class cmCPackLog;
 
 /** \class cmCPackGeneratorFactory
  * \brief A container for CPack generators
@@ -28,7 +25,7 @@ public:
   cmTypeMacro(cmCPackGeneratorFactory, cmObject);
 
   cmCPackGeneratorFactory();
-  ~cmCPackGeneratorFactory();
+  ~cmCPackGeneratorFactory() CM_OVERRIDE;
 
   //! Get the generator
   cmCPackGenerator* NewGenerator(const std::string& name);
diff --git a/Source/CPack/cmCPackLog.cxx b/Source/CPack/cmCPackLog.cxx
index ff06eb8..be429fe 100644
--- a/Source/CPack/cmCPackLog.cxx
+++ b/Source/CPack/cmCPackLog.cxx
@@ -1,20 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackLog.h"
 
 #include "cmGeneratedFileStream.h"
 #include "cmSystemTools.h"
 
+#include <iostream>
+
 cmCPackLog::cmCPackLog()
 {
   this->Verbose = false;
@@ -28,13 +20,13 @@ cmCPackLog::cmCPackLog()
   this->DefaultOutput = &std::cout;
   this->DefaultError = &std::cerr;
 
-  this->LogOutput = 0;
+  this->LogOutput = CM_NULLPTR;
   this->LogOutputCleanup = false;
 }
 
 cmCPackLog::~cmCPackLog()
 {
-  this->SetLogOutputStream(0);
+  this->SetLogOutputStream(CM_NULLPTR);
 }
 
 void cmCPackLog::SetLogOutputStream(std::ostream* os)
@@ -48,13 +40,13 @@ void cmCPackLog::SetLogOutputStream(std::ostream* os)
 
 bool cmCPackLog::SetLogOutputFile(const char* fname)
 {
-  cmGeneratedFileStream* cg = 0;
+  cmGeneratedFileStream* cg = CM_NULLPTR;
   if (fname) {
     cg = new cmGeneratedFileStream(fname);
   }
   if (cg && !*cg) {
     delete cg;
-    cg = 0;
+    cg = CM_NULLPTR;
   }
   this->SetLogOutputStream(cg);
   if (!cg) {
diff --git a/Source/CPack/cmCPackLog.h b/Source/CPack/cmCPackLog.h
index 41871cc..0831843 100644
--- a/Source/CPack/cmCPackLog.h
+++ b/Source/CPack/cmCPackLog.h
@@ -1,19 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackLog_h
 #define cmCPackLog_h
 
+#include <cmConfigure.h>
+
 #include "cmObject.h"
+#include "cmTypeMacro.h"
+
+#include <ostream>
+#include <string.h>
+#include <string>
 
 #define cmCPack_Log(ctSelf, logType, msg)                                     \
   do {                                                                        \
@@ -42,7 +39,7 @@ public:
   cmTypeMacro(cmCPackLog, cmObject);
 
   cmCPackLog();
-  ~cmCPackLog();
+  ~cmCPackLog() CM_OVERRIDE;
 
   enum __log_tags
   {
diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx
index 9fa588d..2c9ca63 100644
--- a/Source/CPack/cmCPackNSISGenerator.cxx
+++ b/Source/CPack/cmCPackNSISGenerator.cxx
@@ -1,28 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackNSISGenerator.h"
 
 #include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
 
+#include <algorithm>
 #include <cmsys/Directory.hxx>
-#include <cmsys/Glob.hxx>
 #include <cmsys/RegularExpression.hxx>
-#include <cmsys/SystemTools.hxx>
+#include <map>
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
 
 /* NSIS uses different command line syntax on Windows and others */
 #ifdef _WIN32
@@ -68,14 +61,26 @@ int cmCPackNSISGenerator::PackageFiles()
   std::ostringstream str;
   std::vector<std::string>::const_iterator it;
   for (it = files.begin(); it != files.end(); ++it) {
+    std::string outputDir = "$INSTDIR";
     std::string fileN =
       cmSystemTools::RelativePath(toplevel.c_str(), it->c_str());
     if (!this->Components.empty()) {
+      const std::string::size_type pos = fileN.find('/');
+
+      // Use the custom component install directory if we have one
+      if (pos != std::string::npos) {
+        const std::string componentName = fileN.substr(0, pos);
+        outputDir = CustomComponentInstallDirectory(componentName);
+      } else {
+        outputDir = CustomComponentInstallDirectory(fileN);
+      }
+
       // Strip off the component part of the path.
-      fileN = fileN.substr(fileN.find('/') + 1, std::string::npos);
+      fileN = fileN.substr(pos + 1, std::string::npos);
     }
     std::replace(fileN.begin(), fileN.end(), '/', '\\');
-    str << "  Delete \"$INSTDIR\\" << fileN << "\"" << std::endl;
+
+    str << "  Delete \"" << outputDir << "\\" << fileN << "\"" << std::endl;
   }
   cmCPackLogger(cmCPackLog::LOG_DEBUG, "Uninstall Files: " << str.str()
                                                            << std::endl);
@@ -105,7 +110,12 @@ int cmCPackNSISGenerator::PackageFiles()
       }
     }
     std::replace(fileN.begin(), fileN.end(), '/', '\\');
-    dstr << "  RMDir \"$INSTDIR\\" << fileN << "\"" << std::endl;
+
+    const std::string componentOutputDir =
+      CustomComponentInstallDirectory(componentName);
+
+    dstr << "  RMDir \"" << componentOutputDir << "\\" << fileN << "\""
+         << std::endl;
     if (!componentName.empty()) {
       this->Components[componentName].Directories.push_back(fileN);
     }
@@ -212,7 +222,7 @@ int cmCPackNSISGenerator::PackageFiles()
     std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
     for (groupIt = this->ComponentGroups.begin();
          groupIt != this->ComponentGroups.end(); ++groupIt) {
-      if (groupIt->second.ParentGroup == 0) {
+      if (groupIt->second.ParentGroup == CM_NULLPTR) {
         componentCode +=
           this->CreateComponentGroupDescription(&groupIt->second, macrosOut);
       }
@@ -301,8 +311,9 @@ int cmCPackNSISGenerator::PackageFiles()
   cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << nsisCmd << std::endl);
   std::string output;
   int retVal = 1;
-  bool res = cmSystemTools::RunSingleCommand(
-    nsisCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+  bool res =
+    cmSystemTools::RunSingleCommand(nsisCmd.c_str(), &output, &output, &retVal,
+                                    CM_NULLPTR, this->GeneratorVerbose, 0);
   if (!res || retVal) {
     cmGeneratedFileStream ofs(tmpFile.c_str());
     ofs << "# Run command: " << nsisCmd << std::endl
@@ -326,7 +337,7 @@ int cmCPackNSISGenerator::InitializeInternal()
       "NSIS Generator cannot work with CPACK_INCLUDE_TOPLEVEL_DIRECTORY set. "
       "This option will be reset to 0 (for this generator only)."
         << std::endl);
-    this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", 0);
+    this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", CM_NULLPTR);
   }
 
   cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackNSISGenerator::Initialize()"
@@ -399,8 +410,9 @@ int cmCPackNSISGenerator::InitializeInternal()
                                                                << std::endl);
   std::string output;
   int retVal = 1;
-  bool resS = cmSystemTools::RunSingleCommand(
-    nsisCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+  bool resS =
+    cmSystemTools::RunSingleCommand(nsisCmd.c_str(), &output, &output, &retVal,
+                                    CM_NULLPTR, this->GeneratorVerbose, 0);
   cmsys::RegularExpression versionRex("v([0-9]+.[0-9]+)");
   cmsys::RegularExpression versionRexCVS("v(.*)\\.cvs");
   if (!resS || retVal ||
@@ -516,8 +528,8 @@ int cmCPackNSISGenerator::InitializeInternal()
   return this->Superclass::InitializeInternal();
 }
 
-void cmCPackNSISGenerator::CreateMenuLinks(std::ostringstream& str,
-                                           std::ostringstream& deleteStr)
+void cmCPackNSISGenerator::CreateMenuLinks(std::ostream& str,
+                                           std::ostream& deleteStr)
 {
   const char* cpackMenuLinks = this->GetOption("CPACK_NSIS_MENU_LINKS");
   if (!cpackMenuLinks) {
@@ -621,7 +633,7 @@ bool cmCPackNSISGenerator::SupportsComponentInstallation() const
 }
 
 std::string cmCPackNSISGenerator::CreateComponentDescription(
-  cmCPackComponent* component, std::ostringstream& macrosOut)
+  cmCPackComponent* component, std::ostream& macrosOut)
 {
   // Basic description of the component
   std::string componentCode = "Section ";
@@ -645,7 +657,10 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
     }
     componentCode += "  SectionIn" + out.str() + "\n";
   }
-  componentCode += "  SetOutPath \"$INSTDIR\"\n";
+
+  const std::string componentOutputDir =
+    CustomComponentInstallDirectory(component->Name);
+  componentCode += "  SetOutPath \"" + componentOutputDir + "\"\n";
 
   // Create the actual installation commands
   if (component->IsDownloaded) {
@@ -791,13 +806,13 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
        ++pathIt) {
     path = *pathIt;
     std::replace(path.begin(), path.end(), '/', '\\');
-    macrosOut << "  Delete \"$INSTDIR\\" << path << "\"\n";
+    macrosOut << "  Delete \"" << componentOutputDir << "\\" << path << "\"\n";
   }
   for (pathIt = component->Directories.begin();
        pathIt != component->Directories.end(); ++pathIt) {
     path = *pathIt;
     std::replace(path.begin(), path.end(), '/', '\\');
-    macrosOut << "  RMDir \"$INSTDIR\\" << path << "\"\n";
+    macrosOut << "  RMDir \"" << componentOutputDir << "\\" << path << "\"\n";
   }
   macrosOut << "  noremove_" << component->Name << ":\n";
   macrosOut << "!macroend\n";
@@ -873,7 +888,7 @@ std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription(
 }
 
 std::string cmCPackNSISGenerator::CreateComponentGroupDescription(
-  cmCPackComponentGroup* group, std::ostringstream& macrosOut)
+  cmCPackComponentGroup* group, std::ostream& macrosOut)
 {
   if (group->Components.empty() && group->Subgroups.empty()) {
     // Silently skip empty groups. NSIS doesn't support them.
@@ -909,6 +924,15 @@ std::string cmCPackNSISGenerator::CreateComponentGroupDescription(
   return code;
 }
 
+std::string cmCPackNSISGenerator::CustomComponentInstallDirectory(
+  const std::string& componentName)
+{
+  const char* outputDir =
+    this->GetOption("CPACK_NSIS_" + componentName + "_INSTALL_DIRECTORY");
+  const std::string componentOutputDir = (outputDir ? outputDir : "$INSTDIR");
+  return componentOutputDir;
+}
+
 std::string cmCPackNSISGenerator::TranslateNewlines(std::string str)
 {
   cmSystemTools::ReplaceString(str, "\n", "$\\r$\\n");
diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h
index fa52902..d61341c 100644
--- a/Source/CPack/cmCPackNSISGenerator.h
+++ b/Source/CPack/cmCPackNSISGenerator.h
@@ -1,21 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackNSISGenerator_h
 #define cmCPackNSISGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
+#include <iosfwd>
 #include <set>
+#include <string>
+#include <vector>
+
+class cmCPackComponent;
+class cmCPackComponentGroup;
 
 /** \class cmCPackNSISGenerator
  * \brief A generator for NSIS files
@@ -36,27 +35,28 @@ public:
    * Construct generator
    */
   cmCPackNSISGenerator(bool nsis64 = false);
-  virtual ~cmCPackNSISGenerator();
+  ~cmCPackNSISGenerator() CM_OVERRIDE;
 
 protected:
-  virtual int InitializeInternal();
-  void CreateMenuLinks(std::ostringstream& str, std::ostringstream& deleteStr);
-  int PackageFiles();
-  virtual const char* GetOutputExtension() { return ".exe"; }
-  virtual const char* GetOutputPostfix() { return "win32"; }
+  int InitializeInternal() CM_OVERRIDE;
+  void CreateMenuLinks(std::ostream& str, std::ostream& deleteStr);
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".exe"; }
+  const char* GetOutputPostfix() CM_OVERRIDE { return "win32"; }
 
   bool GetListOfSubdirectories(const char* dir,
                                std::vector<std::string>& dirs);
 
-  enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const;
-  virtual bool SupportsAbsoluteDestination() const;
-  virtual bool SupportsComponentInstallation() const;
+  enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const
+    CM_OVERRIDE;
+  bool SupportsAbsoluteDestination() const CM_OVERRIDE;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
   /// Produce a string that contains the NSIS code to describe a
   /// particular component. Any added macros will be emitted via
   /// macrosOut.
   std::string CreateComponentDescription(cmCPackComponent* component,
-                                         std::ostringstream& macrosOut);
+                                         std::ostream& macrosOut);
 
   /// Produce NSIS code that selects all of the components that this component
   /// depends on, recursively.
@@ -72,7 +72,12 @@ protected:
   /// particular component group, including its components. Any
   /// added macros will be emitted via macrosOut.
   std::string CreateComponentGroupDescription(cmCPackComponentGroup* group,
-                                              std::ostringstream& macrosOut);
+                                              std::ostream& macrosOut);
+
+  /// Returns the custom install directory if available for the specified
+  /// component, otherwise $INSTDIR is returned.
+  std::string CustomComponentInstallDirectory(
+    const std::string& componentName);
 
   /// Translations any newlines found in the string into \\r\\n, so that the
   /// resulting string can be used within NSIS.
diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx
index d5691be..225c1fb 100644
--- a/Source/CPack/cmCPackOSXX11Generator.cxx
+++ b/Source/CPack/cmCPackOSXX11Generator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackOSXX11Generator.h"
 
 #include "cmCPackLog.h"
@@ -102,15 +92,14 @@ int cmCPackOSXX11Generator::PackageFiles()
   }
 
   std::string applicationsLinkName = diskImageDirectory + "/Applications";
-  cmSystemTools::CreateSymlink("/Applications", applicationsLinkName.c_str());
+  cmSystemTools::CreateSymlink("/Applications", applicationsLinkName);
 
-  if (!this->CopyResourcePlistFile("VolumeIcon.icns",
-                                   diskImageDirectory.c_str(),
+  if (!this->CopyResourcePlistFile("VolumeIcon.icns", diskImageDirectory,
                                    ".VolumeIcon.icns", true) ||
-      !this->CopyResourcePlistFile("DS_Store", diskImageDirectory.c_str(),
-                                   ".DS_Store", true) ||
+      !this->CopyResourcePlistFile("DS_Store", diskImageDirectory, ".DS_Store",
+                                   true) ||
       !this->CopyResourcePlistFile("background.png",
-                                   diskImageBackgroundImageDir.c_str(),
+                                   diskImageBackgroundImageDir,
                                    "background.png", true) ||
       !this->CopyResourcePlistFile("RuntimeScript", dir) ||
       !this->CopyResourcePlistFile("OSXX11.Info.plist", contDir,
@@ -158,11 +147,10 @@ int cmCPackOSXX11Generator::PackageFiles()
   tmpFile += "/hdiutilOutput.log";
   std::ostringstream dmgCmd;
   dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE")
-         << "\" create -ov -format UDZO -srcfolder \""
-         << diskImageDirectory.c_str() << "\" \"" << packageFileNames[0]
-         << "\"";
+         << "\" create -ov -format UDZO -srcfolder \"" << diskImageDirectory
+         << "\" \"" << packageFileNames[0] << "\"";
   cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Compress disk image using command: "
-                  << dmgCmd.str().c_str() << std::endl);
+                  << dmgCmd.str() << std::endl);
   // since we get random dashboard failures with this one
   // try running it more than once
   int retVal = 1;
@@ -181,12 +169,12 @@ int cmCPackOSXX11Generator::PackageFiles()
   }
   if (!res || retVal) {
     cmGeneratedFileStream ofs(tmpFile.c_str());
-    ofs << "# Run command: " << dmgCmd.str().c_str() << std::endl
+    ofs << "# Run command: " << dmgCmd.str() << std::endl
         << "# Output:" << std::endl
-        << output.c_str() << std::endl;
+        << output << std::endl;
     cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running hdiutil command: "
-                    << dmgCmd.str().c_str() << std::endl
-                    << "Please check " << tmpFile.c_str() << " for errors"
+                    << dmgCmd.str() << std::endl
+                    << "Please check " << tmpFile << " for errors"
                     << std::endl);
     return 0;
   }
@@ -249,7 +237,7 @@ bool cmCPackOSXX11Generator::CopyCreateResourceFile(const std::string& name)
 
   cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
                 << (inFileName ? inFileName : "(NULL)")
-                << " to " << destFileName.c_str() << std::endl);
+                << " to " << destFileName << std::endl);
   this->ConfigureFile(inFileName, destFileName.c_str());
   return true;
 }
@@ -277,9 +265,8 @@ bool cmCPackOSXX11Generator::CopyResourcePlistFile(
   destFileName += "/";
   destFileName += outputFileName;
 
-  cmCPackLogger(cmCPackLog::LOG_VERBOSE,
-                "Configure file: " << inFileName.c_str() << " to "
-                                   << destFileName.c_str() << std::endl);
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
+                  << inFileName << " to " << destFileName << std::endl);
   this->ConfigureFile(inFileName.c_str(), destFileName.c_str(), copyOnly);
   return true;
 }
diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h
index adc05d2..eb1e5ff 100644
--- a/Source/CPack/cmCPackOSXX11Generator.h
+++ b/Source/CPack/cmCPackOSXX11Generator.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackOSXX11Generator_h
 #define cmCPackOSXX11Generator_h
 
@@ -32,10 +22,10 @@ public:
   virtual ~cmCPackOSXX11Generator();
 
 protected:
-  virtual int InitializeInternal();
-  int PackageFiles();
-  virtual const char* GetPackagingInstallPrefix();
-  virtual const char* GetOutputExtension() { return ".dmg"; }
+  virtual int InitializeInternal() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetPackagingInstallPrefix() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; }
 
   // bool CopyCreateResourceFile(const std::string& name,
   //                            const std::string& dir);
diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx
new file mode 100644
index 0000000..785ee01
--- /dev/null
+++ b/Source/CPack/cmCPackPKGGenerator.cxx
@@ -0,0 +1,357 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmCPackPKGGenerator.h"
+
+#include "cmCPackComponentGroup.h"
+#include "cmCPackLog.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmXMLWriter.h"
+#include "cmake.h"
+
+#include <cmsys/Glob.hxx>
+#include <cmsys/SystemTools.hxx>
+
+cmCPackPKGGenerator::cmCPackPKGGenerator()
+{
+  this->componentPackageMethod = ONE_PACKAGE;
+}
+
+cmCPackPKGGenerator::~cmCPackPKGGenerator()
+{
+}
+
+bool cmCPackPKGGenerator::SupportsComponentInstallation() const
+{
+  return true;
+}
+
+int cmCPackPKGGenerator::InitializeInternal()
+{
+  cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackPKGGenerator::Initialize()"
+                  << std::endl);
+
+  return this->Superclass::InitializeInternal();
+}
+
+std::string cmCPackPKGGenerator::GetPackageName(
+  const cmCPackComponent& component)
+{
+  if (component.ArchiveFile.empty()) {
+    std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
+    packagesDir += ".dummy";
+    std::ostringstream out;
+    out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-"
+        << component.Name << ".pkg";
+    return out.str();
+  } else {
+    return component.ArchiveFile + ".pkg";
+  }
+}
+
+void cmCPackPKGGenerator::WriteDistributionFile(const char* metapackageFile)
+{
+  std::string distributionTemplate =
+    this->FindTemplate("CPack.distribution.dist.in");
+  if (distributionTemplate.empty()) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find input file: "
+                    << distributionTemplate << std::endl);
+    return;
+  }
+
+  std::string distributionFile = metapackageFile;
+  distributionFile += "/Contents/distribution.dist";
+
+  // Create the choice outline, which provides a tree-based view of
+  // the components in their groups.
+  std::ostringstream choiceOut;
+  cmXMLWriter xout(choiceOut, 1);
+  xout.StartElement("choices-outline");
+
+  // Emit the outline for the groups
+  std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
+  for (groupIt = this->ComponentGroups.begin();
+       groupIt != this->ComponentGroups.end(); ++groupIt) {
+    if (groupIt->second.ParentGroup == 0) {
+      CreateChoiceOutline(groupIt->second, xout);
+    }
+  }
+
+  // Emit the outline for the non-grouped components
+  std::map<std::string, cmCPackComponent>::iterator compIt;
+  for (compIt = this->Components.begin(); compIt != this->Components.end();
+       ++compIt) {
+    if (!compIt->second.Group) {
+      xout.StartElement("line");
+      xout.Attribute("choice", compIt->first + "Choice");
+      xout.Content(""); // Avoid self-closing tag.
+      xout.EndElement();
+    }
+  }
+  if (!this->PostFlightComponent.Name.empty()) {
+    xout.StartElement("line");
+    xout.Attribute("choice", PostFlightComponent.Name + "Choice");
+    xout.Content(""); // Avoid self-closing tag.
+    xout.EndElement();
+  }
+  xout.EndElement(); // choices-outline>
+
+  // Create the actual choices
+  for (groupIt = this->ComponentGroups.begin();
+       groupIt != this->ComponentGroups.end(); ++groupIt) {
+    CreateChoice(groupIt->second, xout);
+  }
+  for (compIt = this->Components.begin(); compIt != this->Components.end();
+       ++compIt) {
+    CreateChoice(compIt->second, xout);
+  }
+
+  if (!this->PostFlightComponent.Name.empty()) {
+    CreateChoice(PostFlightComponent, xout);
+  }
+
+  this->SetOption("CPACK_PACKAGEMAKER_CHOICES", choiceOut.str().c_str());
+
+  // Create the distribution.dist file in the metapackage to turn it
+  // into a distribution package.
+  this->ConfigureFile(distributionTemplate.c_str(), distributionFile.c_str());
+}
+
+void cmCPackPKGGenerator::CreateChoiceOutline(
+  const cmCPackComponentGroup& group, cmXMLWriter& xout)
+{
+  xout.StartElement("line");
+  xout.Attribute("choice", group.Name + "Choice");
+  std::vector<cmCPackComponentGroup*>::const_iterator groupIt;
+  for (groupIt = group.Subgroups.begin(); groupIt != group.Subgroups.end();
+       ++groupIt) {
+    CreateChoiceOutline(**groupIt, xout);
+  }
+
+  std::vector<cmCPackComponent*>::const_iterator compIt;
+  for (compIt = group.Components.begin(); compIt != group.Components.end();
+       ++compIt) {
+    xout.StartElement("line");
+    xout.Attribute("choice", (*compIt)->Name + "Choice");
+    xout.Content(""); // Avoid self-closing tag.
+    xout.EndElement();
+  }
+  xout.EndElement();
+}
+
+void cmCPackPKGGenerator::CreateChoice(const cmCPackComponentGroup& group,
+                                       cmXMLWriter& xout)
+{
+  xout.StartElement("choice");
+  xout.Attribute("id", group.Name + "Choice");
+  xout.Attribute("title", group.DisplayName);
+  xout.Attribute("start_selected", "true");
+  xout.Attribute("start_enabled", "true");
+  xout.Attribute("start_visible", "true");
+  if (!group.Description.empty()) {
+    xout.Attribute("description", group.Description);
+  }
+  xout.EndElement();
+}
+
+void cmCPackPKGGenerator::CreateChoice(const cmCPackComponent& component,
+                                       cmXMLWriter& xout)
+{
+  std::string packageId = "com.";
+  packageId += this->GetOption("CPACK_PACKAGE_VENDOR");
+  packageId += '.';
+  packageId += this->GetOption("CPACK_PACKAGE_NAME");
+  packageId += '.';
+  packageId += component.Name;
+
+  xout.StartElement("choice");
+  xout.Attribute("id", component.Name + "Choice");
+  xout.Attribute("title", component.DisplayName);
+  xout.Attribute(
+    "start_selected",
+    component.IsDisabledByDefault && !component.IsRequired ? "false" : "true");
+  xout.Attribute("start_enabled", component.IsRequired ? "false" : "true");
+  xout.Attribute("start_visible", component.IsHidden ? "false" : "true");
+  if (!component.Description.empty()) {
+    xout.Attribute("description", component.Description);
+  }
+  if (!component.Dependencies.empty() ||
+      !component.ReverseDependencies.empty()) {
+    // The "selected" expression is evaluated each time any choice is
+    // selected, for all choices *except* the one that the user
+    // selected. A component is marked selected if it has been
+    // selected (my.choice.selected in Javascript) and all of the
+    // components it depends on have been selected (transitively) or
+    // if any of the components that depend on it have been selected
+    // (transitively). Assume that we have components A, B, C, D, and
+    // E, where each component depends on the previous component (B
+    // depends on A, C depends on B, D depends on C, and E depends on
+    // D). The expression we build for the component C will be
+    //   my.choice.selected && B && A || D || E
+    // This way, selecting C will automatically select everything it depends
+    // on (B and A), while selecting something that depends on C--either D
+    // or E--will automatically cause C to get selected.
+    std::ostringstream selected("my.choice.selected");
+    std::set<const cmCPackComponent*> visited;
+    AddDependencyAttributes(component, visited, selected);
+    visited.clear();
+    AddReverseDependencyAttributes(component, visited, selected);
+    xout.Attribute("selected", selected.str());
+  }
+  xout.StartElement("pkg-ref");
+  xout.Attribute("id", packageId);
+  xout.EndElement(); // pkg-ref
+  xout.EndElement(); // choice
+
+  // Create a description of the package associated with this
+  // component.
+  std::string relativePackageLocation = "Contents/Packages/";
+  relativePackageLocation += this->GetPackageName(component);
+
+  // Determine the installed size of the package.
+  std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
+  dirName += '/';
+  dirName += component.Name;
+  dirName += this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
+  unsigned long installedSize = component.GetInstalledSizeInKbytes(dirName);
+
+  xout.StartElement("pkg-ref");
+  xout.Attribute("id", packageId);
+  xout.Attribute("version", this->GetOption("CPACK_PACKAGE_VERSION"));
+  xout.Attribute("installKBytes", installedSize);
+  xout.Attribute("auth", "Admin");
+  xout.Attribute("onConclusion", "None");
+  if (component.IsDownloaded) {
+    xout.Content(this->GetOption("CPACK_DOWNLOAD_SITE"));
+    xout.Content(this->GetPackageName(component));
+  } else {
+    xout.Content("file:./");
+    xout.Content(relativePackageLocation);
+  }
+  xout.EndElement(); // pkg-ref
+}
+
+void cmCPackPKGGenerator::AddDependencyAttributes(
+  const cmCPackComponent& component,
+  std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
+{
+  if (visited.find(&component) != visited.end()) {
+    return;
+  }
+  visited.insert(&component);
+
+  std::vector<cmCPackComponent*>::const_iterator dependIt;
+  for (dependIt = component.Dependencies.begin();
+       dependIt != component.Dependencies.end(); ++dependIt) {
+    out << " && choices['" << (*dependIt)->Name << "Choice'].selected";
+    AddDependencyAttributes(**dependIt, visited, out);
+  }
+}
+
+void cmCPackPKGGenerator::AddReverseDependencyAttributes(
+  const cmCPackComponent& component,
+  std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
+{
+  if (visited.find(&component) != visited.end()) {
+    return;
+  }
+  visited.insert(&component);
+
+  std::vector<cmCPackComponent*>::const_iterator dependIt;
+  for (dependIt = component.ReverseDependencies.begin();
+       dependIt != component.ReverseDependencies.end(); ++dependIt) {
+    out << " || choices['" << (*dependIt)->Name << "Choice'].selected";
+    AddReverseDependencyAttributes(**dependIt, visited, out);
+  }
+}
+
+bool cmCPackPKGGenerator::CopyCreateResourceFile(const std::string& name,
+                                                 const std::string& dirName)
+{
+  std::string uname = cmSystemTools::UpperCase(name);
+  std::string cpackVar = "CPACK_RESOURCE_FILE_" + uname;
+  const char* inFileName = this->GetOption(cpackVar);
+  if (!inFileName) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "CPack option: "
+                    << cpackVar.c_str()
+                    << " not specified. It should point to "
+                    << (!name.empty() ? name : "<empty>") << ".rtf, " << name
+                    << ".html, or " << name << ".txt file" << std::endl);
+    return false;
+  }
+  if (!cmSystemTools::FileExists(inFileName)) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find "
+                    << (!name.empty() ? name : "<empty>")
+                    << " resource file: " << inFileName << std::endl);
+    return false;
+  }
+  std::string ext = cmSystemTools::GetFilenameLastExtension(inFileName);
+  if (ext != ".rtfd" && ext != ".rtf" && ext != ".html" && ext != ".txt") {
+    cmCPackLogger(
+      cmCPackLog::LOG_ERROR, "Bad file extension specified: "
+        << ext
+        << ". Currently only .rtfd, .rtf, .html, and .txt files allowed."
+        << std::endl);
+    return false;
+  }
+
+  std::string destFileName = dirName;
+  destFileName += '/';
+  destFileName += name + ext;
+
+  // Set this so that distribution.dist gets the right name (without
+  // the path).
+  this->SetOption("CPACK_RESOURCE_FILE_" + uname + "_NOPATH",
+                  (name + ext).c_str());
+
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE,
+                "Configure file: " << (inFileName ? inFileName : "(NULL)")
+                                   << " to " << destFileName << std::endl);
+  this->ConfigureFile(inFileName, destFileName.c_str());
+  return true;
+}
+
+bool cmCPackPKGGenerator::CopyResourcePlistFile(const std::string& name,
+                                                const char* outName)
+{
+  if (!outName) {
+    outName = name.c_str();
+  }
+
+  std::string inFName = "CPack.";
+  inFName += name;
+  inFName += ".in";
+  std::string inFileName = this->FindTemplate(inFName.c_str());
+  if (inFileName.empty()) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Cannot find input file: " << inFName << std::endl);
+    return false;
+  }
+
+  std::string destFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+  destFileName += "/";
+  destFileName += outName;
+
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
+                  << inFileName << " to " << destFileName << std::endl);
+  this->ConfigureFile(inFileName.c_str(), destFileName.c_str());
+  return true;
+}
+
+int cmCPackPKGGenerator::CopyInstallScript(const std::string& resdir,
+                                           const std::string& script,
+                                           const std::string& name)
+{
+  std::string dst = resdir;
+  dst += "/";
+  dst += name;
+  cmSystemTools::CopyFileAlways(script, dst);
+  cmSystemTools::SetPermissions(dst.c_str(), 0777);
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE,
+                "copy script : " << script << "\ninto " << dst << std::endl);
+
+  return 1;
+}
diff --git a/Source/CPack/cmCPackPKGGenerator.h b/Source/CPack/cmCPackPKGGenerator.h
new file mode 100644
index 0000000..5569185
--- /dev/null
+++ b/Source/CPack/cmCPackPKGGenerator.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 cmCPackPKGGenerator_h
+#define cmCPackPKGGenerator_h
+
+#include "cmCPackGenerator.h"
+
+class cmCPackComponent;
+class cmXMLWriter;
+
+/** \class cmCPackPKGGenerator
+ * \brief A generator for pkg files
+ *
+ */
+class cmCPackPKGGenerator : public cmCPackGenerator
+{
+public:
+  cmCPackTypeMacro(cmCPackPKGGenerator, cmCPackGenerator);
+
+  /**
+   * Construct generator
+   */
+  cmCPackPKGGenerator();
+  virtual ~cmCPackPKGGenerator();
+
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
+
+protected:
+  int InitializeInternal() CM_OVERRIDE;
+  const char* GetOutputPostfix() CM_OVERRIDE { return "darwin"; }
+
+  // Copies or creates the resource file with the given name to the
+  // package or package staging directory dirName. The variable
+  // CPACK_RESOURCE_FILE_${NAME} (where ${NAME} is the uppercased
+  // version of name) specifies the input file to use for this file,
+  // which will be configured via ConfigureFile.
+  bool CopyCreateResourceFile(const std::string& name,
+                              const std::string& dirName);
+  bool CopyResourcePlistFile(const std::string& name, const char* outName = 0);
+
+  int CopyInstallScript(const std::string& resdir, const std::string& script,
+                        const std::string& name);
+
+  // Retrieve the name of package file that will be generated for this
+  // component. The name is just the file name with extension, and
+  // does not include the subdirectory.
+  std::string GetPackageName(const cmCPackComponent& component);
+
+  // Writes a distribution.dist file, which turns a metapackage into a
+  // full-fledged distribution. This file is used to describe
+  // inter-component dependencies. metapackageFile is the name of the
+  // metapackage for the distribution. Only valid for a
+  // component-based install.
+  void WriteDistributionFile(const char* metapackageFile);
+
+  // Subroutine of WriteDistributionFile that writes out the
+  // dependency attributes for inter-component dependencies.
+  void AddDependencyAttributes(const cmCPackComponent& component,
+                               std::set<const cmCPackComponent*>& visited,
+                               std::ostringstream& out);
+
+  // Subroutine of WriteDistributionFile that writes out the
+  // reverse dependency attributes for inter-component dependencies.
+  void AddReverseDependencyAttributes(
+    const cmCPackComponent& component,
+    std::set<const cmCPackComponent*>& visited, std::ostringstream& out);
+
+  // Generates XML that encodes the hierarchy of component groups and
+  // their components in a form that can be used by distribution
+  // metapackages.
+  void CreateChoiceOutline(const cmCPackComponentGroup& group,
+                           cmXMLWriter& xout);
+
+  /// Create the "choice" XML element to describe a component group
+  /// for the installer GUI.
+  void CreateChoice(const cmCPackComponentGroup& group, cmXMLWriter& xout);
+
+  /// Create the "choice" XML element to describe a component for the
+  /// installer GUI.
+  void CreateChoice(const cmCPackComponent& component, cmXMLWriter& xout);
+
+  // The PostFlight component when creating a metapackage
+  cmCPackComponent PostFlightComponent;
+};
+
+#endif
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx
index 5ca3ff7..25e8a1c 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.cxx
+++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackPackageMakerGenerator.h"
 
 #include "cmCPackComponentGroup.h"
@@ -17,6 +8,7 @@
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSystemTools.h"
+#include "cmXMLWriter.h"
 #include "cmake.h"
 
 #include <cmsys/FStream.hxx>
@@ -46,21 +38,6 @@ bool cmCPackPackageMakerGenerator::SupportsComponentInstallation() const
   return this->PackageCompatibilityVersion >= getVersion(10, 4);
 }
 
-int cmCPackPackageMakerGenerator::CopyInstallScript(const std::string& resdir,
-                                                    const std::string& script,
-                                                    const std::string& name)
-{
-  std::string dst = resdir;
-  dst += "/";
-  dst += name;
-  cmSystemTools::CopyFileAlways(script.c_str(), dst.c_str());
-  cmSystemTools::SetPermissions(dst.c_str(), 0777);
-  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "copy script : "
-                  << script << "\ninto " << dst.c_str() << std::endl);
-
-  return 1;
-}
-
 int cmCPackPackageMakerGenerator::PackageFiles()
 {
   // TODO: Use toplevel
@@ -116,7 +93,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
       if (!cmsys::SystemTools::MakeDirectory(preflightDirName.c_str())) {
         cmCPackLogger(cmCPackLog::LOG_ERROR,
                       "Problem creating installer directory: "
-                        << preflightDirName.c_str() << std::endl);
+                        << preflightDirName << std::endl);
         return 0;
       }
     }
@@ -124,7 +101,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
       if (!cmsys::SystemTools::MakeDirectory(postflightDirName.c_str())) {
         cmCPackLogger(cmCPackLog::LOG_ERROR,
                       "Problem creating installer directory: "
-                        << postflightDirName.c_str() << std::endl);
+                        << postflightDirName << std::endl);
         return 0;
       }
     }
@@ -132,13 +109,13 @@ int cmCPackPackageMakerGenerator::PackageFiles()
     // then copy them into the resource directory and make
     // them executable
     if (preflight) {
-      this->CopyInstallScript(resDir.c_str(), preflight, "preflight");
+      this->CopyInstallScript(resDir, preflight, "preflight");
     }
     if (postflight) {
-      this->CopyInstallScript(resDir.c_str(), postflight, "postflight");
+      this->CopyInstallScript(resDir, postflight, "postflight");
     }
     if (postupgrade) {
-      this->CopyInstallScript(resDir.c_str(), postupgrade, "postupgrade");
+      this->CopyInstallScript(resDir, postupgrade, "postupgrade");
     }
   } else if (postflight) {
     // create a postflight component to house the script
@@ -152,7 +129,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
     if (!cmsys::SystemTools::MakeDirectory(packageDir.c_str())) {
       cmCPackLogger(cmCPackLog::LOG_ERROR,
                     "Problem creating component packages directory: "
-                      << packageDir.c_str() << std::endl);
+                      << packageDir << std::endl);
       return 0;
     }
 
@@ -162,7 +139,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
       cmCPackLogger(
         cmCPackLog::LOG_ERROR,
         "Problem creating component PostFlight Packages directory: "
-          << packageFileDir.c_str() << std::endl);
+          << packageFileDir << std::endl);
       return 0;
     }
     std::string packageFile =
@@ -174,7 +151,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
 
     // copy postflight script into resource directory of .pkg
     std::string resourceDir = packageFile + "/Contents/Resources";
-    this->CopyInstallScript(resourceDir.c_str(), postflight, "postflight");
+    this->CopyInstallScript(resourceDir, postflight, "postflight");
   }
 
   if (!this->Components.empty()) {
@@ -184,7 +161,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
     if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str())) {
       cmCPackLogger(cmCPackLog::LOG_ERROR,
                     "Problem creating component packages directory: "
-                      << basePackageDir.c_str() << std::endl);
+                      << basePackageDir << std::endl);
       return 0;
     }
 
@@ -268,9 +245,9 @@ int cmCPackPackageMakerGenerator::PackageFiles()
   this->SetOption("CPACK_MODULE_VERSION_SUFFIX", "");
 
   // Copy or create all of the resource files we need.
-  if (!this->CopyCreateResourceFile("License", resDir.c_str()) ||
-      !this->CopyCreateResourceFile("ReadMe", resDir.c_str()) ||
-      !this->CopyCreateResourceFile("Welcome", resDir.c_str()) ||
+  if (!this->CopyCreateResourceFile("License", resDir) ||
+      !this->CopyCreateResourceFile("ReadMe", resDir) ||
+      !this->CopyCreateResourceFile("Welcome", resDir) ||
       !this->CopyResourcePlistFile("Info.plist") ||
       !this->CopyResourcePlistFile("Description.plist")) {
     cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the resource files"
@@ -329,12 +306,12 @@ int cmCPackPackageMakerGenerator::PackageFiles()
   }
   if (!res || retVal) {
     cmGeneratedFileStream ofs(tmpFile.c_str());
-    ofs << "# Run command: " << dmgCmd.str().c_str() << std::endl
+    ofs << "# Run command: " << dmgCmd.str() << std::endl
         << "# Output:" << std::endl
-        << output.c_str() << std::endl;
+        << output << std::endl;
     cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running hdiutil command: "
-                    << dmgCmd.str().c_str() << std::endl
-                    << "Please check " << tmpFile.c_str() << " for errors"
+                    << dmgCmd.str() << std::endl
+                    << "Please check " << tmpFile << " for errors"
                     << std::endl);
     return 0;
   }
@@ -344,8 +321,6 @@ int cmCPackPackageMakerGenerator::PackageFiles()
 
 int cmCPackPackageMakerGenerator::InitializeInternal()
 {
-  cmCPackLogger(cmCPackLog::LOG_DEBUG,
-                "cmCPackPackageMakerGenerator::Initialize()" << std::endl);
   this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr");
 
   // Starting with Xcode 4.3, PackageMaker is a separate app, and you
@@ -388,7 +363,7 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
   }
 
   // Get path to the real PackageMaker, not a symlink:
-  pkgPath = cmSystemTools::GetRealPath(pkgPath.c_str());
+  pkgPath = cmSystemTools::GetRealPath(pkgPath);
   // Up from there to find the version.plist file in the "Contents" dir:
   std::string contents_dir;
   contents_dir = cmSystemTools::GetFilenamePath(pkgPath);
@@ -399,7 +374,7 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
   if (!cmSystemTools::FileExists(versionFile.c_str())) {
     cmCPackLogger(cmCPackLog::LOG_ERROR,
                   "Cannot find PackageMaker compiler version file: "
-                    << versionFile.c_str() << std::endl);
+                    << versionFile << std::endl);
     return 0;
   }
 
@@ -433,7 +408,7 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
   if (!cmSystemTools::GetLineFromStream(ifs, line) || !rexVersion.find(line)) {
     cmCPackLogger(cmCPackLog::LOG_ERROR,
                   "Problem reading the PackageMaker compiler version file: "
-                    << versionFile.c_str() << std::endl);
+                    << versionFile << std::endl);
     return 0;
   }
   this->PackageMakerVersion = atof(rexVersion.match(1).c_str());
@@ -481,80 +456,6 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
   return this->Superclass::InitializeInternal();
 }
 
-bool cmCPackPackageMakerGenerator::CopyCreateResourceFile(
-  const std::string& name, const std::string& dirName)
-{
-  std::string uname = cmSystemTools::UpperCase(name);
-  std::string cpackVar = "CPACK_RESOURCE_FILE_" + uname;
-  const char* inFileName = this->GetOption(cpackVar.c_str());
-  if (!inFileName) {
-    cmCPackLogger(cmCPackLog::LOG_ERROR, "CPack option: "
-                    << cpackVar.c_str()
-                    << " not specified. It should point to "
-                    << (!name.empty() ? name : "<empty>") << ".rtf, " << name
-                    << ".html, or " << name << ".txt file" << std::endl);
-    return false;
-  }
-  if (!cmSystemTools::FileExists(inFileName)) {
-    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find "
-                    << (!name.empty() ? name : "<empty>")
-                    << " resource file: " << inFileName << std::endl);
-    return false;
-  }
-  std::string ext = cmSystemTools::GetFilenameLastExtension(inFileName);
-  if (ext != ".rtfd" && ext != ".rtf" && ext != ".html" && ext != ".txt") {
-    cmCPackLogger(
-      cmCPackLog::LOG_ERROR, "Bad file extension specified: "
-        << ext
-        << ". Currently only .rtfd, .rtf, .html, and .txt files allowed."
-        << std::endl);
-    return false;
-  }
-
-  std::string destFileName = dirName;
-  destFileName += '/';
-  destFileName += name + ext;
-
-  // Set this so that distribution.dist gets the right name (without
-  // the path).
-  this->SetOption(("CPACK_RESOURCE_FILE_" + uname + "_NOPATH").c_str(),
-                  (name + ext).c_str());
-
-  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
-                  << (inFileName ? inFileName : "(NULL)") << " to "
-                  << destFileName.c_str() << std::endl);
-  this->ConfigureFile(inFileName, destFileName.c_str());
-  return true;
-}
-
-bool cmCPackPackageMakerGenerator::CopyResourcePlistFile(
-  const std::string& name, const char* outName)
-{
-  if (!outName) {
-    outName = name.c_str();
-  }
-
-  std::string inFName = "CPack.";
-  inFName += name;
-  inFName += ".in";
-  std::string inFileName = this->FindTemplate(inFName.c_str());
-  if (inFileName.empty()) {
-    cmCPackLogger(cmCPackLog::LOG_ERROR,
-                  "Cannot find input file: " << inFName << std::endl);
-    return false;
-  }
-
-  std::string destFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
-  destFileName += "/";
-  destFileName += outName;
-
-  cmCPackLogger(cmCPackLog::LOG_VERBOSE,
-                "Configure file: " << inFileName.c_str() << " to "
-                                   << destFileName.c_str() << std::endl);
-  this->ConfigureFile(inFileName.c_str(), destFileName.c_str());
-  return true;
-}
-
 bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command,
                                                    const char* packageFile)
 {
@@ -572,11 +473,11 @@ bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command,
     cmGeneratedFileStream ofs(tmpFile.c_str());
     ofs << "# Run command: " << command << std::endl
         << "# Output:" << std::endl
-        << output.c_str() << std::endl;
+        << output << std::endl;
     cmCPackLogger(
       cmCPackLog::LOG_ERROR, "Problem running PackageMaker command: "
         << command << std::endl
-        << "Please check " << tmpFile.c_str() << " for errors" << std::endl);
+        << "Please check " << tmpFile << " for errors" << std::endl);
     return false;
   }
   // sometimes the command finishes but the directory is not yet
@@ -597,21 +498,6 @@ bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command,
   return true;
 }
 
-std::string cmCPackPackageMakerGenerator::GetPackageName(
-  const cmCPackComponent& component)
-{
-  if (component.ArchiveFile.empty()) {
-    std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
-    packagesDir += ".dummy";
-    std::ostringstream out;
-    out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-"
-        << component.Name << ".pkg";
-    return out.str();
-  } else {
-    return component.ArchiveFile + ".pkg";
-  }
-}
-
 bool cmCPackPackageMakerGenerator::GenerateComponentPackage(
   const char* packageFile, const char* packageDir,
   const cmCPackComponent& component)
@@ -629,21 +515,22 @@ bool cmCPackPackageMakerGenerator::GenerateComponentPackage(
     std::string descriptionFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
     descriptionFile += '/' + component.Name + "-Description.plist";
     cmsys::ofstream out(descriptionFile.c_str());
-    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl
-        << "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
-        << "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << std::endl
-        << "<plist version=\"1.4\">" << std::endl
-        << "<dict>" << std::endl
-        << "  <key>IFPkgDescriptionTitle</key>" << std::endl
-        << "  <string>" << component.DisplayName << "</string>" << std::endl
-        << "  <key>IFPkgDescriptionVersion</key>" << std::endl
-        << "  <string>" << this->GetOption("CPACK_PACKAGE_VERSION")
-        << "</string>" << std::endl
-        << "  <key>IFPkgDescriptionDescription</key>" << std::endl
-        << "  <string>" + this->EscapeForXML(component.Description)
-        << "</string>" << std::endl
-        << "</dict>" << std::endl
-        << "</plist>" << std::endl;
+    cmXMLWriter xout(out);
+    xout.StartDocument();
+    xout.Doctype("plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
+                 "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
+    xout.StartElement("plist");
+    xout.Attribute("version", "1.4");
+    xout.StartElement("dict");
+    xout.Element("key", "IFPkgDescriptionTitle");
+    xout.Element("string", component.DisplayName);
+    xout.Element("key", "IFPkgDescriptionVersion");
+    xout.Element("string", this->GetOption("CPACK_PACKAGE_VERSION"));
+    xout.Element("key", "IFPkgDescriptionDescription");
+    xout.Element("string", component.Description);
+    xout.EndElement(); // dict
+    xout.EndElement(); // plist
+    xout.EndDocument();
     out.close();
 
     // Create the Info.plist file for this component
@@ -686,219 +573,3 @@ bool cmCPackPackageMakerGenerator::GenerateComponentPackage(
   // Run PackageMaker
   return RunPackageMaker(pkgCmd.str().c_str(), packageFile);
 }
-
-void cmCPackPackageMakerGenerator::WriteDistributionFile(
-  const char* metapackageFile)
-{
-  std::string distributionTemplate =
-    this->FindTemplate("CPack.distribution.dist.in");
-  if (distributionTemplate.empty()) {
-    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find input file: "
-                    << distributionTemplate << std::endl);
-    return;
-  }
-
-  std::string distributionFile = metapackageFile;
-  distributionFile += "/Contents/distribution.dist";
-
-  // Create the choice outline, which provides a tree-based view of
-  // the components in their groups.
-  std::ostringstream choiceOut;
-  choiceOut << "<choices-outline>" << std::endl;
-
-  // Emit the outline for the groups
-  std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
-  for (groupIt = this->ComponentGroups.begin();
-       groupIt != this->ComponentGroups.end(); ++groupIt) {
-    if (groupIt->second.ParentGroup == 0) {
-      CreateChoiceOutline(groupIt->second, choiceOut);
-    }
-  }
-
-  // Emit the outline for the non-grouped components
-  std::map<std::string, cmCPackComponent>::iterator compIt;
-  for (compIt = this->Components.begin(); compIt != this->Components.end();
-       ++compIt) {
-    if (!compIt->second.Group) {
-      choiceOut << "<line choice=\"" << compIt->first << "Choice\"></line>"
-                << std::endl;
-    }
-  }
-  if (!this->PostFlightComponent.Name.empty()) {
-    choiceOut << "<line choice=\"" << PostFlightComponent.Name
-              << "Choice\"></line>" << std::endl;
-  }
-  choiceOut << "</choices-outline>" << std::endl;
-
-  // Create the actual choices
-  for (groupIt = this->ComponentGroups.begin();
-       groupIt != this->ComponentGroups.end(); ++groupIt) {
-    CreateChoice(groupIt->second, choiceOut);
-  }
-  for (compIt = this->Components.begin(); compIt != this->Components.end();
-       ++compIt) {
-    CreateChoice(compIt->second, choiceOut);
-  }
-
-  if (!this->PostFlightComponent.Name.empty()) {
-    CreateChoice(PostFlightComponent, choiceOut);
-  }
-
-  this->SetOption("CPACK_PACKAGEMAKER_CHOICES", choiceOut.str().c_str());
-
-  // Create the distribution.dist file in the metapackage to turn it
-  // into a distribution package.
-  this->ConfigureFile(distributionTemplate.c_str(), distributionFile.c_str());
-}
-
-void cmCPackPackageMakerGenerator::CreateChoiceOutline(
-  const cmCPackComponentGroup& group, std::ostringstream& out)
-{
-  out << "<line choice=\"" << group.Name << "Choice\">" << std::endl;
-  std::vector<cmCPackComponentGroup*>::const_iterator groupIt;
-  for (groupIt = group.Subgroups.begin(); groupIt != group.Subgroups.end();
-       ++groupIt) {
-    CreateChoiceOutline(**groupIt, out);
-  }
-
-  std::vector<cmCPackComponent*>::const_iterator compIt;
-  for (compIt = group.Components.begin(); compIt != group.Components.end();
-       ++compIt) {
-    out << "  <line choice=\"" << (*compIt)->Name << "Choice\"></line>"
-        << std::endl;
-  }
-  out << "</line>" << std::endl;
-}
-
-void cmCPackPackageMakerGenerator::CreateChoice(
-  const cmCPackComponentGroup& group, std::ostringstream& out)
-{
-  out << "<choice id=\"" << group.Name << "Choice\" "
-      << "title=\"" << group.DisplayName << "\" "
-      << "start_selected=\"true\" "
-      << "start_enabled=\"true\" "
-      << "start_visible=\"true\" ";
-  if (!group.Description.empty()) {
-    out << "description=\"" << EscapeForXML(group.Description) << "\"";
-  }
-  out << "></choice>" << std::endl;
-}
-
-void cmCPackPackageMakerGenerator::CreateChoice(
-  const cmCPackComponent& component, std::ostringstream& out)
-{
-  std::string packageId = "com.";
-  packageId += this->GetOption("CPACK_PACKAGE_VENDOR");
-  packageId += '.';
-  packageId += this->GetOption("CPACK_PACKAGE_NAME");
-  packageId += '.';
-  packageId += component.Name;
-
-  out << "<choice id=\"" << component.Name << "Choice\" "
-      << "title=\"" << component.DisplayName << "\" "
-      << "start_selected=\""
-      << (component.IsDisabledByDefault && !component.IsRequired ? "false"
-                                                                 : "true")
-      << "\" "
-      << "start_enabled=\"" << (component.IsRequired ? "false" : "true")
-      << "\" "
-      << "start_visible=\"" << (component.IsHidden ? "false" : "true")
-      << "\" ";
-  if (!component.Description.empty()) {
-    out << "description=\"" << EscapeForXML(component.Description) << "\" ";
-  }
-  if (!component.Dependencies.empty() ||
-      !component.ReverseDependencies.empty()) {
-    // The "selected" expression is evaluated each time any choice is
-    // selected, for all choices *except* the one that the user
-    // selected. A component is marked selected if it has been
-    // selected (my.choice.selected in Javascript) and all of the
-    // components it depends on have been selected (transitively) or
-    // if any of the components that depend on it have been selected
-    // (transitively). Assume that we have components A, B, C, D, and
-    // E, where each component depends on the previous component (B
-    // depends on A, C depends on B, D depends on C, and E depends on
-    // D). The expression we build for the component C will be
-    //   my.choice.selected && B && A || D || E
-    // This way, selecting C will automatically select everything it depends
-    // on (B and A), while selecting something that depends on C--either D
-    // or E--will automatically cause C to get selected.
-    out << "selected=\"my.choice.selected";
-    std::set<const cmCPackComponent*> visited;
-    AddDependencyAttributes(component, visited, out);
-    visited.clear();
-    AddReverseDependencyAttributes(component, visited, out);
-    out << "\"";
-  }
-  out << ">" << std::endl;
-  out << "  <pkg-ref id=\"" << packageId << "\"></pkg-ref>" << std::endl;
-  out << "</choice>" << std::endl;
-
-  // Create a description of the package associated with this
-  // component.
-  std::string relativePackageLocation = "Contents/Packages/";
-  relativePackageLocation += this->GetPackageName(component);
-
-  // Determine the installed size of the package.
-  std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
-  dirName += '/';
-  dirName += component.Name;
-  dirName += this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
-  unsigned long installedSize =
-    component.GetInstalledSizeInKbytes(dirName.c_str());
-
-  out << "<pkg-ref id=\"" << packageId << "\" "
-      << "version=\"" << this->GetOption("CPACK_PACKAGE_VERSION") << "\" "
-      << "installKBytes=\"" << installedSize << "\" "
-      << "auth=\"Admin\" onConclusion=\"None\">";
-  if (component.IsDownloaded) {
-    out << this->GetOption("CPACK_DOWNLOAD_SITE")
-        << this->GetPackageName(component);
-  } else {
-    out << "file:./" << relativePackageLocation;
-  }
-  out << "</pkg-ref>" << std::endl;
-}
-
-void cmCPackPackageMakerGenerator::AddDependencyAttributes(
-  const cmCPackComponent& component,
-  std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
-{
-  if (visited.find(&component) != visited.end()) {
-    return;
-  }
-  visited.insert(&component);
-
-  std::vector<cmCPackComponent*>::const_iterator dependIt;
-  for (dependIt = component.Dependencies.begin();
-       dependIt != component.Dependencies.end(); ++dependIt) {
-    out << " && choices['" << (*dependIt)->Name << "Choice'].selected";
-    AddDependencyAttributes(**dependIt, visited, out);
-  }
-}
-
-void cmCPackPackageMakerGenerator::AddReverseDependencyAttributes(
-  const cmCPackComponent& component,
-  std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
-{
-  if (visited.find(&component) != visited.end()) {
-    return;
-  }
-  visited.insert(&component);
-
-  std::vector<cmCPackComponent*>::const_iterator dependIt;
-  for (dependIt = component.ReverseDependencies.begin();
-       dependIt != component.ReverseDependencies.end(); ++dependIt) {
-    out << " || choices['" << (*dependIt)->Name << "Choice'].selected";
-    AddReverseDependencyAttributes(**dependIt, visited, out);
-  }
-}
-
-std::string cmCPackPackageMakerGenerator::EscapeForXML(std::string str)
-{
-  cmSystemTools::ReplaceString(str, "&", "&");
-  cmSystemTools::ReplaceString(str, "<", "<");
-  cmSystemTools::ReplaceString(str, ">", ">");
-  cmSystemTools::ReplaceString(str, "\"", """);
-  return str;
-}
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h
index 2b8d253..d679bc1 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.h
+++ b/Source/CPack/cmCPackPackageMakerGenerator.h
@@ -1,19 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackPackageMakerGenerator_h
 #define cmCPackPackageMakerGenerator_h
 
-#include "cmCPackGenerator.h"
+#include "cmCPackPKGGenerator.h"
 
 class cmCPackComponent;
 
@@ -23,46 +13,28 @@ class cmCPackComponent;
  * http://developer.apple.com/documentation/Darwin
  * /Reference/ManPages/man1/packagemaker.1.html
  */
-class cmCPackPackageMakerGenerator : public cmCPackGenerator
+class cmCPackPackageMakerGenerator : public cmCPackPKGGenerator
 {
 public:
-  cmCPackTypeMacro(cmCPackPackageMakerGenerator, cmCPackGenerator);
+  cmCPackTypeMacro(cmCPackPackageMakerGenerator, cmCPackPKGGenerator);
 
   /**
    * Construct generator
    */
   cmCPackPackageMakerGenerator();
   virtual ~cmCPackPackageMakerGenerator();
-
-  virtual bool SupportsComponentInstallation() const;
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
 
 protected:
-  int CopyInstallScript(const std::string& resdir, const std::string& script,
-                        const std::string& name);
-  virtual int InitializeInternal();
-  int PackageFiles();
-  virtual const char* GetOutputExtension() { return ".dmg"; }
-  virtual const char* GetOutputPostfix() { return "darwin"; }
-
-  // Copies or creates the resource file with the given name to the
-  // package or package staging directory dirName. The variable
-  // CPACK_RESOURCE_FILE_${NAME} (where ${NAME} is the uppercased
-  // version of name) specifies the input file to use for this file,
-  // which will be configured via ConfigureFile.
-  bool CopyCreateResourceFile(const std::string& name,
-                              const std::string& dirName);
-  bool CopyResourcePlistFile(const std::string& name, const char* outName = 0);
+  int InitializeInternal() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; }
 
   // Run PackageMaker with the given command line, which will (if
   // successful) produce the given package file. Returns true if
   // PackageMaker succeeds, false otherwise.
   bool RunPackageMaker(const char* command, const char* packageFile);
 
-  // Retrieve the name of package file that will be generated for this
-  // component. The name is just the file name with extension, and
-  // does not include the subdirectory.
-  std::string GetPackageName(const cmCPackComponent& component);
-
   // Generate a package in the file packageFile for the given
   // component.  All of the files within this component are stored in
   // the directory packageDir. Returns true if successful, false
@@ -71,48 +43,6 @@ protected:
                                 const char* packageDir,
                                 const cmCPackComponent& component);
 
-  // Writes a distribution.dist file, which turns a metapackage into a
-  // full-fledged distribution. This file is used to describe
-  // inter-component dependencies. metapackageFile is the name of the
-  // metapackage for the distribution. Only valid for a
-  // component-based install.
-  void WriteDistributionFile(const char* metapackageFile);
-
-  // Subroutine of WriteDistributionFile that writes out the
-  // dependency attributes for inter-component dependencies.
-  void AddDependencyAttributes(const cmCPackComponent& component,
-                               std::set<const cmCPackComponent*>& visited,
-                               std::ostringstream& out);
-
-  // Subroutine of WriteDistributionFile that writes out the
-  // reverse dependency attributes for inter-component dependencies.
-  void AddReverseDependencyAttributes(
-    const cmCPackComponent& component,
-    std::set<const cmCPackComponent*>& visited, std::ostringstream& out);
-
-  // Generates XML that encodes the hierarchy of component groups and
-  // their components in a form that can be used by distribution
-  // metapackages.
-  void CreateChoiceOutline(const cmCPackComponentGroup& group,
-                           std::ostringstream& out);
-
-  /// Create the "choice" XML element to describe a component group
-  /// for the installer GUI.
-  void CreateChoice(const cmCPackComponentGroup& group,
-                    std::ostringstream& out);
-
-  /// Create the "choice" XML element to describe a component for the
-  /// installer GUI.
-  void CreateChoice(const cmCPackComponent& component,
-                    std::ostringstream& out);
-
-  // Escape the given string to make it usable as an XML attribute
-  // value.
-  std::string EscapeForXML(std::string str);
-
-  // The PostFlight component when creating a metapackage
-  cmCPackComponent PostFlightComponent;
-
   double PackageMakerVersion;
   unsigned int PackageCompatibilityVersion;
 };
diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx
new file mode 100644
index 0000000..ff0ec79
--- /dev/null
+++ b/Source/CPack/cmCPackProductBuildGenerator.cxx
@@ -0,0 +1,222 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmCPackProductBuildGenerator.h"
+
+#include "cmCPackComponentGroup.h"
+#include "cmCPackLog.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <cmsys/Glob.hxx>
+#include <cmsys/SystemTools.hxx>
+
+cmCPackProductBuildGenerator::cmCPackProductBuildGenerator()
+{
+  this->componentPackageMethod = ONE_PACKAGE;
+}
+
+cmCPackProductBuildGenerator::~cmCPackProductBuildGenerator()
+{
+}
+
+int cmCPackProductBuildGenerator::PackageFiles()
+{
+  // TODO: Use toplevel
+  //       It is used! Is this an obsolete comment?
+
+  std::string packageDirFileName =
+    this->GetOption("CPACK_TEMPORARY_DIRECTORY");
+
+  // Create the directory where component packages will be built.
+  std::string basePackageDir = packageDirFileName;
+  basePackageDir += "/Contents/Packages";
+  if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str())) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Problem creating component packages directory: "
+                    << basePackageDir << std::endl);
+    return 0;
+  }
+
+  if (!this->Components.empty()) {
+    std::map<std::string, cmCPackComponent>::iterator compIt;
+    for (compIt = this->Components.begin(); compIt != this->Components.end();
+         ++compIt) {
+      std::string packageDir = toplevel;
+      packageDir += '/';
+      packageDir += compIt->first;
+      if (!this->GenerateComponentPackage(basePackageDir,
+                                          GetPackageName(compIt->second),
+                                          packageDir, &compIt->second)) {
+        return 0;
+      }
+    }
+  } else {
+    if (!this->GenerateComponentPackage(basePackageDir,
+                                        this->GetOption("CPACK_PACKAGE_NAME"),
+                                        toplevel, NULL)) {
+      return 0;
+    }
+  }
+
+  // Copy or create all of the resource files we need.
+  std::string resDir = packageDirFileName + "/Contents";
+  if (!this->CopyCreateResourceFile("License", resDir) ||
+      !this->CopyCreateResourceFile("ReadMe", resDir) ||
+      !this->CopyCreateResourceFile("Welcome", resDir)) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the resource files"
+                    << std::endl);
+    return 0;
+  }
+
+  // combine package(s) into a distribution
+  WriteDistributionFile(packageDirFileName.c_str());
+  std::ostringstream pkgCmd;
+
+  std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
+  std::string productbuild = this->GetOption("CPACK_COMMAND_PRODUCTBUILD");
+
+  pkgCmd << productbuild << " --distribution \"" << packageDirFileName
+         << "/Contents/distribution.dist\""
+         << " --package-path \"" << packageDirFileName << "/Contents/Packages"
+         << "\""
+         << " --resources \"" << resDir << "\""
+         << " --version \"" << version << "\""
+         << " \"" << packageFileNames[0] << "\"";
+
+  // Run ProductBuild
+  return RunProductBuild(pkgCmd.str());
+}
+
+int cmCPackProductBuildGenerator::InitializeInternal()
+{
+  this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/Applications");
+
+  std::vector<std::string> no_paths;
+  std::string program =
+    cmSystemTools::FindProgram("pkgbuild", no_paths, false);
+  if (program.empty()) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find pkgbuild executable"
+                    << std::endl);
+    return 0;
+  }
+  this->SetOptionIfNotSet("CPACK_COMMAND_PKGBUILD", program.c_str());
+
+  program = cmSystemTools::FindProgram("productbuild", no_paths, false);
+  if (program.empty()) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find productbuild executable"
+                    << std::endl);
+    return 0;
+  }
+  this->SetOptionIfNotSet("CPACK_COMMAND_PRODUCTBUILD", program.c_str());
+
+  return this->Superclass::InitializeInternal();
+}
+
+bool cmCPackProductBuildGenerator::RunProductBuild(const std::string& command)
+{
+  std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+  tmpFile += "/ProductBuildOutput.log";
+
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << command << std::endl);
+  std::string output, error_output;
+  int retVal = 1;
+  bool res =
+    cmSystemTools::RunSingleCommand(command.c_str(), &output, &error_output,
+                                    &retVal, 0, this->GeneratorVerbose, 0);
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running command" << std::endl);
+  if (!res || retVal) {
+    cmGeneratedFileStream ofs(tmpFile.c_str());
+    ofs << "# Run command: " << command << std::endl
+        << "# Output:" << std::endl
+        << output << std::endl;
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Problem running command: " << command << std::endl
+                                              << "Please check " << tmpFile
+                                              << " for errors" << std::endl);
+    return false;
+  }
+  return true;
+}
+
+bool cmCPackProductBuildGenerator::GenerateComponentPackage(
+  const std::string& packageFileDir, const std::string& packageFileName,
+  const std::string& packageDir, const cmCPackComponent* component)
+{
+  std::string packageFile = packageFileDir;
+  packageFile += '/';
+  packageFile += packageFileName;
+
+  cmCPackLogger(cmCPackLog::LOG_OUTPUT, "-   Building component package: "
+                  << packageFile << std::endl);
+
+  const char* comp_name = component ? component->Name.c_str() : NULL;
+
+  const char* preflight = this->GetComponentScript("PREFLIGHT", comp_name);
+  const char* postflight = this->GetComponentScript("POSTFLIGHT", comp_name);
+
+  std::string resDir = packageFileDir;
+  if (component) {
+    resDir += "/";
+    resDir += component->Name;
+  }
+  std::string scriptDir = resDir + "/scripts";
+
+  if (!cmsys::SystemTools::MakeDirectory(scriptDir.c_str())) {
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Problem creating installer directory: " << scriptDir
+                                                           << std::endl);
+    return 0;
+  }
+
+  // if preflight, postflight, or postupgrade are set
+  // then copy them into the script directory and make
+  // them executable
+  if (preflight) {
+    this->CopyInstallScript(scriptDir, preflight, "preinstall");
+  }
+  if (postflight) {
+    this->CopyInstallScript(scriptDir, postflight, "postinstall");
+  }
+
+  // The command that will be used to run ProductBuild
+  std::ostringstream pkgCmd;
+
+  std::string pkgId = "com.";
+  pkgId += this->GetOption("CPACK_PACKAGE_VENDOR");
+  pkgId += '.';
+  pkgId += this->GetOption("CPACK_PACKAGE_NAME");
+  if (component) {
+    pkgId += '.';
+    pkgId += component->Name;
+  }
+
+  std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
+  std::string pkgbuild = this->GetOption("CPACK_COMMAND_PKGBUILD");
+
+  pkgCmd << pkgbuild << " --root \"" << packageDir << "\""
+         << " --identifier \"" << pkgId << "\""
+         << " --scripts \"" << scriptDir << "\""
+         << " --version \"" << version << "\""
+         << " --install-location \"/\""
+         << " \"" << packageFile << "\"";
+
+  // Run ProductBuild
+  return RunProductBuild(pkgCmd.str());
+}
+
+const char* cmCPackProductBuildGenerator::GetComponentScript(
+  const char* script, const char* component_name)
+{
+  std::string scriptname = std::string("CPACK_") + script + "_";
+  if (component_name) {
+    scriptname += cmSystemTools::UpperCase(component_name);
+    scriptname += "_";
+  }
+  scriptname += "SCRIPT";
+
+  return this->GetOption(scriptname);
+}
diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h
new file mode 100644
index 0000000..4145eb4
--- /dev/null
+++ b/Source/CPack/cmCPackProductBuildGenerator.h
@@ -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 cmCPackProductBuildGenerator_h
+#define cmCPackProductBuildGenerator_h
+
+#include "cmCPackPKGGenerator.h"
+
+class cmCPackComponent;
+
+/** \class cmCPackProductBuildGenerator
+ * \brief A generator for ProductBuild files
+ *
+ */
+class cmCPackProductBuildGenerator : public cmCPackPKGGenerator
+{
+public:
+  cmCPackTypeMacro(cmCPackProductBuildGenerator, cmCPackPKGGenerator);
+
+  /**
+   * Construct generator
+   */
+  cmCPackProductBuildGenerator();
+  virtual ~cmCPackProductBuildGenerator();
+
+protected:
+  int InitializeInternal() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".pkg"; }
+
+  // Run ProductBuild with the given command line, which will (if
+  // successful) produce the given package file. Returns true if
+  // ProductBuild succeeds, false otherwise.
+  bool RunProductBuild(const std::string& command);
+
+  // Generate a package in the file packageFile for the given
+  // component.  All of the files within this component are stored in
+  // the directory packageDir. Returns true if successful, false
+  // otherwise.
+  bool GenerateComponentPackage(const std::string& packageFileDir,
+                                const std::string& packageFileName,
+                                const std::string& packageDir,
+                                const cmCPackComponent* component);
+
+  const char* GetComponentScript(const char* script,
+                                 const char* script_component);
+};
+
+#endif
diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx
index 9827b70..bd55206 100644
--- a/Source/CPack/cmCPackRPMGenerator.cxx
+++ b/Source/CPack/cmCPackRPMGenerator.cxx
@@ -1,19 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackRPMGenerator.h"
 
+#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmSystemTools.h"
 
+#include <algorithm>
+#include <map>
+#include <ostream>
+#include <utility>
+#include <vector>
+
 cmCPackRPMGenerator::cmCPackRPMGenerator()
 {
 }
@@ -121,7 +120,7 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
     for (compIt = this->Components.begin(); compIt != this->Components.end();
          ++compIt) {
       // Does the component belong to a group?
-      if (compIt->second.Group == NULL) {
+      if (compIt->second.Group == CM_NULLPTR) {
         cmCPackLogger(
           cmCPackLog::LOG_VERBOSE, "Component <"
             << compIt->second.Name
@@ -215,24 +214,16 @@ int cmCPackRPMGenerator::PackageFiles()
     // 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.
-    else {
-      return PackageComponents(componentPackageMethod ==
-                               ONE_PACKAGE_PER_COMPONENT);
-    }
+    return PackageComponents(componentPackageMethod ==
+                             ONE_PACKAGE_PER_COMPONENT);
   }
   // CASE 3 : NON COMPONENT package.
-  else {
-    return PackageComponentsAllInOne("");
-  }
+  return PackageComponentsAllInOne("");
 }
 
 bool cmCPackRPMGenerator::SupportsComponentInstallation() const
 {
-  if (IsOn("CPACK_RPM_COMPONENT_INSTALL")) {
-    return true;
-  } else {
-    return false;
-  }
+  return IsOn("CPACK_RPM_COMPONENT_INSTALL");
 }
 
 std::string cmCPackRPMGenerator::GetComponentInstallDirNameSuffix(
@@ -249,9 +240,8 @@ std::string cmCPackRPMGenerator::GetComponentInstallDirNameSuffix(
   // the current COMPONENT belongs to.
   std::string groupVar =
     "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
-  if (NULL != GetOption(groupVar)) {
+  if (CM_NULLPTR != GetOption(groupVar)) {
     return std::string(GetOption(groupVar));
-  } else {
-    return componentName;
   }
+  return componentName;
 }
diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h
index b39f2c2..f8bcbfe 100644
--- a/Source/CPack/cmCPackRPMGenerator.h
+++ b/Source/CPack/cmCPackRPMGenerator.h
@@ -1,19 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackRPMGenerator_h
 #define cmCPackRPMGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
+
+#include <string>
 
 /** \class cmCPackRPMGenerator
  * \brief A generator for RPM packages
@@ -32,7 +27,7 @@ public:
    * Construct generator
    */
   cmCPackRPMGenerator();
-  virtual ~cmCPackRPMGenerator();
+  ~cmCPackRPMGenerator() CM_OVERRIDE;
 
   static bool CanGenerate()
   {
@@ -49,8 +44,8 @@ public:
   }
 
 protected:
-  virtual int InitializeInternal();
-  virtual int PackageFiles();
+  int InitializeInternal() CM_OVERRIDE;
+  int PackageFiles() CM_OVERRIDE;
   /**
    * This method factors out the work done in component packaging case.
    */
@@ -67,10 +62,10 @@ protected:
    * components will be put in a single installer.
    */
   int PackageComponentsAllInOne(const std::string& compInstDirName);
-  virtual const char* GetOutputExtension() { return ".rpm"; }
-  virtual bool SupportsComponentInstallation() const;
-  virtual std::string GetComponentInstallDirNameSuffix(
-    const std::string& componentName);
+  const char* GetOutputExtension() CM_OVERRIDE { return ".rpm"; }
+  bool SupportsComponentInstallation() const CM_OVERRIDE;
+  std::string GetComponentInstallDirNameSuffix(
+    const std::string& componentName) CM_OVERRIDE;
 
   void AddGeneratedPackageNames();
 };
diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx
index 4d07a7e..66ba9f6 100644
--- a/Source/CPack/cmCPackSTGZGenerator.cxx
+++ b/Source/CPack/cmCPackSTGZGenerator.cxx
@@ -1,24 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackSTGZGenerator.h"
 
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
 
 #include <cmsys/FStream.hxx>
+#include <sstream>
+#include <stdio.h>
+#include <string>
+#include <vector>
 
 #include <sys/types.h>
 // include sys/stat.h after sys/types.h
diff --git a/Source/CPack/cmCPackSTGZGenerator.h b/Source/CPack/cmCPackSTGZGenerator.h
index 08152b5..a1bee5f 100644
--- a/Source/CPack/cmCPackSTGZGenerator.h
+++ b/Source/CPack/cmCPackSTGZGenerator.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackSTGZGenerator_h
 #define cmCPackSTGZGenerator_h
 
+#include <cmConfigure.h>
+
+#include "cmCPackGenerator.h"
 #include "cmCPackTGZGenerator.h"
+#include "cmTypeMacro.h"
+
+#include <iosfwd>
 
 /** \class cmCPackSTGZGenerator
  * \brief A generator for Self extractable TGZ files
@@ -28,13 +24,13 @@ public:
    * Construct generator
    */
   cmCPackSTGZGenerator();
-  virtual ~cmCPackSTGZGenerator();
+  ~cmCPackSTGZGenerator() CM_OVERRIDE;
 
 protected:
-  int PackageFiles();
-  virtual int InitializeInternal();
-  int GenerateHeader(std::ostream* os);
-  virtual const char* GetOutputExtension() { return ".sh"; }
+  int PackageFiles() CM_OVERRIDE;
+  int InitializeInternal() CM_OVERRIDE;
+  int GenerateHeader(std::ostream* os) CM_OVERRIDE;
+  const char* GetOutputExtension() CM_OVERRIDE { return ".sh"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackTGZGenerator.cxx b/Source/CPack/cmCPackTGZGenerator.cxx
index 7c5c245..eaf8186 100644
--- a/Source/CPack/cmCPackTGZGenerator.cxx
+++ b/Source/CPack/cmCPackTGZGenerator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackTGZGenerator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPackTGZGenerator::cmCPackTGZGenerator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressGZip, "paxr")
 {
diff --git a/Source/CPack/cmCPackTGZGenerator.h b/Source/CPack/cmCPackTGZGenerator.h
index 408422b..e93fb44 100644
--- a/Source/CPack/cmCPackTGZGenerator.h
+++ b/Source/CPack/cmCPackTGZGenerator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackTGZGenerator_h
 #define cmCPackTGZGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPackTGZGenerator
  * \brief A generator for TGZ files
@@ -27,10 +21,10 @@ public:
    * Construct generator
    */
   cmCPackTGZGenerator();
-  virtual ~cmCPackTGZGenerator();
+  ~cmCPackTGZGenerator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".tar.gz"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".tar.gz"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackTXZGenerator.cxx b/Source/CPack/cmCPackTXZGenerator.cxx
index d17a164..e55e903 100644
--- a/Source/CPack/cmCPackTXZGenerator.cxx
+++ b/Source/CPack/cmCPackTXZGenerator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackTXZGenerator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPackTXZGenerator::cmCPackTXZGenerator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressXZ, "paxr")
 {
diff --git a/Source/CPack/cmCPackTXZGenerator.h b/Source/CPack/cmCPackTXZGenerator.h
index 05052a1..b8a7597 100644
--- a/Source/CPack/cmCPackTXZGenerator.h
+++ b/Source/CPack/cmCPackTXZGenerator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackTXZGenerator_h
 #define cmCPackTXZGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPackTXZGenerator
  * \brief A generator for TXZ files
@@ -27,10 +21,10 @@ public:
    * Construct generator
    */
   cmCPackTXZGenerator();
-  virtual ~cmCPackTXZGenerator();
+  ~cmCPackTXZGenerator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".tar.xz"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".tar.xz"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackTarBZip2Generator.cxx b/Source/CPack/cmCPackTarBZip2Generator.cxx
index 694d392..c7a3dd4 100644
--- a/Source/CPack/cmCPackTarBZip2Generator.cxx
+++ b/Source/CPack/cmCPackTarBZip2Generator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackTarBZip2Generator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPackTarBZip2Generator::cmCPackTarBZip2Generator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressBZip2, "paxr")
 {
diff --git a/Source/CPack/cmCPackTarBZip2Generator.h b/Source/CPack/cmCPackTarBZip2Generator.h
index 4033197..2e8ba9b 100644
--- a/Source/CPack/cmCPackTarBZip2Generator.h
+++ b/Source/CPack/cmCPackTarBZip2Generator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackTarBZip2Generator_h
 #define cmCPackTarBZip2Generator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPackTarBZip2Generator
  * \brief A generator for TarBZip2 files
@@ -26,10 +20,10 @@ public:
    * Construct generator
    */
   cmCPackTarBZip2Generator();
-  virtual ~cmCPackTarBZip2Generator();
+  ~cmCPackTarBZip2Generator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".tar.bz2"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".tar.bz2"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackTarCompressGenerator.cxx b/Source/CPack/cmCPackTarCompressGenerator.cxx
index aec6893..0a7cd97 100644
--- a/Source/CPack/cmCPackTarCompressGenerator.cxx
+++ b/Source/CPack/cmCPackTarCompressGenerator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackTarCompressGenerator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPackTarCompressGenerator::cmCPackTarCompressGenerator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressCompress, "paxr")
 {
diff --git a/Source/CPack/cmCPackTarCompressGenerator.h b/Source/CPack/cmCPackTarCompressGenerator.h
index 7ff9a0a..7d253e1 100644
--- a/Source/CPack/cmCPackTarCompressGenerator.h
+++ b/Source/CPack/cmCPackTarCompressGenerator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackTarCompressGenerator_h
 #define cmCPackTarCompressGenerator_h
 
-#include "cmCPackTGZGenerator.h"
+#include <cmConfigure.h>
+
+#include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPackTarCompressGenerator
  * \brief A generator for TarCompress files
@@ -26,10 +20,10 @@ public:
    * Construct generator
    */
   cmCPackTarCompressGenerator();
-  virtual ~cmCPackTarCompressGenerator();
+  ~cmCPackTarCompressGenerator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".tar.Z"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".tar.Z"; }
 };
 
 #endif
diff --git a/Source/CPack/cmCPackZIPGenerator.cxx b/Source/CPack/cmCPackZIPGenerator.cxx
index 9b42e6d..6b77c36 100644
--- a/Source/CPack/cmCPackZIPGenerator.cxx
+++ b/Source/CPack/cmCPackZIPGenerator.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackZIPGenerator.h"
 
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+
 cmCPackZIPGenerator::cmCPackZIPGenerator()
   : cmCPackArchiveGenerator(cmArchiveWrite::CompressNone, "zip")
 {
diff --git a/Source/CPack/cmCPackZIPGenerator.h b/Source/CPack/cmCPackZIPGenerator.h
index 70e1a5f..e0334fb 100644
--- a/Source/CPack/cmCPackZIPGenerator.h
+++ b/Source/CPack/cmCPackZIPGenerator.h
@@ -1,19 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackZIPGenerator_h
 #define cmCPackZIPGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCPackZIPGenerator
  * \brief A generator for ZIP files
@@ -27,10 +21,10 @@ public:
    * Construct generator
    */
   cmCPackZIPGenerator();
-  virtual ~cmCPackZIPGenerator();
+  ~cmCPackZIPGenerator() CM_OVERRIDE;
 
 protected:
-  virtual const char* GetOutputExtension() { return ".zip"; }
+  const char* GetOutputExtension() CM_OVERRIDE { return ".zip"; }
 };
 
 #endif
diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx
index 94e1615..5c45b14 100644
--- a/Source/CPack/cpack.cxx
+++ b/Source/CPack/cpack.cxx
@@ -1,39 +1,38 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include <cmConfigure.h>
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include "cmSystemTools.h"
-
-// Need these for documentation support.
 #include "cmCPackGenerator.h"
 #include "cmCPackGeneratorFactory.h"
+#include "cmCPackLog.h"
 #include "cmDocumentation.h"
+#include "cmDocumentationEntry.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTypeMacro.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
-#include "cmake.h"
-
-#include "cmCPackLog.h"
 
 #include <cmsys/CommandLineArguments.hxx>
 #include <cmsys/Encoding.hxx>
-#include <cmsys/SystemTools.hxx>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <utility>
+#include <vector>
 
 static const char* cmDocumentationName[][2] = {
-  { 0, "  cpack - Packaging driver provided by CMake." },
-  { 0, 0 }
+  { CM_NULLPTR, "  cpack - Packaging driver provided by CMake." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationUsage[][2] = {
-  { 0, "  cpack -G <generator> [options]" },
-  { 0, 0 }
+  { CM_NULLPTR, "  cpack -G <generator> [options]" },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationOptions[][2] = {
@@ -47,10 +46,10 @@ static const char* cmDocumentationOptions[][2] = {
   { "-R <package version>", "override/define CPACK_PACKAGE_VERSION" },
   { "-B <package directory>", "override/define CPACK_PACKAGE_DIRECTORY" },
   { "--vendor <vendor name>", "override/define CPACK_PACKAGE_VENDOR" },
-  { 0, 0 }
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
-int cpackUnknownArgument(const char*, void*)
+int cpackUnknownArgument(const char* /*unused*/, void* /*unused*/)
 {
   return 1;
 }
@@ -185,7 +184,7 @@ int main(int argc, char const* const* argv)
   cminst.GetCurrentSnapshot().SetDefaultDefinitions();
   cminst.GetState()->RemoveUnscriptableCommands();
   cmGlobalGenerator cmgg(&cminst);
-  cmsys::auto_ptr<cmMakefile> globalMF(
+  CM_AUTO_PTR<cmMakefile> globalMF(
     new cmMakefile(&cmgg, cminst.GetCurrentSnapshot()));
 #if defined(__CYGWIN__)
   globalMF->AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0");
@@ -200,7 +199,7 @@ int main(int argc, char const* const* argv)
 
   cmCPackGeneratorFactory generators;
   generators.SetLogger(&log);
-  cmCPackGenerator* cpackGenerator = 0;
+  cmCPackGenerator* cpackGenerator = CM_NULLPTR;
 
   cmDocumentation doc;
   doc.addCPackStandardDocSections();
@@ -209,11 +208,7 @@ int main(int argc, char const* const* argv)
    * should launch cpack using "cpackConfigFile" if it exists
    * in the current directory.
    */
-  if ((doc.CheckOptions(argc, argv, "-G")) && !(argc == 1)) {
-    help = true;
-  } else {
-    help = false;
-  }
+  help = doc.CheckOptions(argc, argv, "-G") && argc != 1;
 
   // This part is used for cpack documentation lookup as well.
   cminst.AddCMakePaths();
diff --git a/Source/CPack/cygwin.readme b/Source/CPack/cygwin.readme
deleted file mode 100644
index c0cd4b9..0000000
--- a/Source/CPack/cygwin.readme
+++ /dev/null
@@ -1,69 +0,0 @@
-http://cygwin.com/setup.html
-
-
-Need to produce two tar files:
-
-Source-
-
-- create subdirs
-- copy src
-- duplicate src
-- configure files into duplicate src
-   CPack.cygwin-readme.in
-   CPack.cygwin-install.sh.in
-   CPack.setup.hint.in
-- diff duplicate src and orig src
-- write diff into toplevel
-- create tar file call super class
-
-cmake-2.2.3-1
-
-
-1. a source release
-cmake-2.2.3-2-src.tar.bz2
-
-cmake-2.2.3-2.patch  has cmake-2.2.3/CYGWIN-PATCHES/cmake.README cmake-2.2.3/CYGWIN-PATCHES/setup.hint
-cmake-2.2.3-2.sh  -> script to create cygwin release
-cmake-2.2.3.tar.bz2  -> unmodified cmake sources for 2.2.3
-
-
-
-
-
-2 a binary release
-cmake-2.2.3-2.tar.bz2
-
-normal binary release with use as the root of the tree:
-
-Here is the bootstrap command used:
-
-  ${SOURCE_DIR}/bootstrap --prefix=/usr --datadir=/share/cmake-${VER} \
-                          --docdir=/share/doc/cmake-${VER} --mandir=/share/man
-
-CMAKE_DOC_DIR    /share/doc/${PKG}-${VER}
-CMAKE_MAN_DIR    /share/man
-CMAKE_DATA_DIR   /share/${PKG}-${VER}
-
-Here is the directory stucture:
-
-usr/bin/cmake.exe
-usr/share/doc/cmake-2.2.3/MANIFEST    ***
-usr/share/doc/Cygwin/cmake-2.2.3-2.README   ****
-usr/share/cmake-2.2.3/Modules
-
-
-
-usr/bin
-usr/share/cmake-2.2.3/include
-usr/share/cmake-2.2.3/Modules/Platform
-usr/share/cmake-2.2.3/Modules
-usr/share/cmake-2.2.3/Templates
-usr/share/cmake-2.2.3
-usr/share/doc/cmake-2.2.3
-usr/share/doc/Cygwin
-usr/share/doc
-usr/share/man/man1
-usr/share/man
-usr/share
-usr
-
diff --git a/Source/CTest/cmCTestBZR.cxx b/Source/CTest/cmCTestBZR.cxx
index dd53be8..b42953b 100644
--- a/Source/CTest/cmCTestBZR.cxx
+++ b/Source/CTest/cmCTestBZR.cxx
@@ -1,25 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestBZR.h"
 
 #include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 #include "cmXMLParser.h"
 
-#include <cmsys/RegularExpression.hxx>
-
 #include <cm_expat.h>
+#include <cmsys/RegularExpression.hxx>
+#include <list>
+#include <map>
+#include <ostream>
+#include <stdlib.h>
+#include <vector>
 
-extern "C" int cmBZRXMLParserUnknownEncodingHandler(void*,
+extern "C" int cmBZRXMLParserUnknownEncodingHandler(void* /*unused*/,
                                                     const XML_Char* name,
                                                     XML_Encoding* info)
 {
@@ -61,8 +58,9 @@ extern "C" int cmBZRXMLParserUnknownEncodingHandler(void*,
   // workaround for these unknown encodings.
   if (name == std::string("ascii") || name == std::string("cp1252") ||
       name == std::string("ANSI_X3.4-1968")) {
-    for (unsigned int i = 0; i < 256; ++i)
+    for (unsigned int i = 0; i < 256; ++i) {
       info->map[i] = latin1[i];
+    }
     return 1;
   }
 
@@ -100,7 +98,7 @@ private:
   bool CheckOutFound;
   cmsys::RegularExpression RegexCheckOut;
   cmsys::RegularExpression RegexParent;
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexCheckOut.find(this->Line)) {
       this->BZR->URL = this->RegexCheckOut.match(1);
@@ -125,7 +123,7 @@ public:
 private:
   std::string& Rev;
   cmsys::RegularExpression RegexRevno;
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexRevno.find(this->Line)) {
       this->Rev = this->RegexRevno.match(1);
@@ -138,13 +136,13 @@ std::string cmCTestBZR::LoadInfo()
 {
   // Run "bzr info" to get the repository info from the work tree.
   const char* bzr = this->CommandLineTool.c_str();
-  const char* bzr_info[] = { bzr, "info", 0 };
+  const char* bzr_info[] = { bzr, "info", CM_NULLPTR };
   InfoParser iout(this, "info-out> ");
   OutputLogger ierr(this->Log, "info-err> ");
   this->RunChild(bzr_info, &iout, &ierr);
 
   // Run "bzr revno" to get the repository revision number from the work tree.
-  const char* bzr_revno[] = { bzr, "revno", 0 };
+  const char* bzr_revno[] = { bzr, "revno", CM_NULLPTR };
   std::string rev;
   RevnoParser rout(this, "revno-out> ", rev);
   OutputLogger rerr(this->Log, "revno-err> ");
@@ -182,14 +180,15 @@ public:
   {
     this->InitializeParser();
   }
-  ~LogParser() { this->CleanupParser(); }
+  ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
 
-  virtual int InitializeParser()
+  int InitializeParser() CM_OVERRIDE
   {
     int res = cmXMLParser::InitializeParser();
     if (res) {
       XML_SetUnknownEncodingHandler(static_cast<XML_Parser>(this->Parser),
-                                    cmBZRXMLParserUnknownEncodingHandler, 0);
+                                    cmBZRXMLParserUnknownEncodingHandler,
+                                    CM_NULLPTR);
     }
     return res;
   }
@@ -206,14 +205,14 @@ private:
 
   cmsys::RegularExpression EmailRegex;
 
-  virtual bool ProcessChunk(const char* data, int length)
+  bool ProcessChunk(const char* data, int length) CM_OVERRIDE
   {
     this->OutputLogger::ProcessChunk(data, length);
     this->ParseChunk(data, length);
     return true;
   }
 
-  virtual void StartElement(const std::string& name, const char**)
+  void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE
   {
     this->CData.clear();
     if (name == "log") {
@@ -238,12 +237,12 @@ private:
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     this->CData.insert(this->CData.end(), data, data + length);
   }
 
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "log") {
       this->BZR->DoRevision(this->Rev, this->Changes);
@@ -273,7 +272,7 @@ private:
     this->CData.clear();
   }
 
-  virtual void ReportError(int, int, const char* msg)
+  void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
   {
     this->BZR->Log << "Error parsing bzr log xml: " << msg << "\n";
   }
@@ -293,7 +292,7 @@ private:
   cmCTestBZR* BZR;
   cmsys::RegularExpression RegexUpdate;
 
-  virtual bool ProcessChunk(const char* first, int length)
+  bool ProcessChunk(const char* first, int length) CM_OVERRIDE
   {
     bool last_is_new_line = (*first == '\r' || *first == '\n');
 
@@ -324,7 +323,7 @@ private:
     return true;
   }
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexUpdate.find(this->Line)) {
       this->DoPath(this->RegexUpdate.match(1)[0],
@@ -336,8 +335,9 @@ private:
 
   void DoPath(char c0, char c1, char c2, std::string path)
   {
-    if (path.empty())
+    if (path.empty()) {
       return;
+    }
     cmSystemTools::ConvertToUnixSlashes(path);
 
     const std::string dir = cmSystemTools::GetFilenamePath(path);
@@ -378,7 +378,7 @@ bool cmCTestBZR::UpdateImpl()
 
   bzr_update.push_back(this->URL.c_str());
 
-  bzr_update.push_back(0);
+  bzr_update.push_back(CM_NULLPTR);
 
   // For some reason bzr uses stderr to display the update status.
   OutputLogger out(this->Log, "pull-out> ");
@@ -406,7 +406,8 @@ void cmCTestBZR::LoadRevisions()
   // Run "bzr log" to get all global revisions of interest.
   const char* bzr = this->CommandLineTool.c_str();
   const char* bzr_log[] = {
-    bzr, "log", "-v", "-r", revs.c_str(), "--xml", this->URL.c_str(), 0
+    bzr,       "log", "-v", "-r", revs.c_str(), "--xml", this->URL.c_str(),
+    CM_NULLPTR
   };
   {
     LogParser out(this, "log-out> ");
@@ -429,7 +430,7 @@ public:
 private:
   cmCTestBZR* BZR;
   cmsys::RegularExpression RegexStatus;
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexStatus.find(this->Line)) {
       this->DoPath(this->RegexStatus.match(1)[0],
@@ -441,8 +442,9 @@ private:
 
   void DoPath(char c0, char c1, char c2, std::string path)
   {
-    if (path.empty())
+    if (path.empty()) {
       return;
+    }
     cmSystemTools::ConvertToUnixSlashes(path);
 
     if (c0 == 'C') {
@@ -462,7 +464,7 @@ void cmCTestBZR::LoadModifications()
 {
   // Run "bzr status" which reports local modifications.
   const char* bzr = this->CommandLineTool.c_str();
-  const char* bzr_status[] = { bzr, "status", "-SV", 0 };
+  const char* bzr_status[] = { bzr, "status", "-SV", CM_NULLPTR };
   StatusParser out(this, "status-out> ");
   OutputLogger err(this->Log, "status-err> ");
   this->RunChild(bzr_status, &out, &err);
diff --git a/Source/CTest/cmCTestBZR.h b/Source/CTest/cmCTestBZR.h
index 4f44136..e7af90b 100644
--- a/Source/CTest/cmCTestBZR.h
+++ b/Source/CTest/cmCTestBZR.h
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestBZR_h
 #define cmCTestBZR_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGlobalVC.h"
 
+#include <iosfwd>
+#include <string>
+
+class cmCTest;
+
 /** \class cmCTestBZR
  * \brief Interaction with bzr command-line tool
  *
@@ -24,30 +22,31 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestBZR(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestBZR();
+  ~cmCTestBZR() CM_OVERRIDE;
 
 private:
   // Implement cmCTestVC internal API.
-  virtual void NoteOldRevision();
-  virtual void NoteNewRevision();
-  virtual bool UpdateImpl();
+  void NoteOldRevision() CM_OVERRIDE;
+  void NoteNewRevision() CM_OVERRIDE;
+  bool UpdateImpl() CM_OVERRIDE;
 
   // URL of repository directory checked out in the working tree.
   std::string URL;
 
   std::string LoadInfo();
-  void LoadModifications();
-  void LoadRevisions();
+  void LoadModifications() CM_OVERRIDE;
+  void LoadRevisions() CM_OVERRIDE;
 
   // Parsing helper classes.
   class InfoParser;
-  class RevnoParser;
   class LogParser;
-  class UpdateParser;
+  class RevnoParser;
   class StatusParser;
+  class UpdateParser;
+
   friend class InfoParser;
-  friend class RevnoParser;
   friend class LogParser;
+  friend class RevnoParser;
   friend class UpdateParser;
   friend class StatusParser;
 };
diff --git a/Source/CTest/cmCTestBatchTestHandler.cxx b/Source/CTest/cmCTestBatchTestHandler.cxx
index 386c8d5..beee53a 100644
--- a/Source/CTest/cmCTestBatchTestHandler.cxx
+++ b/Source/CTest/cmCTestBatchTestHandler.cxx
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestBatchTestHandler.h"
 
 #include "cmCTest.h"
+#include "cmCTestMultiProcessHandler.h"
+#include "cmCTestTestHandler.h"
 #include "cmProcess.h"
-#include "cmStandardIncludes.h"
 #include "cmSystemTools.h"
-#include <stdlib.h>
+
+#include <map>
+#include <utility>
+#include <vector>
 
 cmCTestBatchTestHandler::~cmCTestBatchTestHandler()
 {
@@ -45,7 +39,7 @@ void cmCTestBatchTestHandler::WriteBatchScript()
   fout.close();
 }
 
-void cmCTestBatchTestHandler::WriteSrunArgs(int test, cmsys::ofstream& fout)
+void cmCTestBatchTestHandler::WriteSrunArgs(int test, std::ostream& fout)
 {
   cmCTestTestHandler::cmCTestTestProperties* properties =
     this->Properties[test];
@@ -73,7 +67,7 @@ void cmCTestBatchTestHandler::WriteSrunArgs(int test, cmsys::ofstream& fout)
   }
 }
 
-void cmCTestBatchTestHandler::WriteTestCommand(int test, cmsys::ofstream& fout)
+void cmCTestBatchTestHandler::WriteTestCommand(int test, std::ostream& fout)
 {
   std::vector<std::string> args = this->Properties[test]->Args;
   std::vector<std::string> processArgs;
diff --git a/Source/CTest/cmCTestBatchTestHandler.h b/Source/CTest/cmCTestBatchTestHandler.h
index 7a2a4a2..44db252 100644
--- a/Source/CTest/cmCTestBatchTestHandler.h
+++ b/Source/CTest/cmCTestBatchTestHandler.h
@@ -1,24 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestBatchTestHandler_h
 #define cmCTestBatchTestHandler_h
 
-#include <cmStandardIncludes.h>
+#include <cmConfigure.h>
 
 #include <cmCTestMultiProcessHandler.h>
-#include <cmCTestRunTest.h>
-#include <cmCTestTestHandler.h>
 #include <cmsys/FStream.hxx>
+#include <string>
 
 /** \class cmCTestBatchTestHandler
  * \brief run parallel ctest
@@ -28,13 +17,13 @@
 class cmCTestBatchTestHandler : public cmCTestMultiProcessHandler
 {
 public:
-  ~cmCTestBatchTestHandler();
-  virtual void RunTests();
+  ~cmCTestBatchTestHandler() CM_OVERRIDE;
+  void RunTests() CM_OVERRIDE;
 
 protected:
   void WriteBatchScript();
-  void WriteSrunArgs(int test, cmsys::ofstream& fout);
-  void WriteTestCommand(int test, cmsys::ofstream& fout);
+  void WriteSrunArgs(int test, std::ostream& fout);
+  void WriteTestCommand(int test, std::ostream& fout);
 
   void SubmitBatchScript();
 
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx
index 0cba8b2..6780a0e 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.cxx
+++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestBuildAndTestHandler.h"
 
 #include "cmCTest.h"
@@ -17,7 +7,9 @@
 #include "cmGlobalGenerator.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
+
 #include <cmsys/Process.h>
+#include <stdlib.h>
 
 cmCTestBuildAndTestHandler::cmCTestBuildAndTestHandler()
 {
@@ -72,7 +64,7 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
     args.push_back(toolset);
   }
 
-  const char* config = 0;
+  const char* config = CM_NULLPTR;
   if (!this->CTest->GetConfigType().empty()) {
     config = this->CTest->GetConfigType().c_str();
   }
@@ -123,14 +115,15 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
   return 0;
 }
 
-void CMakeMessageCallback(const char* m, const char*, bool&, void* s)
+void CMakeMessageCallback(const char* m, const char* /*unused*/,
+                          bool& /*unused*/, void* s)
 {
   std::string* out = (std::string*)s;
   *out += m;
   *out += "\n";
 }
 
-void CMakeProgressCallback(const char* msg, float, void* s)
+void CMakeProgressCallback(const char* msg, float /*unused*/, void* s)
 {
   std::string* out = (std::string*)s;
   *out += msg;
@@ -158,10 +151,10 @@ public:
   }
   ~cmCTestBuildAndTestCaptureRAII()
   {
-    this->CM.SetProgressCallback(0, 0);
-    cmSystemTools::SetStderrCallback(0, 0);
-    cmSystemTools::SetStdoutCallback(0, 0);
-    cmSystemTools::SetMessageCallback(0, 0);
+    this->CM.SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
+    cmSystemTools::SetStderrCallback(CM_NULLPTR, CM_NULLPTR);
+    cmSystemTools::SetStdoutCallback(CM_NULLPTR, CM_NULLPTR);
+    cmSystemTools::SetMessageCallback(CM_NULLPTR, CM_NULLPTR);
   }
 };
 
@@ -247,7 +240,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
       }
     }
     std::string output;
-    const char* config = 0;
+    const char* config = CM_NULLPTR;
     if (!this->CTest->GetConfigType().empty()) {
       config = this->CTest->GetConfigType().c_str();
     }
@@ -302,7 +295,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
     out << "Could not find path to executable, perhaps it was not built: "
         << this->TestCommand << "\n";
     out << "tried to find it in these places:\n";
-    out << fullPath.c_str() << "\n";
+    out << fullPath << "\n";
     for (unsigned int i = 0; i < failed.size(); ++i) {
       out << failed[i] << "\n";
     }
@@ -321,7 +314,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
   for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) {
     testCommand.push_back(this->TestCommandArgs[k].c_str());
   }
-  testCommand.push_back(0);
+  testCommand.push_back(CM_NULLPTR);
   std::string outs;
   int retval = 0;
   // run the test from the this->BuildRunDir if set
@@ -347,8 +340,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
     }
   }
 
-  int runTestRes =
-    this->CTest->RunTest(testCommand, &outs, &retval, 0, remainingTime, 0);
+  int runTestRes = this->CTest->RunTest(testCommand, &outs, &retval,
+                                        CM_NULLPTR, remainingTime, CM_NULLPTR);
 
   if (runTestRes != cmsysProcess_State_Exited || retval != 0) {
     out << "Test command failed: " << testCommand[0] << "\n";
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.h b/Source/CTest/cmCTestBuildAndTestHandler.h
index d0443ae..8d787ea 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.h
+++ b/Source/CTest/cmCTestBuildAndTestHandler.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestBuildAndTestHandler_h
 #define cmCTestBuildAndTestHandler_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGenericHandler.h"
-#include "cmListFileCache.h"
+#include "cmTypeMacro.h"
+
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmake;
 
@@ -30,12 +27,12 @@ public:
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   //! Set all the build and test arguments
-  virtual int ProcessCommandLineArguments(
-    const std::string& currentArg, size_t& idx,
-    const std::vector<std::string>& allArgs);
+  int ProcessCommandLineArguments(const std::string& currentArg, size_t& idx,
+                                  const std::vector<std::string>& allArgs)
+    CM_OVERRIDE;
 
   /*
    * Get the output variable
@@ -44,7 +41,7 @@ public:
 
   cmCTestBuildAndTestHandler();
 
-  virtual void Initialize();
+  void Initialize() CM_OVERRIDE;
 
 protected:
   ///! Run CMake and build a test and then run it as a single test.
diff --git a/Source/CTest/cmCTestBuildCommand.cxx b/Source/CTest/cmCTestBuildCommand.cxx
index 05cccbf..4c82760 100644
--- a/Source/CTest/cmCTestBuildCommand.cxx
+++ b/Source/CTest/cmCTestBuildCommand.cxx
@@ -1,32 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestBuildCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestBuildHandler.h"
 #include "cmCTestGenericHandler.h"
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
+#include <sstream>
+#include <string.h>
+
+class cmExecutionStatus;
+
 cmCTestBuildCommand::cmCTestBuildCommand()
 {
-  this->GlobalGenerator = 0;
+  this->GlobalGenerator = CM_NULLPTR;
   this->Arguments[ctb_NUMBER_ERRORS] = "NUMBER_ERRORS";
   this->Arguments[ctb_NUMBER_WARNINGS] = "NUMBER_WARNINGS";
   this->Arguments[ctb_TARGET] = "TARGET";
   this->Arguments[ctb_CONFIGURATION] = "CONFIGURATION";
   this->Arguments[ctb_FLAGS] = "FLAGS";
   this->Arguments[ctb_PROJECT_NAME] = "PROJECT_NAME";
-  this->Arguments[ctb_LAST] = 0;
+  this->Arguments[ctb_LAST] = CM_NULLPTR;
   this->Last = ctb_LAST;
 }
 
@@ -34,7 +32,7 @@ cmCTestBuildCommand::~cmCTestBuildCommand()
 {
   if (this->GlobalGenerator) {
     delete this->GlobalGenerator;
-    this->GlobalGenerator = 0;
+    this->GlobalGenerator = CM_NULLPTR;
   }
 }
 
@@ -43,7 +41,7 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
   cmCTestGenericHandler* handler = this->CTest->GetInitializedHandler("build");
   if (!handler) {
     this->SetError("internal CTest error. Cannot instantiate build handler");
-    return 0;
+    return CM_NULLPTR;
   }
   this->Handler = (cmCTestBuildHandler*)handler;
 
@@ -91,7 +89,7 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
       if (this->GlobalGenerator) {
         if (this->GlobalGenerator->GetName() != cmakeGeneratorName) {
           delete this->GlobalGenerator;
-          this->GlobalGenerator = 0;
+          this->GlobalGenerator = CM_NULLPTR;
         }
       }
       if (!this->GlobalGenerator) {
@@ -104,11 +102,11 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
           e += "\"";
           this->Makefile->IssueMessage(cmake::FATAL_ERROR, e);
           cmSystemTools::SetFatalErrorOccured();
-          return 0;
+          return CM_NULLPTR;
         }
       }
       if (strlen(cmakeBuildConfiguration) == 0) {
-        const char* config = 0;
+        const char* config = CM_NULLPTR;
 #ifdef CMAKE_INTDIR
         config = CMAKE_INTDIR;
 #endif
@@ -145,7 +143,7 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
         "with a custom command line.";
       /* clang-format on */
       this->SetError(ostr.str());
-      return 0;
+      return CM_NULLPTR;
     }
   }
 
diff --git a/Source/CTest/cmCTestBuildCommand.h b/Source/CTest/cmCTestBuildCommand.h
index f420c2f..0aaf623 100644
--- a/Source/CTest/cmCTestBuildCommand.h
+++ b/Source/CTest/cmCTestBuildCommand.h
@@ -1,21 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestBuildCommand_h
 #define cmCTestBuildCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
 
-class cmGlobalGenerator;
 class cmCTestBuildHandler;
+class cmCTestGenericHandler;
+class cmCommand;
+class cmExecutionStatus;
+class cmGlobalGenerator;
 
 /** \class cmCTestBuild
  * \brief Run a ctest script
@@ -26,12 +26,12 @@ class cmCTestBuildCommand : public cmCTestHandlerCommand
 {
 public:
   cmCTestBuildCommand();
-  ~cmCTestBuildCommand();
+  ~cmCTestBuildCommand() CM_OVERRIDE;
 
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestBuildCommand* ni = new cmCTestBuildCommand;
     ni->CTest = this->CTest;
@@ -42,10 +42,10 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_build"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_build"; }
 
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   cmTypeMacro(cmCTestBuildCommand, cmCTestHandlerCommand);
 
@@ -65,7 +65,7 @@ protected:
     ctb_LAST
   };
 
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx
index 7141daf..7b4d994 100644
--- a/Source/CTest/cmCTestBuildHandler.cxx
+++ b/Source/CTest/cmCTestBuildHandler.cxx
@@ -1,40 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestBuildHandler.h"
 
 #include "cmAlgorithms.h"
 #include "cmCTest.h"
 #include "cmFileTimeComparison.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmXMLWriter.h"
-#include "cmake.h"
 
-//#include <cmsys/RegularExpression.hxx>
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Process.h>
-
-// used for sleep
-#ifdef _WIN32
-#include "windows.h"
-#endif
-
-#include <float.h>
-#include <math.h>
+#include <set>
 #include <stdlib.h>
-#include <time.h>
+#include <string.h>
 
 static const char* cmCTestErrorMatches[] = {
   "^[Bb]us [Ee]rror",
@@ -92,7 +73,7 @@ static const char* cmCTestErrorMatches[] = {
   "^The project cannot be built\\.",
   "^\\[ERROR\\]",
   "^Command .* failed with exit code",
-  0
+  CM_NULLPTR
 };
 
 static const char* cmCTestErrorExceptions[] = {
@@ -107,7 +88,7 @@ static const char* cmCTestErrorExceptions[] = {
   ":[ \\t]+Where:",
   "([^ :]+):([0-9]+): Warning",
   "------ Build started: .* ------",
-  0
+  CM_NULLPTR
 };
 
 static const char* cmCTestWarningMatches[] = {
@@ -132,7 +113,7 @@ static const char* cmCTestWarningMatches[] = {
   "cc-[0-9]* CC: REMARK File = .*, Line = [0-9]*",
   "^CMake Warning.*:",
   "^\\[WARNING\\]",
-  0
+  CM_NULLPTR
 };
 
 static const char* cmCTestWarningExceptions[] = {
@@ -152,7 +133,7 @@ static const char* cmCTestWarningExceptions[] = {
   "ld32: WARNING 85: definition of dataKey in",
   "cc: warning 422: Unknown option \"\\+b",
   "_with_warning_C",
-  0
+  CM_NULLPTR
 };
 
 struct cmCTestBuildCompileErrorWarningRex
@@ -170,7 +151,7 @@ static cmCTestBuildCompileErrorWarningRex cmCTestWarningErrorFileLine[] = {
   { "^([a-zA-Z./0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
   { "\"([a-zA-Z./0-9_+ ~-]+)\", line ([0-9]+)", 1, 2 },
   { "File = ([a-zA-Z./0-9_+ ~-]+), Line = ([0-9]+)", 1, 2 },
-  { 0, 0, 0 }
+  { CM_NULLPTR, 0, 0 }
 };
 
 cmCTestBuildHandler::cmCTestBuildHandler()
@@ -375,11 +356,11 @@ int cmCTestBuildHandler::ProcessHandler()
   regexes.clear();                                                            \
   cmCTestOptionalLog(this->CTest, DEBUG,                                      \
                      this << "Add " #regexes << std::endl, this->Quiet);      \
-  for (it = strings.begin(); it != strings.end(); ++it) {                     \
+  for (it = (strings).begin(); it != (strings).end(); ++it) {                 \
     cmCTestOptionalLog(this->CTest, DEBUG,                                    \
                        "Add " #strings ": " << *it << std::endl,              \
                        this->Quiet);                                          \
-    regexes.push_back(it->c_str());                                           \
+    (regexes).push_back(it->c_str());                                         \
   }
   cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorMatches,
                                          this->ErrorMatchRegex);
@@ -521,7 +502,7 @@ public:
   {
   }
   FragmentCompare()
-    : FTC(0)
+    : FTC(CM_NULLPTR)
   {
   }
   bool operator()(std::string const& l, std::string const& r)
@@ -532,9 +513,8 @@ public:
     if (this->FTC->FileTimeCompare(l.c_str(), r.c_str(), &result) &&
         result != 0) {
       return result < 0;
-    } else {
-      return l < r;
     }
+    return l < r;
   }
 
 private:
@@ -790,7 +770,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
   // First generate the command and arguments
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
 
-  if (args.size() < 1) {
+  if (args.empty()) {
     return false;
   }
 
@@ -799,7 +779,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
        a != args.end(); ++a) {
     argv.push_back(a->c_str());
   }
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run command:",
                      this->Quiet);
@@ -851,7 +831,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
 
   // For every chunk of data
   int res;
-  while ((res = cmsysProcess_WaitForData(cp, &data, &length, 0))) {
+  while ((res = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR))) {
     // Replace '\0' with '\n', since '\0' does not really make sense. This is
     // for Visual Studio output
     for (int cc = 0; cc < length; ++cc) {
@@ -870,8 +850,9 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
     }
   }
 
-  this->ProcessBuffer(0, 0, tick, tick_len, ofs, &this->BuildProcessingQueue);
-  this->ProcessBuffer(0, 0, tick, tick_len, ofs,
+  this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
+                      &this->BuildProcessingQueue);
+  this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
                       &this->BuildProcessingErrorQueue);
   cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT, " Size of output: "
                        << ((this->BuildOutputLogSize + 512) / 1024) << "K"
@@ -879,7 +860,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
                      this->Quiet);
 
   // Properly handle output of the build command
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   int result = cmsysProcess_GetState(cp);
 
   if (result == cmsysProcess_State_Exited) {
diff --git a/Source/CTest/cmCTestBuildHandler.h b/Source/CTest/cmCTestBuildHandler.h
index 48a37b7..16563ce 100644
--- a/Source/CTest/cmCTestBuildHandler.h
+++ b/Source/CTest/cmCTestBuildHandler.h
@@ -1,25 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestBuildHandler_h
 #define cmCTestBuildHandler_h
 
-#include "cmCTestGenericHandler.h"
+#include <cmConfigure.h>
 
-#include "cmListFileCache.h"
+#include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
 #include <cmsys/RegularExpression.hxx>
-
 #include <deque>
+#include <iosfwd>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmMakefile;
 class cmXMLWriter;
@@ -36,16 +30,16 @@ public:
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   cmCTestBuildHandler();
 
-  void PopulateCustomVectors(cmMakefile* mf);
+  void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
 
   /**
    * Initialize handler
    */
-  virtual void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   int GetTotalErrors() { return this->TotalErrors; }
   int GetTotalWarnings() { return this->TotalWarnings; }
@@ -148,6 +142,7 @@ private:
   bool UseCTestLaunch;
   std::string CTestLaunchDir;
   class LaunchHelper;
+
   friend class LaunchHelper;
   class FragmentCompare;
 };
diff --git a/Source/CTest/cmCTestCVS.cxx b/Source/CTest/cmCTestCVS.cxx
index 5ddafbb..98bb678 100644
--- a/Source/CTest/cmCTestCVS.cxx
+++ b/Source/CTest/cmCTestCVS.cxx
@@ -1,22 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestCVS.h"
 
 #include "cmCTest.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 
 #include <cmsys/FStream.hxx>
 #include <cmsys/RegularExpression.hxx>
+#include <utility>
 
 cmCTestCVS::cmCTestCVS(cmCTest* ct, std::ostream& log)
   : cmCTestVC(ct, log)
@@ -53,7 +46,7 @@ private:
   cmsys::RegularExpression RegexFileRemoved1;
   cmsys::RegularExpression RegexFileRemoved2;
 
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexFileUpdated.find(this->Line)) {
       this->DoFile(PathUpdated, this->RegexFileUpdated.match(2));
@@ -103,7 +96,7 @@ bool cmCTestCVS::UpdateImpl()
        ai != args.end(); ++ai) {
     cvs_update.push_back(ai->c_str());
   }
-  cvs_update.push_back(0);
+  cvs_update.push_back(CM_NULLPTR);
 
   UpdateParser out(this, "up-out> ");
   UpdateParser err(this, "up-err> ");
@@ -140,7 +133,7 @@ private:
   SectionType Section;
   Revision Rev;
 
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->Line == ("======================================="
                        "======================================")) {
@@ -216,10 +209,9 @@ std::string cmCTestCVS::ComputeBranchFlag(std::string const& dir)
     std::string flag = "-r";
     flag += tagLine.substr(1);
     return flag;
-  } else {
-    // Use the default branch.
-    return "-b";
   }
+  // Use the default branch.
+  return "-b";
 }
 
 void cmCTestCVS::LoadRevisions(std::string const& file, const char* branchFlag,
@@ -229,7 +221,8 @@ void cmCTestCVS::LoadRevisions(std::string const& file, const char* branchFlag,
 
   // Run "cvs log" to get revisions of this file on this branch.
   const char* cvs = this->CommandLineTool.c_str();
-  const char* cvs_log[] = { cvs, "log", "-N", branchFlag, file.c_str(), 0 };
+  const char* cvs_log[] = { cvs,        "log",        "-N",
+                            branchFlag, file.c_str(), CM_NULLPTR };
 
   LogParser out(this, "log-out> ", revisions);
   OutputLogger err(this->Log, "log-err> ");
diff --git a/Source/CTest/cmCTestCVS.h b/Source/CTest/cmCTestCVS.h
index 62fe01b..d921b1a 100644
--- a/Source/CTest/cmCTestCVS.h
+++ b/Source/CTest/cmCTestCVS.h
@@ -1,19 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestCVS_h
 #define cmCTestCVS_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestVC.h"
 
+#include <iosfwd>
+#include <map>
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmXMLWriter;
+
 /** \class cmCTestCVS
  * \brief Interaction with cvs command-line tool
  *
@@ -24,12 +25,12 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestCVS(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestCVS();
+  ~cmCTestCVS() CM_OVERRIDE;
 
 private:
   // Implement cmCTestVC internal API.
-  virtual bool UpdateImpl();
-  virtual bool WriteXMLUpdates(cmXMLWriter& xml);
+  bool UpdateImpl() CM_OVERRIDE;
+  bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE;
 
   // Update status for files in each directory.
   class Directory : public std::map<std::string, PathStatus>
@@ -44,10 +45,11 @@ private:
                          Directory const& dir);
 
   // Parsing helper classes.
-  class UpdateParser;
   class LogParser;
-  friend class UpdateParser;
+  class UpdateParser;
+
   friend class LogParser;
+  friend class UpdateParser;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestCommand.h b/Source/CTest/cmCTestCommand.h
index 22a2c8e..2b9b93b 100644
--- a/Source/CTest/cmCTestCommand.h
+++ b/Source/CTest/cmCTestCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestCommand_h
 #define cmCTestCommand_h
 
@@ -29,8 +20,8 @@ class cmCTestCommand : public cmCommand
 public:
   cmCTestCommand()
   {
-    this->CTest = 0;
-    this->CTestScriptHandler = 0;
+    this->CTest = CM_NULLPTR;
+    this->CTestScriptHandler = CM_NULLPTR;
   }
 
   cmCTest* CTest;
diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx
index a90f27a..62802ef 100644
--- a/Source/CTest/cmCTestConfigureCommand.cxx
+++ b/Source/CTest/cmCTestConfigureCommand.cxx
@@ -1,24 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestConfigureCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <sstream>
+#include <string.h>
+#include <vector>
 
 cmCTestConfigureCommand::cmCTestConfigureCommand()
 {
   this->Arguments[ctc_OPTIONS] = "OPTIONS";
-  this->Arguments[ctc_LAST] = 0;
+  this->Arguments[ctc_LAST] = CM_NULLPTR;
   this->Last = ctc_LAST;
 }
 
@@ -35,7 +33,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
       "Build directory not specified. Either use BUILD "
       "argument to CTEST_CONFIGURE command or set CTEST_BINARY_DIRECTORY "
       "variable");
-    return 0;
+    return CM_NULLPTR;
   }
 
   const char* ctestConfigureCommand =
@@ -55,7 +53,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
           "Source directory not specified. Either use SOURCE "
           "argument to CTEST_CONFIGURE command or set CTEST_SOURCE_DIRECTORY "
           "variable");
-        return 0;
+        return CM_NULLPTR;
       }
 
       const std::string cmakelists_file = source_dir + "/CMakeLists.txt";
@@ -63,7 +61,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
         std::ostringstream e;
         e << "CMakeLists.txt file does not exist [" << cmakelists_file << "]";
         this->SetError(e.str());
-        return 0;
+        return CM_NULLPTR;
       }
 
       bool multiConfig = false;
@@ -90,8 +88,9 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
         cmakeConfigureCommand += option;
         cmakeConfigureCommand += "\"";
 
-        if ((0 != strstr(option.c_str(), "CMAKE_BUILD_TYPE=")) ||
-            (0 != strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING="))) {
+        if ((CM_NULLPTR != strstr(option.c_str(), "CMAKE_BUILD_TYPE=")) ||
+            (CM_NULLPTR !=
+             strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING="))) {
           cmakeBuildTypeInOptions = true;
         }
       }
@@ -134,7 +133,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
         "Configure command is not specified. If this is a "
         "\"built with CMake\" project, set CTEST_CMAKE_GENERATOR. If not, "
         "set CTEST_CONFIGURE_COMMAND.");
-      return 0;
+      return CM_NULLPTR;
     }
   }
 
@@ -143,7 +142,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
   if (!handler) {
     this->SetError(
       "internal CTest error. Cannot instantiate configure handler");
-    return 0;
+    return CM_NULLPTR;
   }
   handler->SetQuiet(this->Quiet);
   return handler;
diff --git a/Source/CTest/cmCTestConfigureCommand.h b/Source/CTest/cmCTestConfigureCommand.h
index 9ff3d4a..8bc69fe 100644
--- a/Source/CTest/cmCTestConfigureCommand.h
+++ b/Source/CTest/cmCTestConfigureCommand.h
@@ -1,18 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestConfigureCommand_h
 #define cmCTestConfigureCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+
+class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestConfigure
  * \brief Run a ctest script
@@ -27,7 +26,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestConfigureCommand* ni = new cmCTestConfigureCommand;
     ni->CTest = this->CTest;
@@ -38,12 +37,12 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_configure"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_configure"; }
 
   cmTypeMacro(cmCTestConfigureCommand, cmCTestHandlerCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
   enum
   {
diff --git a/Source/CTest/cmCTestConfigureHandler.cxx b/Source/CTest/cmCTestConfigureHandler.cxx
index b99455f..5d87f3f 100644
--- a/Source/CTest/cmCTestConfigureHandler.cxx
+++ b/Source/CTest/cmCTestConfigureHandler.cxx
@@ -1,22 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestConfigureHandler.h"
 
 #include "cmCTest.h"
 #include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
 #include "cmXMLWriter.h"
-#include "cmake.h"
-#include <cmsys/Process.h>
+
+#include <ostream>
+#include <string>
 
 cmCTestConfigureHandler::cmCTestConfigureHandler()
 {
diff --git a/Source/CTest/cmCTestConfigureHandler.h b/Source/CTest/cmCTestConfigureHandler.h
index 4c1a96b..913e5c9 100644
--- a/Source/CTest/cmCTestConfigureHandler.h
+++ b/Source/CTest/cmCTestConfigureHandler.h
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestConfigureHandler_h
 #define cmCTestConfigureHandler_h
 
-#include "cmCTestGenericHandler.h"
+#include <cmConfigure.h>
 
-#include "cmListFileCache.h"
+#include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCTestConfigureHandler
  * \brief A class that handles ctest -S invocations
@@ -29,11 +20,11 @@ public:
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   cmCTestConfigureHandler();
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestCoverageCommand.cxx b/Source/CTest/cmCTestCoverageCommand.cxx
index 223d010..535da58 100644
--- a/Source/CTest/cmCTestCoverageCommand.cxx
+++ b/Source/CTest/cmCTestCoverageCommand.cxx
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestCoverageCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestCoverageHandler.h"
 
+class cmCTestGenericHandler;
+
 cmCTestCoverageCommand::cmCTestCoverageCommand()
 {
   this->LabelsMentioned = false;
@@ -30,7 +23,7 @@ cmCTestGenericHandler* cmCTestCoverageCommand::InitializeHandler()
     this->CTest->GetInitializedHandler("coverage"));
   if (!handler) {
     this->SetError("internal CTest error. Cannot instantiate test handler");
-    return 0;
+    return CM_NULLPTR;
   }
 
   // If a LABELS option was given, select only files with the labels.
diff --git a/Source/CTest/cmCTestCoverageCommand.h b/Source/CTest/cmCTestCoverageCommand.h
index f60ffd5..d54e68d 100644
--- a/Source/CTest/cmCTestCoverageCommand.h
+++ b/Source/CTest/cmCTestCoverageCommand.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestCoverageCommand_h
 #define cmCTestCoverageCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <set>
+#include <string>
+
+class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestCoverage
  * \brief Run a ctest script
@@ -27,7 +27,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestCoverageCommand* ni = new cmCTestCoverageCommand;
     ni->CTest = this->CTest;
@@ -38,15 +38,15 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_coverage"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_coverage"; }
 
   cmTypeMacro(cmCTestCoverageCommand, cmCTestHandlerCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
-  virtual bool CheckArgumentKeyword(std::string const& arg);
-  virtual bool CheckArgumentValue(std::string const& arg);
+  bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
+  bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
 
   enum
   {
diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx
index daefb59..b7ac969 100644
--- a/Source/CTest/cmCTestCoverageHandler.cxx
+++ b/Source/CTest/cmCTestCoverageHandler.cxx
@@ -1,19 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestCoverageHandler.h"
 
 #include "cmCTest.h"
 #include "cmGeneratedFileStream.h"
-#include "cmMakefile.h"
 #include "cmParseBlanketJSCoverage.h"
 #include "cmParseCacheCoverage.h"
 #include "cmParseCoberturaCoverage.h"
@@ -25,14 +15,19 @@
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
+#include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
 #include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
-
-#include <float.h>
-#include <math.h>
+#include <iomanip>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
 #include <stdlib.h>
+#include <utility>
+
+class cmMakefile;
 
 #define SAFEDIV(x, y) (((y) != 0) ? ((x) / (y)) : (0))
 
@@ -76,7 +71,7 @@ public:
          i != this->CommandLineStrings.end(); ++i) {
       args.push_back(i->c_str());
     }
-    args.push_back(0); // null terminate
+    args.push_back(CM_NULLPTR); // null terminate
     cmsysProcess_SetCommand(this->Process, &*args.begin());
     if (!this->WorkingDirectory.empty()) {
       cmsysProcess_SetWorkingDirectory(this->Process,
@@ -90,11 +85,8 @@ public:
     cmsysProcess_Execute(this->Process);
     this->PipeState = cmsysProcess_GetState(this->Process);
     // if the process is running or exited return true
-    if (this->PipeState == cmsysProcess_State_Executing ||
-        this->PipeState == cmsysProcess_State_Exited) {
-      return true;
-    }
-    return false;
+    return this->PipeState == cmsysProcess_State_Executing ||
+      this->PipeState == cmsysProcess_State_Exited;
   }
   void SetStdoutFile(const char* fname)
   {
@@ -104,7 +96,7 @@ public:
   {
     cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDERR, fname);
   }
-  int WaitForExit(double* timeout = 0)
+  int WaitForExit(double* timeout = CM_NULLPTR)
   {
     this->PipeState = cmsysProcess_WaitForExit(this->Process, timeout);
     return this->PipeState;
@@ -705,13 +697,8 @@ bool IsFileInDir(const std::string& infile, const std::string& indir)
   std::string file = cmSystemTools::CollapseFullPath(infile);
   std::string dir = cmSystemTools::CollapseFullPath(indir);
 
-  if (file.size() > dir.size() &&
-      (fnc(file.substr(0, dir.size())) == fnc(dir)) &&
-      file[dir.size()] == '/') {
-    return true;
-  }
-
-  return false;
+  return file.size() > dir.size() &&
+    fnc(file.substr(0, dir.size())) == fnc(dir) && file[dir.size()] == '/';
 }
 
 int cmCTestCoverageHandler::HandlePHPCoverage(
@@ -735,10 +722,8 @@ int cmCTestCoverageHandler::HandleCoberturaCoverage(
   // if it doesn't exist or is empty, assume the
   // binary directory is used.
   std::string coverageXMLFile;
-  const char* covDir = cmSystemTools::GetEnv("COBERTURADIR");
-  if (covDir && strlen(covDir) != 0) {
-    coverageXMLFile = std::string(covDir);
-  } else {
+  if (!cmSystemTools::GetEnv("COBERTURADIR", coverageXMLFile) ||
+      coverageXMLFile.empty()) {
     coverageXMLFile = this->CTest->GetBinaryDir();
   }
   // build the find file string with the directory from above
@@ -773,12 +758,11 @@ int cmCTestCoverageHandler::HandleMumpsCoverage(
                        this->Quiet);
     cov.ReadCoverageFile(coverageFile.c_str());
     return static_cast<int>(cont->TotalCoverage.size());
-  } else {
-    cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-                       " Cannot find GTM coverage file: " << coverageFile
-                                                          << std::endl,
-                       this->Quiet);
   }
+  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+                     " Cannot find GTM coverage file: " << coverageFile
+                                                        << std::endl,
+                     this->Quiet);
   cmParseCacheCoverage ccov(*cont, this->CTest);
   coverageFile = this->CTest->GetBinaryDir() + "/cache_coverage.cmcov";
   if (cmSystemTools::FileExists(coverageFile.c_str())) {
@@ -799,7 +783,8 @@ struct cmCTestCoverageHandlerLocale
 {
   cmCTestCoverageHandlerLocale()
   {
-    if (const char* l = cmSystemTools::GetEnv("LC_ALL")) {
+    std::string l;
+    if (cmSystemTools::GetEnv("LC_ALL", l)) {
       lc_all = l;
     }
     if (lc_all != "C") {
@@ -935,8 +920,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
   std::string gcovCommand =
     this->CTest->GetCTestConfiguration("CoverageCommand");
   if (gcovCommand.empty()) {
-    cmCTestLog(this->CTest, ERROR_MESSAGE, "Could not find gcov."
-                 << std::endl);
+    cmCTestLog(this->CTest, WARNING, "Could not find gcov." << std::endl);
     return 0;
   }
   std::string gcovExtraFlags =
@@ -1020,7 +1004,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
       "-o \"" + fileDir + "\" " + "\"" + *it + "\"";
 
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-                       command.c_str() << std::endl, this->Quiet);
+                       command << std::endl, this->Quiet);
 
     std::string output = "";
     std::string errors = "";
@@ -1385,7 +1369,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
                        "Current coverage dir: " << fileDir << std::endl,
                        this->Quiet);
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-                       command.c_str() << std::endl, this->Quiet);
+                       command << std::endl, this->Quiet);
 
     std::string output = "";
     std::string errors = "";
@@ -1789,7 +1773,7 @@ const char* bullseyeHelp[] = {
   "      condition evaluated true or false, respectively.",
   "    * A k indicates a constant decision or condition.",
   "    * The slash / means this probe is excluded from summary results. ",
-  0
+  CM_NULLPTR
 };
 }
 
@@ -1817,7 +1801,7 @@ int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
   cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                      "run covbr: " << std::endl, this->Quiet);
 
-  if (!this->RunBullseyeCommand(cont, "covbr", 0, outputFile)) {
+  if (!this->RunBullseyeCommand(cont, "covbr", CM_NULLPTR, outputFile)) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covbr for."
                  << "\n");
     return -1;
@@ -1890,7 +1874,7 @@ int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
         covLogXML.StartElement("Report");
         // write the bullseye header
         line = 0;
-        for (int k = 0; bullseyeHelp[k] != 0; ++k) {
+        for (int k = 0; bullseyeHelp[k] != CM_NULLPTR; ++k) {
           covLogXML.StartElement("Line");
           covLogXML.Attribute("Number", line);
           covLogXML.Attribute("Count", -1);
@@ -2129,8 +2113,8 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
 int cmCTestCoverageHandler::HandleBullseyeCoverage(
   cmCTestCoverageHandlerContainer* cont)
 {
-  const char* covfile = cmSystemTools::GetEnv("COVFILE");
-  if (!covfile || strlen(covfile) == 0) {
+  std::string covfile;
+  if (!cmSystemTools::GetEnv("COVFILE", covfile) || covfile.empty()) {
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                        " COVFILE environment variable not found, not running "
                        " bullseye\n",
diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h
index 1773218..062f971 100644
--- a/Source/CTest/cmCTestCoverageHandler.h
+++ b/Source/CTest/cmCTestCoverageHandler.h
@@ -1,26 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestCoverageHandler_h
 #define cmCTestCoverageHandler_h
 
-#include "cmCTestGenericHandler.h"
+#include <cmConfigure.h>
 
-#include "cmListFileCache.h"
+#include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
 #include <cmsys/RegularExpression.hxx>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmGeneratedFileStream;
+class cmMakefile;
 class cmXMLWriter;
+
 class cmCTestCoverageHandlerContainer
 {
 public:
@@ -45,16 +43,16 @@ public:
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   cmCTestCoverageHandler();
 
-  virtual void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   /**
    * This method is called when reading CTest custom file
    */
-  void PopulateCustomVectors(cmMakefile* mf);
+  void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
 
   /** Report coverage only for sources with these labels.  */
   void SetLabelFilter(std::set<std::string> const& labels);
diff --git a/Source/CTest/cmCTestCurl.cxx b/Source/CTest/cmCTestCurl.cxx
index 59675dd..a3c13c4 100644
--- a/Source/CTest/cmCTestCurl.cxx
+++ b/Source/CTest/cmCTestCurl.cxx
@@ -1,19 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestCurl.h"
 
 #include "cmCTest.h"
 #include "cmSystemTools.h"
 
+#include <cmConfigure.h>
+#include <ostream>
+#include <stdio.h>
+
 cmCTestCurl::cmCTestCurl(cmCTest* ctest)
 {
   this->CTest = ctest;
@@ -54,8 +49,8 @@ static size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
   return realsize;
 }
 
-static size_t curlDebugCallback(CURL*, curl_infotype, char* chPtr, size_t size,
-                                void* data)
+static size_t curlDebugCallback(CURL* /*unused*/, curl_infotype /*unused*/,
+                                char* chPtr, size_t size, void* data)
 {
   std::vector<char>* vec = static_cast<std::vector<char>*>(data);
   vec->insert(vec->end(), chPtr, chPtr + size);
@@ -88,10 +83,10 @@ bool cmCTestCurl::InitCurl()
   if (this->VerifyHostOff) {
     curl_easy_setopt(this->Curl, CURLOPT_SSL_VERIFYHOST, 0);
   }
-  if (this->HTTPProxy.size()) {
+  if (!this->HTTPProxy.empty()) {
     curl_easy_setopt(this->Curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
     curl_easy_setopt(this->Curl, CURLOPT_PROXYTYPE, this->HTTPProxyType);
-    if (this->HTTPProxyAuth.size() > 0) {
+    if (!this->HTTPProxyAuth.empty()) {
       curl_easy_setopt(this->Curl, CURLOPT_PROXYUSERPWD,
                        this->HTTPProxyAuth.c_str());
     }
@@ -147,7 +142,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
   ::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION, curlDebugCallback);
   // Be sure to set Content-Type to satisfy fussy modsecurity rules
   struct curl_slist* headers =
-    ::curl_slist_append(NULL, "Content-Type: text/xml");
+    ::curl_slist_append(CM_NULLPTR, "Content-Type: text/xml");
   ::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, headers);
   std::vector<char> responseData;
   std::vector<char> debugData;
@@ -160,17 +155,17 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
   ::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, NULL);
   ::curl_slist_free_all(headers);
 
-  if (responseData.size() > 0) {
+  if (!responseData.empty()) {
     response = std::string(responseData.begin(), responseData.end());
     cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Curl response: ["
                  << response << "]\n");
   }
   std::string curlDebug;
-  if (debugData.size() > 0) {
+  if (!debugData.empty()) {
     curlDebug = std::string(debugData.begin(), debugData.end());
     cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
   }
-  if (response.size() == 0) {
+  if (response.empty()) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "No response from server.\n"
                  << curlDebug);
     return false;
@@ -205,11 +200,11 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
 
   CURLcode res = ::curl_easy_perform(this->Curl);
 
-  if (responseData.size() > 0) {
+  if (!responseData.empty()) {
     response = std::string(responseData.begin(), responseData.end());
     cmCTestLog(this->CTest, DEBUG, "Curl response: [" << response << "]\n");
   }
-  if (debugData.size() > 0) {
+  if (!debugData.empty()) {
     std::string curlDebug = std::string(debugData.begin(), debugData.end());
     cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
   }
@@ -219,16 +214,18 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
 
 void cmCTestCurl::SetProxyType()
 {
-  if (cmSystemTools::GetEnv("HTTP_PROXY")) {
-    this->HTTPProxy = cmSystemTools::GetEnv("HTTP_PROXY");
-    if (cmSystemTools::GetEnv("HTTP_PROXY_PORT")) {
+  this->HTTPProxy = "";
+  // this is the default
+  this->HTTPProxyType = CURLPROXY_HTTP;
+  this->HTTPProxyAuth = "";
+  if (cmSystemTools::GetEnv("HTTP_PROXY", this->HTTPProxy)) {
+    std::string port;
+    if (cmSystemTools::GetEnv("HTTP_PROXY_PORT", port)) {
       this->HTTPProxy += ":";
-      this->HTTPProxy += cmSystemTools::GetEnv("HTTP_PROXY_PORT");
+      this->HTTPProxy += port;
     }
-    if (cmSystemTools::GetEnv("HTTP_PROXY_TYPE")) {
-      // this is the default
-      this->HTTPProxyType = CURLPROXY_HTTP;
-      std::string type = cmSystemTools::GetEnv("HTTP_PROXY_TYPE");
+    std::string type;
+    if (cmSystemTools::GetEnv("HTTP_PROXY_TYPE", type)) {
       // HTTP/SOCKS4/SOCKS5
       if (type == "HTTP") {
         this->HTTPProxyType = CURLPROXY_HTTP;
@@ -238,12 +235,11 @@ void cmCTestCurl::SetProxyType()
         this->HTTPProxyType = CURLPROXY_SOCKS5;
       }
     }
-    if (cmSystemTools::GetEnv("HTTP_PROXY_USER")) {
-      this->HTTPProxyAuth = cmSystemTools::GetEnv("HTTP_PROXY_USER");
-    }
-    if (cmSystemTools::GetEnv("HTTP_PROXY_PASSWD")) {
+    cmSystemTools::GetEnv("HTTP_PROXY_USER", this->HTTPProxyAuth);
+    std::string passwd;
+    if (cmSystemTools::GetEnv("HTTP_PROXY_PASSWD", passwd)) {
       this->HTTPProxyAuth += ":";
-      this->HTTPProxyAuth += cmSystemTools::GetEnv("HTTP_PROXY_PASSWD");
+      this->HTTPProxyAuth += passwd;
     }
   }
 }
diff --git a/Source/CTest/cmCTestCurl.h b/Source/CTest/cmCTestCurl.h
index 82601e3..17fbcff 100644
--- a/Source/CTest/cmCTestCurl.h
+++ b/Source/CTest/cmCTestCurl.h
@@ -1,20 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestCurl_h
 #define cmCTestCurl_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cm_curl.h"
+#include <cm_curl.h>
+#include <string>
+#include <vector>
 
 class cmCTest;
 
diff --git a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.cxx b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.cxx
index 1bda9be..f4531a1 100644
--- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.cxx
+++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.cxx
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestEmptyBinaryDirectoryCommand.h"
 
 #include "cmCTestScriptHandler.h"
 
+#include <sstream>
+
+class cmExecutionStatus;
+
 bool cmCTestEmptyBinaryDirectoryCommand::InitialPass(
-  std::vector<std::string> const& args, cmExecutionStatus&)
+  std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
 {
   if (args.size() != 1) {
     this->SetError("called with incorrect number of arguments");
diff --git a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
index e904d19..8b5d5a4 100644
--- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
+++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestEmptyBinaryDirectoryCommand_h
 #define cmCTestEmptyBinaryDirectoryCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
+
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestEmptyBinaryDirectory
  * \brief Run a ctest script
@@ -28,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestEmptyBinaryDirectoryCommand* ni =
       new cmCTestEmptyBinaryDirectoryCommand;
@@ -41,13 +41,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return "ctest_empty_binary_directory";
   }
diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx
index 8b392f2..1bc1851 100644
--- a/Source/CTest/cmCTestGIT.cxx
+++ b/Source/CTest/cmCTestGIT.cxx
@@ -1,27 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestGIT.h"
 
 #include "cmAlgorithms.h"
 #include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 
 #include <cmsys/FStream.hxx>
 #include <cmsys/Process.h>
-#include <cmsys/RegularExpression.hxx>
-
 #include <ctype.h>
-#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
 #include <time.h>
+#include <vector>
 
 static unsigned int cmCTestGITVersion(unsigned int epic, unsigned int major,
                                       unsigned int minor, unsigned int fix)
@@ -52,7 +45,7 @@ public:
 
 private:
   std::string& Line1;
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     // Only the first line is of interest.
     this->Line1 = this->Line;
@@ -64,7 +57,8 @@ std::string cmCTestGIT::GetWorkingRevision()
 {
   // Run plumbing "git rev-list" to get work tree revision.
   const char* git = this->CommandLineTool.c_str();
-  const char* git_rev_list[] = { git, "rev-list", "-n", "1", "HEAD", "--", 0 };
+  const char* git_rev_list[] = { git,    "rev-list", "-n",      "1",
+                                 "HEAD", "--",       CM_NULLPTR };
   std::string rev;
   OneLineParser out(this, "rl-out> ", rev);
   OutputLogger err(this->Log, "rl-err> ");
@@ -93,7 +87,7 @@ std::string cmCTestGIT::FindGitDir()
 
   // Run "git rev-parse --git-dir" to locate the real .git directory.
   const char* git = this->CommandLineTool.c_str();
-  char const* git_rev_parse[] = { git, "rev-parse", "--git-dir", 0 };
+  char const* git_rev_parse[] = { git, "rev-parse", "--git-dir", CM_NULLPTR };
   std::string git_dir_line;
   OneLineParser rev_parse_out(this, "rev-parse-out> ", git_dir_line);
   OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
@@ -135,7 +129,8 @@ std::string cmCTestGIT::FindTopDir()
 
   // Run "git rev-parse --show-cdup" to locate the top of the tree.
   const char* git = this->CommandLineTool.c_str();
-  char const* git_rev_parse[] = { git, "rev-parse", "--show-cdup", 0 };
+  char const* git_rev_parse[] = { git, "rev-parse", "--show-cdup",
+                                  CM_NULLPTR };
   std::string cdup;
   OneLineParser rev_parse_out(this, "rev-parse-out> ", cdup);
   OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
@@ -169,7 +164,7 @@ bool cmCTestGIT::UpdateByFetchAndReset()
   }
 
   // Sentinel argument.
-  git_fetch.push_back(0);
+  git_fetch.push_back(CM_NULLPTR);
 
   // Fetch upstream refs.
   OutputLogger fetch_out(this->Log, "fetch-out> ");
@@ -204,7 +199,8 @@ bool cmCTestGIT::UpdateByFetchAndReset()
   }
 
   // Reset the local branch to point at that tracked from upstream.
-  char const* git_reset[] = { git, "reset", "--hard", sha1.c_str(), 0 };
+  char const* git_reset[] = { git, "reset", "--hard", sha1.c_str(),
+                              CM_NULLPTR };
   OutputLogger reset_out(this->Log, "reset-out> ");
   OutputLogger reset_err(this->Log, "reset-err> ");
   return this->RunChild(&git_reset[0], &reset_out, &reset_err);
@@ -219,7 +215,7 @@ bool cmCTestGIT::UpdateByCustom(std::string const& custom)
        i != git_custom_command.end(); ++i) {
     git_custom.push_back(i->c_str());
   }
-  git_custom.push_back(0);
+  git_custom.push_back(CM_NULLPTR);
 
   OutputLogger custom_out(this->Log, "custom-out> ");
   OutputLogger custom_err(this->Log, "custom-err> ");
@@ -248,7 +244,7 @@ bool cmCTestGIT::UpdateImpl()
 
   // Git < 1.6.5 did not support submodule --recursive
   if (this->GetGitVersion() < cmCTestGITVersion(1, 6, 5, 0)) {
-    recursive = 0;
+    recursive = CM_NULLPTR;
     // No need to require >= 1.6.5 if there are no submodules.
     if (cmSystemTools::FileExists((top_dir + "/.gitmodules").c_str())) {
       this->Log << "Git < 1.6.5 cannot update submodules recursively\n";
@@ -257,7 +253,7 @@ bool cmCTestGIT::UpdateImpl()
 
   // Git < 1.8.1 did not support sync --recursive
   if (this->GetGitVersion() < cmCTestGITVersion(1, 8, 1, 0)) {
-    sync_recursive = 0;
+    sync_recursive = CM_NULLPTR;
     // No need to require >= 1.8.1 if there are no submodules.
     if (cmSystemTools::FileExists((top_dir + "/.gitmodules").c_str())) {
       this->Log << "Git < 1.8.1 cannot synchronize submodules recursively\n";
@@ -272,7 +268,8 @@ bool cmCTestGIT::UpdateImpl()
   std::string init_submodules =
     this->CTest->GetCTestConfiguration("GITInitSubmodules");
   if (cmSystemTools::IsOn(init_submodules.c_str())) {
-    char const* git_submodule_init[] = { git, "submodule", "init", 0 };
+    char const* git_submodule_init[] = { git, "submodule", "init",
+                                         CM_NULLPTR };
     ret = this->RunChild(git_submodule_init, &submodule_out, &submodule_err,
                          top_dir.c_str());
 
@@ -282,7 +279,7 @@ bool cmCTestGIT::UpdateImpl()
   }
 
   char const* git_submodule_sync[] = { git, "submodule", "sync",
-                                       sync_recursive, 0 };
+                                       sync_recursive, CM_NULLPTR };
   ret = this->RunChild(git_submodule_sync, &submodule_out, &submodule_err,
                        top_dir.c_str());
 
@@ -290,7 +287,8 @@ bool cmCTestGIT::UpdateImpl()
     return false;
   }
 
-  char const* git_submodule[] = { git, "submodule", "update", recursive, 0 };
+  char const* git_submodule[] = { git, "submodule", "update", recursive,
+                                  CM_NULLPTR };
   return this->RunChild(git_submodule, &submodule_out, &submodule_err,
                         top_dir.c_str());
 }
@@ -299,7 +297,7 @@ unsigned int cmCTestGIT::GetGitVersion()
 {
   if (!this->CurrentGitVersion) {
     const char* git = this->CommandLineTool.c_str();
-    char const* git_version[] = { git, "--version", 0 };
+    char const* git_version[] = { git, "--version", CM_NULLPTR };
     std::string version;
     OneLineParser version_out(this, "version-out> ", version);
     OutputLogger version_err(this->Log, "version-err> ");
@@ -355,7 +353,7 @@ protected:
     this->Changes.clear();
   }
 
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->Line[0] == ':') {
       this->DiffField = DiffFieldChange;
@@ -513,7 +511,7 @@ private:
     person.TimeZone = strtol(c, (char**)&c, 10);
   }
 
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->Line.empty()) {
       if (this->Section == SectionBody && this->LineEnd == '\0') {
@@ -611,10 +609,10 @@ void cmCTestGIT::LoadRevisions()
   std::string range = this->OldRevision + ".." + this->NewRevision;
   const char* git = this->CommandLineTool.c_str();
   const char* git_rev_list[] = { git,           "rev-list", "--reverse",
-                                 range.c_str(), "--",       0 };
+                                 range.c_str(), "--",       CM_NULLPTR };
   const char* git_diff_tree[] = {
     git,  "diff-tree",    "--stdin",          "--always", "-z",
-    "-r", "--pretty=raw", "--encoding=utf-8", 0
+    "-r", "--pretty=raw", "--encoding=utf-8", CM_NULLPTR
   };
   this->Log << this->ComputeCommandLine(git_rev_list) << " | "
             << this->ComputeCommandLine(git_diff_tree) << "\n";
@@ -639,13 +637,15 @@ void cmCTestGIT::LoadModifications()
   const char* git = this->CommandLineTool.c_str();
 
   // Use 'git update-index' to refresh the index w.r.t. the work tree.
-  const char* git_update_index[] = { git, "update-index", "--refresh", 0 };
+  const char* git_update_index[] = { git, "update-index", "--refresh",
+                                     CM_NULLPTR };
   OutputLogger ui_out(this->Log, "ui-out> ");
   OutputLogger ui_err(this->Log, "ui-err> ");
   this->RunChild(git_update_index, &ui_out, &ui_err);
 
   // Use 'git diff-index' to get modified files.
-  const char* git_diff_index[] = { git, "diff-index", "-z", "HEAD", "--", 0 };
+  const char* git_diff_index[] = { git,    "diff-index", "-z",
+                                   "HEAD", "--",         CM_NULLPTR };
   DiffParser out(this, "di-out> ");
   OutputLogger err(this->Log, "di-err> ");
   this->RunChild(git_diff_index, &out, &err);
diff --git a/Source/CTest/cmCTestGIT.h b/Source/CTest/cmCTestGIT.h
index 685cc31..a655502 100644
--- a/Source/CTest/cmCTestGIT.h
+++ b/Source/CTest/cmCTestGIT.h
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestGIT_h
 #define cmCTestGIT_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGlobalVC.h"
 
+#include <iosfwd>
+#include <string>
+
+class cmCTest;
+
 /** \class cmCTestGIT
  * \brief Interaction with git command-line tool
  *
@@ -24,15 +22,15 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestGIT(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestGIT();
+  ~cmCTestGIT() CM_OVERRIDE;
 
 private:
   unsigned int CurrentGitVersion;
   unsigned int GetGitVersion();
   std::string GetWorkingRevision();
-  virtual void NoteOldRevision();
-  virtual void NoteNewRevision();
-  virtual bool UpdateImpl();
+  void NoteOldRevision() CM_OVERRIDE;
+  void NoteNewRevision() CM_OVERRIDE;
+  bool UpdateImpl() CM_OVERRIDE;
 
   std::string FindGitDir();
   std::string FindTopDir();
@@ -41,18 +39,19 @@ private:
   bool UpdateByCustom(std::string const& custom);
   bool UpdateInternal();
 
-  void LoadRevisions();
-  void LoadModifications();
+  void LoadRevisions() CM_OVERRIDE;
+  void LoadModifications() CM_OVERRIDE;
 
   // "public" needed by older Sun compilers
 public:
   // Parsing helper classes.
-  class OneLineParser;
-  class DiffParser;
   class CommitParser;
-  friend class OneLineParser;
-  friend class DiffParser;
+  class DiffParser;
+  class OneLineParser;
+
   friend class CommitParser;
+  friend class DiffParser;
+  friend class OneLineParser;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx
index 18caabe..c093cc6 100644
--- a/Source/CTest/cmCTestGenericHandler.cxx
+++ b/Source/CTest/cmCTestGenericHandler.cxx
@@ -1,25 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestGenericHandler.h"
 
+#include "cmCTest.h"
 #include "cmSystemTools.h"
 
-#include "cmCTest.h"
+#include <sstream>
+#include <utility>
 
 cmCTestGenericHandler::cmCTestGenericHandler()
 {
   this->HandlerVerbose = cmSystemTools::OUTPUT_NONE;
-  this->CTest = 0;
+  this->CTest = CM_NULLPTR;
   this->SubmitIndex = 0;
   this->AppendXML = false;
   this->Quiet = false;
@@ -77,7 +69,7 @@ const char* cmCTestGenericHandler::GetOption(const std::string& op)
   cmCTestGenericHandler::t_StringToString::iterator remit =
     this->Options.find(op);
   if (remit == this->Options.end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return remit->second.c_str();
 }
diff --git a/Source/CTest/cmCTestGenericHandler.h b/Source/CTest/cmCTestGenericHandler.h
index ad349ac..b2ab1d2 100644
--- a/Source/CTest/cmCTestGenericHandler.h
+++ b/Source/CTest/cmCTestGenericHandler.h
@@ -1,26 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestGenericHandler_h
 #define cmCTestGenericHandler_h
 
-#include "cmObject.h"
+#include <cmConfigure.h>
 
 #include "cmCTest.h"
-#include "cmSystemTools.h" //OutputOption
+#include "cmObject.h"
+#include "cmSystemTools.h"
+
+#include <map>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
-class cmMakefile;
 class cmCTestCommand;
 class cmGeneratedFileStream;
+class cmMakefile;
 
 /** \class cmCTestGenericHandler
  * \brief A superclass of all CTest Handlers
@@ -74,7 +70,7 @@ public:
    * Construct handler
    */
   cmCTestGenericHandler();
-  virtual ~cmCTestGenericHandler();
+  ~cmCTestGenericHandler() CM_OVERRIDE;
 
   typedef std::map<std::string, std::string> t_StringToString;
 
diff --git a/Source/CTest/cmCTestGlobalVC.cxx b/Source/CTest/cmCTestGlobalVC.cxx
index 0c7ca4d..08af179 100644
--- a/Source/CTest/cmCTestGlobalVC.cxx
+++ b/Source/CTest/cmCTestGlobalVC.cxx
@@ -1,21 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestGlobalVC.h"
 
 #include "cmCTest.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 
-#include <cmsys/RegularExpression.hxx>
+#include <ostream>
+#include <utility>
 
 cmCTestGlobalVC::cmCTestGlobalVC(cmCTest* ct, std::ostream& log)
   : cmCTestVC(ct, log)
diff --git a/Source/CTest/cmCTestGlobalVC.h b/Source/CTest/cmCTestGlobalVC.h
index 9a5357f..9a3757d 100644
--- a/Source/CTest/cmCTestGlobalVC.h
+++ b/Source/CTest/cmCTestGlobalVC.h
@@ -1,20 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestGlobalVC_h
 #define cmCTestGlobalVC_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestVC.h"
 
+#include <iosfwd>
 #include <list>
+#include <map>
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmXMLWriter;
 
 /** \class cmCTestGlobalVC
  * \brief Base class for handling globally-versioned trees
@@ -26,11 +26,11 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestGlobalVC(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestGlobalVC();
+  ~cmCTestGlobalVC() CM_OVERRIDE;
 
 protected:
   // Implement cmCTestVC internal API.
-  virtual bool WriteXMLUpdates(cmXMLWriter& xml);
+  bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE;
 
   /** Represent a vcs-reported action for one path in a revision.  */
   struct Change
diff --git a/Source/CTest/cmCTestHG.cxx b/Source/CTest/cmCTestHG.cxx
index c6cfa44..8443c93 100644
--- a/Source/CTest/cmCTestHG.cxx
+++ b/Source/CTest/cmCTestHG.cxx
@@ -1,21 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestHG.h"
 
 #include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 #include "cmXMLParser.h"
 
 #include <cmsys/RegularExpression.hxx>
+#include <ostream>
+#include <vector>
 
 cmCTestHG::cmCTestHG(cmCTest* ct, std::ostream& log)
   : cmCTestGlobalVC(ct, log)
@@ -41,7 +36,7 @@ private:
   std::string& Rev;
   cmsys::RegularExpression RegexIdentify;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexIdentify.find(this->Line)) {
       this->Rev = this->RegexIdentify.match(1);
@@ -65,7 +60,7 @@ private:
   cmCTestHG* HG;
   cmsys::RegularExpression RegexStatus;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexStatus.find(this->Line)) {
       this->DoPath(this->RegexStatus.match(1)[0], this->RegexStatus.match(2));
@@ -75,8 +70,9 @@ private:
 
   void DoPath(char status, std::string const& path)
   {
-    if (path.empty())
+    if (path.empty()) {
       return;
+    }
 
     // See "hg help status".  Note that there is no 'conflict' status.
     switch (status) {
@@ -100,7 +96,7 @@ std::string cmCTestHG::GetWorkingRevision()
 {
   // Run plumbing "hg identify" to get work tree revision.
   const char* hg = this->CommandLineTool.c_str();
-  const char* hg_identify[] = { hg, "identify", "-i", 0 };
+  const char* hg_identify[] = { hg, "identify", "-i", CM_NULLPTR };
   std::string rev;
   IdentifyParser out(this, "rev-out> ", rev);
   OutputLogger err(this->Log, "rev-err> ");
@@ -128,7 +124,7 @@ bool cmCTestHG::UpdateImpl()
   // Use "hg pull" followed by "hg update" to update the working tree.
   {
     const char* hg = this->CommandLineTool.c_str();
-    const char* hg_pull[] = { hg, "pull", "-v", 0 };
+    const char* hg_pull[] = { hg, "pull", "-v", CM_NULLPTR };
     OutputLogger out(this->Log, "pull-out> ");
     OutputLogger err(this->Log, "pull-err> ");
     this->RunChild(&hg_pull[0], &out, &err);
@@ -153,7 +149,7 @@ bool cmCTestHG::UpdateImpl()
   }
 
   // Sentinel argument.
-  hg_update.push_back(0);
+  hg_update.push_back(CM_NULLPTR);
 
   OutputLogger out(this->Log, "update-out> ");
   OutputLogger err(this->Log, "update-err> ");
@@ -170,7 +166,7 @@ public:
   {
     this->InitializeParser();
   }
-  ~LogParser() { this->CleanupParser(); }
+  ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
 private:
   cmCTestHG* HG;
 
@@ -181,14 +177,14 @@ private:
   Change CurChange;
   std::vector<char> CData;
 
-  virtual bool ProcessChunk(const char* data, int length)
+  bool ProcessChunk(const char* data, int length) CM_OVERRIDE
   {
     this->OutputLogger::ProcessChunk(data, length);
     this->ParseChunk(data, length);
     return true;
   }
 
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     this->CData.clear();
     if (name == "logentry") {
@@ -200,12 +196,12 @@ private:
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     this->CData.insert(this->CData.end(), data, data + length);
   }
 
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "logentry") {
       this->HG->DoRevision(this->Rev, this->Changes);
@@ -260,7 +256,7 @@ private:
     return output;
   }
 
-  virtual void ReportError(int, int, const char* msg)
+  void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
   {
     this->HG->Log << "Error parsing hg log xml: " << msg << "\n";
   }
@@ -287,7 +283,8 @@ void cmCTestHG::LoadRevisions()
                               "  <file_dels>{file_dels}</file_dels>\n"
                               "</logentry>\n";
   const char* hg_log[] = {
-    hg, "log", "--removed", "-r", range.c_str(), "--template", hgXMLTemplate, 0
+    hg,           "log",         "--removed", "-r", range.c_str(),
+    "--template", hgXMLTemplate, CM_NULLPTR
   };
 
   LogParser out(this, "log-out> ");
@@ -302,7 +299,7 @@ void cmCTestHG::LoadModifications()
 {
   // Use 'hg status' to get modified files.
   const char* hg = this->CommandLineTool.c_str();
-  const char* hg_status[] = { hg, "status", 0 };
+  const char* hg_status[] = { hg, "status", CM_NULLPTR };
   StatusParser out(this, "status-out> ");
   OutputLogger err(this->Log, "status-err> ");
   this->RunChild(hg_status, &out, &err);
diff --git a/Source/CTest/cmCTestHG.h b/Source/CTest/cmCTestHG.h
index 8cc8c7a..a81c347 100644
--- a/Source/CTest/cmCTestHG.h
+++ b/Source/CTest/cmCTestHG.h
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestHG_h
 #define cmCTestHG_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGlobalVC.h"
 
+#include <iosfwd>
+#include <string>
+
+class cmCTest;
+
 /** \class cmCTestHG
  * \brief Interaction with Mercurial command-line tool
  *
@@ -24,24 +22,25 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestHG(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestHG();
+  ~cmCTestHG() CM_OVERRIDE;
 
 private:
   std::string GetWorkingRevision();
-  virtual void NoteOldRevision();
-  virtual void NoteNewRevision();
-  virtual bool UpdateImpl();
+  void NoteOldRevision() CM_OVERRIDE;
+  void NoteNewRevision() CM_OVERRIDE;
+  bool UpdateImpl() CM_OVERRIDE;
 
-  void LoadRevisions();
-  void LoadModifications();
+  void LoadRevisions() CM_OVERRIDE;
+  void LoadModifications() CM_OVERRIDE;
 
   // Parsing helper classes.
   class IdentifyParser;
-  class StatusParser;
   class LogParser;
+  class StatusParser;
+
   friend class IdentifyParser;
-  friend class StatusParser;
   friend class LogParser;
+  friend class StatusParser;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx
index 76f971d..2e5b56a 100644
--- a/Source/CTest/cmCTestHandlerCommand.cxx
+++ b/Source/CTest/cmCTestHandlerCommand.cxx
@@ -1,18 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestHandlerCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <sstream>
+#include <stdlib.h>
+
+class cmExecutionStatus;
 
 cmCTestHandlerCommand::cmCTestHandlerCommand()
 {
@@ -20,9 +19,10 @@ cmCTestHandlerCommand::cmCTestHandlerCommand()
   size_t cc;
   this->Arguments.reserve(INIT_SIZE);
   for (cc = 0; cc < INIT_SIZE; ++cc) {
-    this->Arguments.push_back(0);
+    this->Arguments.push_back(CM_NULLPTR);
   }
   this->Arguments[ct_RETURN_VALUE] = "RETURN_VALUE";
+  this->Arguments[ct_CAPTURE_CMAKE_ERROR] = "CAPTURE_CMAKE_ERROR";
   this->Arguments[ct_SOURCE] = "SOURCE";
   this->Arguments[ct_BUILD] = "BUILD";
   this->Arguments[ct_SUBMIT_INDEX] = "SUBMIT_INDEX";
@@ -31,15 +31,71 @@ cmCTestHandlerCommand::cmCTestHandlerCommand()
   this->Quiet = false;
 }
 
+namespace {
+// class to save and restore the error state for ctest_* commands
+// if a ctest_* command has a CAPTURE_CMAKE_ERROR then put the error
+// state into there and restore the system wide error to what
+// it was before the command ran
+class SaveRestoreErrorState
+{
+public:
+  SaveRestoreErrorState()
+  {
+    this->InitialErrorState = cmSystemTools::GetErrorOccuredFlag();
+    cmSystemTools::ResetErrorOccuredFlag(); // rest the error state
+    this->CaptureCMakeErrorValue = false;
+  }
+  // if the function has a CAPTURE_CMAKE_ERROR then we should restore
+  // the error state to what it was before the function was run
+  // if not then let the error state be what it is
+  void CaptureCMakeError() { this->CaptureCMakeErrorValue = true; }
+  ~SaveRestoreErrorState()
+  {
+    // if we are not saving the return value then make sure
+    // if it was in error it goes back to being in error
+    // otherwise leave it be what it is
+    if (!this->CaptureCMakeErrorValue) {
+      if (this->InitialErrorState) {
+        cmSystemTools::SetErrorOccured();
+      }
+      return;
+    }
+    // if we have saved the error in a return variable
+    // then put things back exactly like they were
+    bool currentState = cmSystemTools::GetErrorOccuredFlag();
+    // if the state changed during this command we need
+    // to handle it, if not then nothing needs to be done
+    if (currentState != this->InitialErrorState) {
+      // restore the initial error state
+      if (this->InitialErrorState) {
+        cmSystemTools::SetErrorOccured();
+      } else {
+        cmSystemTools::ResetErrorOccuredFlag();
+      }
+    }
+  }
+
+private:
+  bool InitialErrorState;
+  bool CaptureCMakeErrorValue;
+};
+}
+
 bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
-                                        cmExecutionStatus&)
+                                        cmExecutionStatus& /*unused*/)
 {
+  // save error state and restore it if needed
+  SaveRestoreErrorState errorState;
   // Allocate space for argument values.
   this->Values.clear();
-  this->Values.resize(this->Last, 0);
+  this->Values.resize(this->Last, CM_NULLPTR);
 
   // Process input arguments.
   this->ArgumentDoing = ArgumentDoingNone;
+  // look at all arguments and do not short circuit on the first
+  // bad one so that CAPTURE_CMAKE_ERROR can override setting the
+  // global error state
+  bool foundBadArgument = false;
   for (unsigned int i = 0; i < args.size(); ++i) {
     // Check this argument.
     if (!this->CheckArgumentKeyword(args[i]) &&
@@ -47,14 +103,36 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
       std::ostringstream e;
       e << "called with unknown argument \"" << args[i] << "\".";
       this->SetError(e.str());
-      return false;
+      foundBadArgument = true;
     }
-
-    // Quit if an argument is invalid.
+    // note bad argument
     if (this->ArgumentDoing == ArgumentDoingError) {
-      return false;
+      foundBadArgument = true;
     }
   }
+  bool capureCMakeError = (this->Values[ct_CAPTURE_CMAKE_ERROR] &&
+                           *this->Values[ct_CAPTURE_CMAKE_ERROR]);
+  // now that arguments are parsed check to see if there is a
+  // CAPTURE_CMAKE_ERROR specified let the errorState object know.
+  if (capureCMakeError) {
+    errorState.CaptureCMakeError();
+  }
+  // if we found a bad argument then exit before running command
+  if (foundBadArgument) {
+    // store the cmake error
+    if (capureCMakeError) {
+      this->Makefile->AddDefinition(this->Values[ct_CAPTURE_CMAKE_ERROR],
+                                    "-1");
+      const char* err = this->GetError();
+      if (err && !cmSystemTools::FindLastString(err, "unknown error.")) {
+        cmCTestLog(this->CTest, ERROR_MESSAGE, err << " error from command\n");
+      }
+      // return success because failure is recorded in CAPTURE_CMAKE_ERROR
+      return true;
+    }
+    // return failure because of bad argument
+    return false;
+  }
 
   // Set the config type of this ctest to the current value of the
   // CTEST_CONFIGURATION_TYPE script variable if it is defined.
@@ -109,6 +187,15 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
   if (!handler) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot instantiate test handler "
                  << this->GetName() << std::endl);
+    if (capureCMakeError) {
+      this->Makefile->AddDefinition(this->Values[ct_CAPTURE_CMAKE_ERROR],
+                                    "-1");
+      const char* err = this->GetError();
+      if (err && !cmSystemTools::FindLastString(err, "unknown error.")) {
+        cmCTestLog(this->CTest, ERROR_MESSAGE, err << " error from command\n");
+      }
+      return true;
+    }
     return false;
   }
 
@@ -139,6 +226,22 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
     this->Makefile->AddDefinition(this->Values[ct_RETURN_VALUE],
                                   str.str().c_str());
   }
+  // log the error message if there was an error
+  if (capureCMakeError) {
+    const char* returnString = "0";
+    if (cmSystemTools::GetErrorOccuredFlag()) {
+      returnString = "-1";
+      const char* err = this->GetError();
+      // print out the error if it is not "unknown error" which means
+      // there was no message
+      if (err && !cmSystemTools::FindLastString(err, "unknown error.")) {
+        cmCTestLog(this->CTest, ERROR_MESSAGE, err);
+      }
+    }
+    // store the captured cmake error state 0 or -1
+    this->Makefile->AddDefinition(this->Values[ct_CAPTURE_CMAKE_ERROR],
+                                  returnString);
+  }
   cmSystemTools::ChangeDirectory(current_dir);
   return true;
 }
diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h
index 7248832..3fd384f 100644
--- a/Source/CTest/cmCTestHandlerCommand.h
+++ b/Source/CTest/cmCTestHandlerCommand.h
@@ -1,20 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestHandlerCommand_h
 #define cmCTestHandlerCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmCTestGenericHandler;
+class cmExecutionStatus;
 
 /** \class cmCTestHandler
  * \brief Run a ctest script
@@ -30,8 +29,8 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   cmTypeMacro(cmCTestHandlerCommand, cmCTestCommand);
 
@@ -39,6 +38,7 @@ public:
   {
     ct_NONE,
     ct_RETURN_VALUE,
+    ct_CAPTURE_CMAKE_ERROR,
     ct_BUILD,
     ct_SOURCE,
     ct_SUBMIT_INDEX,
diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx
index 4a408a2..e5c50b2 100644
--- a/Source/CTest/cmCTestLaunch.cxx
+++ b/Source/CTest/cmCTestLaunch.cxx
@@ -1,25 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestLaunch.h"
 
+#include <cmConfigure.h>
+
 #include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
+#include <cm_auto_ptr.hxx>
 #include <cmsys/FStream.hxx>
 #include <cmsys/MD5.h>
 #include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
+#include <iostream>
+#include <stdlib.h>
+#include <string.h>
 
 #ifdef _WIN32
 #include <fcntl.h> // for _O_BINARY
@@ -30,7 +30,7 @@
 cmCTestLaunch::cmCTestLaunch(int argc, const char* const* argv)
 {
   this->Passthru = true;
-  this->Process = 0;
+  this->Process = CM_NULLPTR;
   this->ExitCode = 1;
   this->CWD = cmSystemTools::GetCurrentWorkingDirectory();
 
@@ -126,12 +126,11 @@ bool cmCTestLaunch::ParseArguments(int argc, const char* const* argv)
       this->HandleRealArg(this->RealArgV[i]);
     }
     return true;
-  } else {
-    this->RealArgC = 0;
-    this->RealArgV = 0;
-    std::cerr << "No launch/command separator ('--') found!\n";
-    return false;
   }
+  this->RealArgC = 0;
+  this->RealArgV = CM_NULLPTR;
+  std::cerr << "No launch/command separator ('--') found!\n";
+  return false;
 }
 
 void cmCTestLaunch::HandleRealArg(const char* arg)
@@ -227,9 +226,9 @@ void cmCTestLaunch::RunChild()
 
   // Record child stdout and stderr if necessary.
   if (!this->Passthru) {
-    char* data = 0;
+    char* data = CM_NULLPTR;
     int length = 0;
-    while (int p = cmsysProcess_WaitForData(cp, &data, &length, 0)) {
+    while (int p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
       if (p == cmsysProcess_Pipe_STDOUT) {
         fout.write(data, length);
         std::cout.write(data, length);
@@ -243,7 +242,7 @@ void cmCTestLaunch::RunChild()
   }
 
   // Wait for the real command to finish.
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   this->ExitCode = cmsysProcess_GetExitValue(cp);
 }
 
@@ -384,7 +383,7 @@ void cmCTestLaunch::WriteXMLAction(cmXMLWriter& xml)
   }
 
   // OutputType
-  const char* outputType = 0;
+  const char* outputType = CM_NULLPTR;
   if (!this->OptionTargetType.empty()) {
     if (this->OptionTargetType == "EXECUTABLE") {
       outputType = "executable";
@@ -594,12 +593,8 @@ bool cmCTestLaunch::Match(std::string const& line,
 
 bool cmCTestLaunch::MatchesFilterPrefix(std::string const& line) const
 {
-  if (!this->OptionFilterPrefix.empty() &&
-      cmSystemTools::StringStartsWith(line.c_str(),
-                                      this->OptionFilterPrefix.c_str())) {
-    return true;
-  }
-  return false;
+  return !this->OptionFilterPrefix.empty() &&
+    cmSystemTools::StringStartsWith(line, this->OptionFilterPrefix.c_str());
 }
 
 int cmCTestLaunch::Main(int argc, const char* const argv[])
@@ -613,10 +608,6 @@ int cmCTestLaunch::Main(int argc, const char* const argv[])
   return self.Run();
 }
 
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmake.h"
-#include <cmsys/auto_ptr.hxx>
 void cmCTestLaunch::LoadConfig()
 {
   cmake cm;
@@ -624,7 +615,7 @@ void cmCTestLaunch::LoadConfig()
   cm.SetHomeOutputDirectory("");
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator gg(&cm);
-  cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
   std::string fname = this->LogDir;
   fname += "CTestLaunchConfig.cmake";
   if (cmSystemTools::FileExists(fname.c_str()) &&
diff --git a/Source/CTest/cmCTestLaunch.h b/Source/CTest/cmCTestLaunch.h
index cbcc9ec..fbc9e2b 100644
--- a/Source/CTest/cmCTestLaunch.h
+++ b/Source/CTest/cmCTestLaunch.h
@@ -1,20 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestLaunch_h
 #define cmCTestLaunch_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/RegularExpression.hxx>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmXMLWriter;
 
diff --git a/Source/CTest/cmCTestMemCheckCommand.cxx b/Source/CTest/cmCTestMemCheckCommand.cxx
index d53dcd0..05d0a53 100644
--- a/Source/CTest/cmCTestMemCheckCommand.cxx
+++ b/Source/CTest/cmCTestMemCheckCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestMemCheckCommand.h"
 
 #include "cmCTest.h"
diff --git a/Source/CTest/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h
index 245892c..d3b8be7 100644
--- a/Source/CTest/cmCTestMemCheckCommand.h
+++ b/Source/CTest/cmCTestMemCheckCommand.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestMemCheckCommand_h
 #define cmCTestMemCheckCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
 
 class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestMemCheck
  * \brief Run a ctest script
@@ -29,7 +26,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestMemCheckCommand* ni = new cmCTestMemCheckCommand;
     ni->CTest = this->CTest;
@@ -40,12 +37,12 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_memcheck"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_memcheck"; }
 
   cmTypeMacro(cmCTestMemCheckCommand, cmCTestTestCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeActualHandler();
+  cmCTestGenericHandler* InitializeActualHandler() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx
index 5ae98af..b37db30 100644
--- a/Source/CTest/cmCTestMemCheckHandler.cxx
+++ b/Source/CTest/cmCTestMemCheckHandler.cxx
@@ -1,32 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestMemCheckHandler.h"
 
 #include "cmCTest.h"
-#include "cmGeneratedFileStream.h"
-#include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmXMLParser.h"
 #include "cmXMLWriter.h"
-#include "cmake.h"
-#include <cmsys/Base64.h>
+
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-#include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
-
-#include <float.h>
-#include <math.h>
-#include <stdlib.h>
+#include <iostream>
+#include <sstream>
+#include <string.h>
 
 struct CatToErrorType
 {
@@ -42,7 +28,7 @@ static CatToErrorType cmCTestMemCheckBoundsChecker[] = {
   { "Allocation Conflict", cmCTestMemCheckHandler::FMM },
   { "Bad Pointer Use", cmCTestMemCheckHandler::FMW },
   { "Dangling Pointer", cmCTestMemCheckHandler::FMR },
-  { 0, 0 }
+  { CM_NULLPTR, 0 }
 };
 
 static void xmlReportError(int line, const char* msg, void* data)
@@ -61,7 +47,7 @@ public:
     this->CTest = c;
     this->SetErrorCallback(xmlReportError, (void*)c);
   }
-  void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     if (name == "MemoryLeak" || name == "ResourceLeak") {
       this->Errors.push_back(cmCTestMemCheckHandler::MLK);
@@ -72,23 +58,23 @@ public:
     std::ostringstream ostr;
     ostr << name << ":\n";
     int i = 0;
-    for (; atts[i] != 0; i += 2) {
+    for (; atts[i] != CM_NULLPTR; i += 2) {
       ostr << "   " << atts[i] << " - " << atts[i + 1] << "\n";
     }
     ostr << "\n";
     this->Log += ostr.str();
   }
-  void EndElement(const std::string&) {}
+  void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
 
   const char* GetAttribute(const char* name, const char** atts)
   {
     int i = 0;
-    for (; atts[i] != 0; ++i) {
+    for (; atts[i] != CM_NULLPTR; ++i) {
       if (strcmp(name, atts[i]) == 0) {
         return atts[i + 1];
       }
     }
-    return 0;
+    return CM_NULLPTR;
   }
   void ParseError(const char** atts)
   {
@@ -241,9 +227,9 @@ void cmCTestMemCheckHandler::InitializeResultsVectors()
   // define the standard set of errors
   //----------------------------------------------------------------------
   static const char* cmCTestMemCheckResultStrings[] = {
-    "ABR", "ABW", "ABWL", "COR", "EXU", "FFM", "FIM", "FMM",
-    "FMR", "FMW", "FUM",  "IPR", "IPW", "MAF", "MLK", "MPK",
-    "NPR", "ODS", "PAR",  "PLK", "UMC", "UMR", 0
+    "ABR", "ABW", "ABWL", "COR", "EXU", "FFM", "FIM",     "FMM",
+    "FMR", "FMW", "FUM",  "IPR", "IPW", "MAF", "MLK",     "MPK",
+    "NPR", "ODS", "PAR",  "PLK", "UMC", "UMR", CM_NULLPTR
   };
   static const char* cmCTestMemCheckResultLongStrings[] = {
     "Threading Problem",
@@ -268,10 +254,10 @@ void cmCTestMemCheckHandler::InitializeResultsVectors()
     "PLK",
     "Uninitialized Memory Conditional",
     "Uninitialized Memory Read",
-    0
+    CM_NULLPTR
   };
   this->GlobalResults.clear();
-  for (int i = 0; cmCTestMemCheckResultStrings[i] != 0; ++i) {
+  for (int i = 0; cmCTestMemCheckResultStrings[i] != CM_NULLPTR; ++i) {
     this->ResultStrings.push_back(cmCTestMemCheckResultStrings[i]);
     this->ResultStringsLong.push_back(cmCTestMemCheckResultLongStrings[i]);
     this->GlobalResults.push_back(0);
@@ -499,11 +485,12 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
 
   // Setup the options
   std::string memoryTesterOptions;
-  if (this->CTest->GetCTestConfiguration("MemoryCheckCommandOptions").size()) {
+  if (!this->CTest->GetCTestConfiguration("MemoryCheckCommandOptions")
+         .empty()) {
     memoryTesterOptions =
       this->CTest->GetCTestConfiguration("MemoryCheckCommandOptions");
-  } else if (this->CTest->GetCTestConfiguration("ValgrindCommandOptions")
-               .size()) {
+  } else if (!this->CTest->GetCTestConfiguration("ValgrindCommandOptions")
+                .empty()) {
     memoryTesterOptions =
       this->CTest->GetCTestConfiguration("ValgrindCommandOptions");
   }
@@ -522,8 +509,8 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
         this->MemoryTesterOptions.push_back("--show-reachable=yes");
         this->MemoryTesterOptions.push_back("--num-callers=50");
       }
-      if (this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
-            .size()) {
+      if (!this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
+             .empty()) {
         if (!cmSystemTools::FileExists(
               this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
                 .c_str())) {
@@ -637,27 +624,24 @@ bool cmCTestMemCheckHandler::ProcessMemCheckOutput(const std::string& str,
                                                    std::string& log,
                                                    std::vector<int>& results)
 {
-  if (this->MemoryTesterStyle == cmCTestMemCheckHandler::VALGRIND) {
-    return this->ProcessMemCheckValgrindOutput(str, log, results);
-  } else if (this->MemoryTesterStyle == cmCTestMemCheckHandler::PURIFY) {
-    return this->ProcessMemCheckPurifyOutput(str, log, results);
-  } else if (this->MemoryTesterStyle ==
-               cmCTestMemCheckHandler::ADDRESS_SANITIZER ||
-             this->MemoryTesterStyle ==
-               cmCTestMemCheckHandler::THREAD_SANITIZER ||
-             this->MemoryTesterStyle ==
-               cmCTestMemCheckHandler::MEMORY_SANITIZER ||
-             this->MemoryTesterStyle == cmCTestMemCheckHandler::UB_SANITIZER) {
-    return this->ProcessMemCheckSanitizerOutput(str, log, results);
-  } else if (this->MemoryTesterStyle ==
-             cmCTestMemCheckHandler::BOUNDS_CHECKER) {
-    return this->ProcessMemCheckBoundsCheckerOutput(str, log, results);
-  } else {
-    log.append("\nMemory checking style used was: ");
-    log.append("None that I know");
-    log = str;
+  switch (this->MemoryTesterStyle) {
+    case cmCTestMemCheckHandler::VALGRIND:
+      return this->ProcessMemCheckValgrindOutput(str, log, results);
+    case cmCTestMemCheckHandler::PURIFY:
+      return this->ProcessMemCheckPurifyOutput(str, log, results);
+    case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+    case cmCTestMemCheckHandler::THREAD_SANITIZER:
+    case cmCTestMemCheckHandler::MEMORY_SANITIZER:
+    case cmCTestMemCheckHandler::UB_SANITIZER:
+      return this->ProcessMemCheckSanitizerOutput(str, log, results);
+    case cmCTestMemCheckHandler::BOUNDS_CHECKER:
+      return this->ProcessMemCheckBoundsCheckerOutput(str, log, results);
+    default:
+      log.append("\nMemory checking style used was: ");
+      log.append("None that I know");
+      log = str;
+      return true;
   }
-  return true;
 }
 
 std::vector<int>::size_type cmCTestMemCheckHandler::FindOrAddWarning(
@@ -722,10 +706,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
     ostr << *i << std::endl;
   }
   log = ostr.str();
-  if (defects) {
-    return false;
-  }
-  return true;
+  return defects == 0;
 }
 bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
   const std::string& str, std::string& log, std::vector<int>& results)
@@ -766,10 +747,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
   }
 
   log = ostr.str();
-  if (defects) {
-    return false;
-  }
-  return true;
+  return defects == 0;
 }
 
 bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
@@ -904,10 +882,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
                        << (cmSystemTools::GetTime() - sttime) << std::endl,
                      this->Quiet);
   log = ostr.str();
-  if (defects) {
-    return false;
-  }
-  return true;
+  return defects == 0;
 }
 
 bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
@@ -999,7 +974,7 @@ void cmCTestMemCheckHandler::PostProcessBoundsCheckerTest(
     cmsys::ifstream ifs(ofile.c_str());
     if (!ifs) {
       std::string log = "Cannot read memory tester output file: " + ofile;
-      cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
+      cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
       return;
     }
     res.Output += BOUNDS_CHECKER_MARKER;
@@ -1032,7 +1007,7 @@ void cmCTestMemCheckHandler::AppendMemTesterOutput(cmCTestTestResult& res,
     cmsys::ifstream ifs(ofile.c_str());
     if (!ifs) {
       std::string log = "Cannot read memory tester output file: " + ofile;
-      cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
+      cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
       return;
     }
     std::string line;
@@ -1064,7 +1039,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames(
     g.FindFiles(ofile);
     if (g.GetFiles().empty()) {
       std::string log = "Cannot find memory tester output file: " + ofile;
-      cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
+      cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
       ofile = "";
     } else {
       files = g.GetFiles();
@@ -1072,7 +1047,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames(
     }
   } else if (!cmSystemTools::FileExists(ofile.c_str())) {
     std::string log = "Cannot find memory tester output file: " + ofile;
-    cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
+    cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
     ofile = "";
   }
   files.push_back(ofile);
diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h
index 8f0cc47..8d678af 100644
--- a/Source/CTest/cmCTestMemCheckHandler.h
+++ b/Source/CTest/cmCTestMemCheckHandler.h
@@ -1,21 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestMemCheckHandler_h
 #define cmCTestMemCheckHandler_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestTestHandler.h"
+#include "cmTypeMacro.h"
 
-#include "cmListFileCache.h"
 #include <string>
 #include <vector>
 
@@ -33,16 +25,17 @@ class cmCTestMemCheckHandler : public cmCTestTestHandler
 public:
   cmTypeMacro(cmCTestMemCheckHandler, cmCTestTestHandler);
 
-  void PopulateCustomVectors(cmMakefile* mf);
+  void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
 
   cmCTestMemCheckHandler();
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 
 protected:
-  virtual int PreProcessHandler();
-  virtual int PostProcessHandler();
-  virtual void GenerateTestCommand(std::vector<std::string>& args, int test);
+  int PreProcessHandler() CM_OVERRIDE;
+  int PostProcessHandler() CM_OVERRIDE;
+  void GenerateTestCommand(std::vector<std::string>& args,
+                           int test) CM_OVERRIDE;
 
 private:
   enum
@@ -125,7 +118,7 @@ private:
   /**
    * Generate the Dart compatible output
    */
-  void GenerateDartOutput(cmXMLWriter& xml);
+  void GenerateDartOutput(cmXMLWriter& xml) CM_OVERRIDE;
 
   std::vector<std::string> CustomPreMemCheck;
   std::vector<std::string> CustomPostMemCheck;
diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx
index 6f19b32..1766aef 100644
--- a/Source/CTest/cmCTestMultiProcessHandler.cxx
+++ b/Source/CTest/cmCTestMultiProcessHandler.cxx
@@ -1,28 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestMultiProcessHandler.h"
 
 #include "cmCTest.h"
+#include "cmCTestRunTest.h"
 #include "cmCTestScriptHandler.h"
-#include "cmProcess.h"
-#include "cmStandardIncludes.h"
+#include "cmCTestTestHandler.h"
 #include "cmSystemTools.h"
+
+#include <algorithm>
 #include <cmsys/FStream.hxx>
+#include <cmsys/String.hxx>
 #include <cmsys/SystemInformation.hxx>
-#include <float.h>
+#include <iomanip>
 #include <list>
 #include <math.h>
+#include <sstream>
 #include <stack>
 #include <stdlib.h>
+#include <utility>
 
 class TestComparator
 {
@@ -132,6 +128,16 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test)
   testRun->SetIndex(test);
   testRun->SetTestProperties(this->Properties[test]);
 
+  // Find any failed dependencies for this test. We assume the more common
+  // scenario has no failed tests, so make it the outer loop.
+  for (std::vector<std::string>::const_iterator it = this->Failed->begin();
+       it != this->Failed->end(); ++it) {
+    if (this->Properties[test]->RequireSuccessDepends.find(*it) !=
+        this->Properties[test]->RequireSuccessDepends.end()) {
+      testRun->AddFailedDependency(*it);
+    }
+  }
+
   std::string current_dir = cmSystemTools::GetCurrentWorkingDirectory();
   cmSystemTools::ChangeDirectory(this->Properties[test]->Directory);
 
@@ -261,12 +267,14 @@ void cmCTestMultiProcessHandler::StartNextTests()
     allTestsFailedTestLoadCheck = true;
 
     // Check for a fake load average value used in testing.
-    if (const char* fake_load_value =
-          cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING")) {
+    std::string fake_load_value;
+    if (cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING",
+                              fake_load_value)) {
       usedFakeLoadForTesting = true;
-      if (!cmSystemTools::StringToULong(fake_load_value, &systemLoad)) {
+      if (!cmSystemTools::StringToULong(fake_load_value.c_str(),
+                                        &systemLoad)) {
         cmSystemTools::Error("Failed to parse fake load value: ",
-                             fake_load_value);
+                             fake_load_value.c_str());
       }
     }
     // If it's not set, look up the true load average.
@@ -413,12 +421,14 @@ void cmCTestMultiProcessHandler::UpdateCostData()
 
     std::string line;
     while (std::getline(fin, line)) {
-      if (line == "---")
+      if (line == "---") {
         break;
+      }
       std::vector<cmsys::String> parts = cmSystemTools::SplitString(line, ' ');
       // Format: <name> <previous_runs> <avg_cost>
-      if (parts.size() < 3)
+      if (parts.size() < 3) {
         break;
+      }
 
       std::string name = parts[0];
       int prev = atoi(parts[1].c_str());
@@ -449,7 +459,7 @@ void cmCTestMultiProcessHandler::UpdateCostData()
   fout << "---\n";
   for (std::vector<std::string>::iterator i = this->Failed->begin();
        i != this->Failed->end(); ++i) {
-    fout << i->c_str() << "\n";
+    fout << *i << "\n";
   }
   fout.close();
   cmSystemTools::RenameFile(tmpout.c_str(), fname.c_str());
@@ -464,8 +474,9 @@ void cmCTestMultiProcessHandler::ReadCostData()
     fin.open(fname.c_str());
     std::string line;
     while (std::getline(fin, line)) {
-      if (line == "---")
+      if (line == "---") {
         break;
+      }
 
       std::vector<cmsys::String> parts = cmSystemTools::SplitString(line, ' ');
 
@@ -480,8 +491,9 @@ void cmCTestMultiProcessHandler::ReadCostData()
       float cost = static_cast<float>(atof(parts[2].c_str()));
 
       int index = this->SearchByName(name);
-      if (index == -1)
+      if (index == -1) {
         continue;
+      }
 
       this->Properties[index]->PreviousRuns = prev;
       // When not running in parallel mode, don't use cost data
@@ -710,8 +722,8 @@ void cmCTestMultiProcessHandler::PrintTestList()
         << indexStr.str(),
       this->Quiet);
     cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
-    cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
-                       p.Name.c_str() << std::endl, this->Quiet);
+    cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, p.Name << std::endl,
+                       this->Quiet);
     // pop working dir
     cmSystemTools::ChangeDirectory(current_dir);
   }
@@ -818,9 +830,8 @@ bool cmCTestMultiProcessHandler::CheckCycles()
                 << this->Properties[root]->Name
                 << "\".\nPlease fix the cycle and run ctest again.\n");
             return false;
-          } else {
-            s.push(*d);
           }
+          s.push(*d);
         }
       }
     }
diff --git a/Source/CTest/cmCTestMultiProcessHandler.h b/Source/CTest/cmCTestMultiProcessHandler.h
index 9ec1528..fe32e15 100644
--- a/Source/CTest/cmCTestMultiProcessHandler.h
+++ b/Source/CTest/cmCTestMultiProcessHandler.h
@@ -1,20 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestMultiProcessHandler_h
 #define cmCTestMultiProcessHandler_h
 
-#include <cmCTestTestHandler.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include <cmCTestRunTest.h>
+#include <cmCTestTestHandler.h>
+#include <map>
+#include <set>
+#include <stddef.h>
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestRunTest;
 
 /** \class cmCTestMultiProcessHandler
  * \brief run parallel ctest
diff --git a/Source/CTest/cmCTestP4.cxx b/Source/CTest/cmCTestP4.cxx
index 07f9dad..41b45a8 100644
--- a/Source/CTest/cmCTestP4.cxx
+++ b/Source/CTest/cmCTestP4.cxx
@@ -1,25 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestP4.h"
 
 #include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 
-#include <cmsys/Process.h>
+#include <algorithm>
 #include <cmsys/RegularExpression.hxx>
-
-#include <ctype.h>
-#include <sys/types.h>
+#include <ostream>
 #include <time.h>
+#include <utility>
 
 cmCTestP4::cmCTestP4(cmCTest* ct, std::ostream& log)
   : cmCTestGlobalVC(ct, log)
@@ -45,7 +37,7 @@ private:
   std::string& Rev;
   cmsys::RegularExpression RegexIdentify;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexIdentify.find(this->Line)) {
       this->Rev = this->RegexIdentify.match(1);
@@ -69,7 +61,7 @@ private:
   cmsys::RegularExpression RegexIdentify;
   cmCTestP4* P4;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexIdentify.find(this->Line)) {
       P4->ChangeLists.push_back(this->RegexIdentify.match(1));
@@ -92,7 +84,7 @@ private:
   cmsys::RegularExpression RegexUser;
   cmCTestP4* P4;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexUser.find(this->Line)) {
       User NewUser;
@@ -135,7 +127,7 @@ private:
   std::string CurrentPath;
   cmsys::RegularExpression RegexDiff;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (!this->Line.empty() && this->Line[0] == '=' &&
         this->RegexDiff.find(this->Line)) {
@@ -163,7 +155,7 @@ cmCTestP4::User cmCTestP4::GetUserData(const std::string& username)
     p4_users.push_back("-m");
     p4_users.push_back("1");
     p4_users.push_back(username.c_str());
-    p4_users.push_back(0);
+    p4_users.push_back(CM_NULLPTR);
 
     UserParser out(this, "users-out> ");
     OutputLogger err(this->Log, "users-err> ");
@@ -225,7 +217,7 @@ private:
   SectionType Section;
   Revision Rev;
 
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->Line.empty()) {
       this->NextSection();
@@ -358,7 +350,7 @@ std::string cmCTestP4::GetWorkingRevision()
 
   std::string source = this->SourceDirectory + "/...#have";
   p4_identify.push_back(source.c_str());
-  p4_identify.push_back(0);
+  p4_identify.push_back(CM_NULLPTR);
 
   std::string rev;
   IdentifyParser out(this, "p4_changes-out> ", rev);
@@ -373,9 +365,8 @@ std::string cmCTestP4::GetWorkingRevision()
 
   if (rev.empty()) {
     return "0";
-  } else {
-    return rev;
   }
+  return rev;
 }
 
 void cmCTestP4::NoteOldRevision()
@@ -418,7 +409,7 @@ void cmCTestP4::LoadRevisions()
 
   p4_changes.push_back("changes");
   p4_changes.push_back(range.c_str());
-  p4_changes.push_back(0);
+  p4_changes.push_back(CM_NULLPTR);
 
   ChangesParser out(this, "p4_changes-out> ");
   OutputLogger err(this->Log, "p4_changes-err> ");
@@ -426,8 +417,9 @@ void cmCTestP4::LoadRevisions()
   ChangeLists.clear();
   this->RunChild(&p4_changes[0], &out, &err);
 
-  if (ChangeLists.empty())
+  if (ChangeLists.empty()) {
     return;
+  }
 
   // p4 describe -s ... at 1111111,2222222
   std::vector<char const*> p4_describe;
@@ -437,7 +429,7 @@ void cmCTestP4::LoadRevisions()
     p4_describe.push_back("describe");
     p4_describe.push_back("-s");
     p4_describe.push_back(i->c_str());
-    p4_describe.push_back(0);
+    p4_describe.push_back(CM_NULLPTR);
 
     DescribeParser outDescribe(this, "p4_describe-out> ");
     OutputLogger errDescribe(this->Log, "p4_describe-err> ");
@@ -456,7 +448,7 @@ void cmCTestP4::LoadModifications()
   p4_diff.push_back("-dn");
   std::string source = this->SourceDirectory + "/...";
   p4_diff.push_back(source.c_str());
-  p4_diff.push_back(0);
+  p4_diff.push_back(CM_NULLPTR);
 
   DiffParser out(this, "p4_diff-out> ");
   OutputLogger err(this->Log, "p4_diff-err> ");
@@ -473,7 +465,7 @@ bool cmCTestP4::UpdateCustom(const std::string& custom)
        i != p4_custom_command.end(); ++i) {
     p4_custom.push_back(i->c_str());
   }
-  p4_custom.push_back(0);
+  p4_custom.push_back(CM_NULLPTR);
 
   OutputLogger custom_out(this->Log, "p4_customsync-out> ");
   OutputLogger custom_err(this->Log, "p4_customsync-err> ");
@@ -524,7 +516,7 @@ bool cmCTestP4::UpdateImpl()
   }
 
   p4_sync.push_back(source.c_str());
-  p4_sync.push_back(0);
+  p4_sync.push_back(CM_NULLPTR);
 
   OutputLogger out(this->Log, "p4_sync-out> ");
   OutputLogger err(this->Log, "p4_sync-err> ");
diff --git a/Source/CTest/cmCTestP4.h b/Source/CTest/cmCTestP4.h
index 917751e..eadc4fb 100644
--- a/Source/CTest/cmCTestP4.h
+++ b/Source/CTest/cmCTestP4.h
@@ -1,22 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestP4_h
 #define cmCTestP4_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGlobalVC.h"
 
+#include <iosfwd>
 #include <map>
+#include <string>
 #include <vector>
 
+class cmCTest;
+
 /** \class cmCTestP4
  * \brief Interaction with the Perforce command-line tool
  *
@@ -27,7 +24,7 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestP4(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestP4();
+  ~cmCTestP4() CM_OVERRIDE;
 
 private:
   std::vector<std::string> ChangeLists;
@@ -54,20 +51,21 @@ private:
   void SetP4Options(std::vector<char const*>& options);
 
   std::string GetWorkingRevision();
-  virtual void NoteOldRevision();
-  virtual void NoteNewRevision();
-  virtual bool UpdateImpl();
+  void NoteOldRevision() CM_OVERRIDE;
+  void NoteNewRevision() CM_OVERRIDE;
+  bool UpdateImpl() CM_OVERRIDE;
   bool UpdateCustom(const std::string& custom);
 
-  void LoadRevisions();
-  void LoadModifications();
+  void LoadRevisions() CM_OVERRIDE;
+  void LoadModifications() CM_OVERRIDE;
 
-  // Parsing helper classes.
-  class IdentifyParser;
   class ChangesParser;
-  class UserParser;
   class DescribeParser;
   class DiffParser;
+  // Parsing helper classes.
+  class IdentifyParser;
+  class UserParser;
+
   friend class IdentifyParser;
   friend class ChangesParser;
   friend class UserParser;
diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.cxx b/Source/CTest/cmCTestReadCustomFilesCommand.cxx
index 2613c1c..b21be87 100644
--- a/Source/CTest/cmCTestReadCustomFilesCommand.cxx
+++ b/Source/CTest/cmCTestReadCustomFilesCommand.cxx
@@ -1,22 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestReadCustomFilesCommand.h"
 
 #include "cmCTest.h"
 
+class cmExecutionStatus;
+
 bool cmCTestReadCustomFilesCommand::InitialPass(
-  std::vector<std::string> const& args, cmExecutionStatus&)
+  std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.h b/Source/CTest/cmCTestReadCustomFilesCommand.h
index 713fc66..29eba90 100644
--- a/Source/CTest/cmCTestReadCustomFilesCommand.h
+++ b/Source/CTest/cmCTestReadCustomFilesCommand.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestReadCustomFilesCommand_h
 #define cmCTestReadCustomFilesCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
+
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestReadCustomFiles
  * \brief Run a ctest script
@@ -28,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestReadCustomFilesCommand* ni = new cmCTestReadCustomFilesCommand;
     ni->CTest = this->CTest;
@@ -39,13 +39,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_read_custom_files"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_read_custom_files"; }
 
   cmTypeMacro(cmCTestReadCustomFilesCommand, cmCTestCommand);
 };
diff --git a/Source/CTest/cmCTestRunScriptCommand.cxx b/Source/CTest/cmCTestRunScriptCommand.cxx
index e143d50..238284a 100644
--- a/Source/CTest/cmCTestRunScriptCommand.cxx
+++ b/Source/CTest/cmCTestRunScriptCommand.cxx
@@ -1,22 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestRunScriptCommand.h"
 
 #include "cmCTestScriptHandler.h"
+#include "cmMakefile.h"
+
+#include <sstream>
+
+class cmExecutionStatus;
 
 bool cmCTestRunScriptCommand::InitialPass(std::vector<std::string> const& args,
-                                          cmExecutionStatus&)
+                                          cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->CTestScriptHandler->RunCurrentScript();
     return true;
   }
diff --git a/Source/CTest/cmCTestRunScriptCommand.h b/Source/CTest/cmCTestRunScriptCommand.h
index c503516..2978bb9 100644
--- a/Source/CTest/cmCTestRunScriptCommand.h
+++ b/Source/CTest/cmCTestRunScriptCommand.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestRunScriptCommand_h
 #define cmCTestRunScriptCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
+
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestRunScript
  * \brief Run a ctest script
@@ -28,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestRunScriptCommand* ni = new cmCTestRunScriptCommand;
     ni->CTest = this->CTest;
@@ -40,13 +40,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_run_script"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_run_script"; }
 
   cmTypeMacro(cmCTestRunScriptCommand, cmCTestCommand);
 };
diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx
index 9dda865..b30f6eb 100644
--- a/Source/CTest/cmCTestRunTest.cxx
+++ b/Source/CTest/cmCTestRunTest.cxx
@@ -1,35 +1,35 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestRunTest.h"
 
 #include "cmCTest.h"
 #include "cmCTestMemCheckHandler.h"
+#include "cmCTestTestHandler.h"
+#include "cmProcess.h"
 #include "cmSystemTools.h"
-#include "cm_curl.h"
 
+#include <cmConfigure.h>
+#include <cm_curl.h>
 #include <cm_zlib.h>
 #include <cmsys/Base64.h>
+#include <cmsys/Process.h>
+#include <cmsys/RegularExpression.hxx>
+#include <iomanip>
+#include <sstream>
+#include <stdio.h>
+#include <time.h>
+#include <utility>
 
 cmCTestRunTest::cmCTestRunTest(cmCTestTestHandler* handler)
 {
   this->CTest = handler->CTest;
   this->TestHandler = handler;
-  this->TestProcess = 0;
+  this->TestProcess = CM_NULLPTR;
   this->TestResult.ExecutionTime = 0;
   this->TestResult.ReturnValue = 0;
   this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
   this->TestResult.TestCount = 0;
-  this->TestResult.Properties = 0;
+  this->TestResult.Properties = CM_NULLPTR;
   this->ProcessOutput = "";
   this->CompressedOutput = "";
   this->CompressionRatio = 2;
@@ -54,7 +54,8 @@ bool cmCTestRunTest::CheckOutput()
     if (p == cmsysProcess_Pipe_None) {
       // Process has terminated and all output read.
       return false;
-    } else if (p == cmsysProcess_Pipe_STDOUT) {
+    }
+    if (p == cmsysProcess_Pipe_STDOUT) {
       // Store this line of output.
       cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->GetIndex()
                    << ": " << line << std::endl);
@@ -82,8 +83,7 @@ bool cmCTestRunTest::CheckOutput()
           }
         }
       }
-    } else // if(p == cmsysProcess_Pipe_Timeout)
-    {
+    } else { // if(p == cmsysProcess_Pipe_Timeout)
       break;
     }
   }
@@ -167,7 +167,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
     passIt;
   bool forceFail = false;
   bool outputTestErrorsToConsole = false;
-  if (!this->TestProperties->RequiredRegularExpressions.empty()) {
+  if (!this->TestProperties->RequiredRegularExpressions.empty() &&
+      this->FailedDependencies.empty()) {
     bool found = false;
     for (passIt = this->TestProperties->RequiredRegularExpressions.begin();
          passIt != this->TestProperties->RequiredRegularExpressions.end();
@@ -191,7 +192,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
     }
     reason += "]";
   }
-  if (!this->TestProperties->ErrorRegularExpressions.empty()) {
+  if (!this->TestProperties->ErrorRegularExpressions.empty() &&
+      this->FailedDependencies.empty()) {
     for (passIt = this->TestProperties->ErrorRegularExpressions.begin();
          passIt != this->TestProperties->ErrorRegularExpressions.end();
          ++passIt) {
@@ -207,7 +209,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
   }
   if (res == cmsysProcess_State_Exited) {
     bool success = !forceFail &&
-      (retVal == 0 || this->TestProperties->RequiredRegularExpressions.size());
+      (retVal == 0 ||
+       !this->TestProperties->RequiredRegularExpressions.empty());
     if (this->TestProperties->SkipReturnCode >= 0 &&
         this->TestProperties->SkipReturnCode == retVal) {
       this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
@@ -426,6 +429,23 @@ bool cmCTestRunTest::StartTest(size_t total)
   this->TestResult.Name = this->TestProperties->Name;
   this->TestResult.Path = this->TestProperties->Directory;
 
+  if (!this->FailedDependencies.empty()) {
+    this->TestProcess = new cmProcess;
+    std::string msg = "Failed test dependencies:";
+    for (std::set<std::string>::const_iterator it =
+           this->FailedDependencies.begin();
+         it != this->FailedDependencies.end(); ++it) {
+      msg += " " + *it;
+    }
+    *this->TestHandler->LogFile << msg << std::endl;
+    cmCTestLog(this->CTest, HANDLER_OUTPUT, msg << std::endl);
+    this->TestResult.Output = msg;
+    this->TestResult.FullCommandLine = "";
+    this->TestResult.CompletionStatus = "Not Run";
+    this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
+    return false;
+  }
+
   if (args.size() >= 2 && args[1] == "NOT_AVAILABLE") {
     this->TestProcess = new cmProcess;
     std::string msg;
@@ -537,7 +557,7 @@ void cmCTestRunTest::ComputeArguments()
                << " command: " << testCommand << std::endl);
 
   // Print any test-specific env vars in verbose mode
-  if (this->TestProperties->Environment.size()) {
+  if (!this->TestProperties->Environment.empty()) {
     cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index
                  << ": "
                  << "Environment variables: " << std::endl);
@@ -576,7 +596,7 @@ double cmCTestRunTest::ResolveTimeout()
     return timeout;
   }
   struct tm* lctime;
-  time_t current_time = time(0);
+  time_t current_time = time(CM_NULLPTR);
   lctime = gmtime(&current_time);
   int gm_hour = lctime->tm_hour;
   time_t gm_time = mktime(lctime);
diff --git a/Source/CTest/cmCTestRunTest.h b/Source/CTest/cmCTestRunTest.h
index 3dcc026..a10e271 100644
--- a/Source/CTest/cmCTestRunTest.h
+++ b/Source/CTest/cmCTestRunTest.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestRunTest_h
 #define cmCTestRunTest_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include <cmCTestTestHandler.h>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
-#include <cmProcess.h>
+class cmCTest;
+class cmProcess;
 
 /** \class cmRunTest
  * \brief represents a single test to be run
@@ -43,6 +40,11 @@ public:
 
   int GetIndex() { return this->Index; }
 
+  void AddFailedDependency(const std::string& failedTest)
+  {
+    this->FailedDependencies.insert(failedTest);
+  }
+
   std::string GetProcessOutput() { return this->ProcessOutput; }
 
   bool IsStopTimePassed() { return this->StopTimePassed; }
@@ -100,6 +102,7 @@ private:
   // The test results
   cmCTestTestHandler::cmCTestTestResult TestResult;
   int Index;
+  std::set<std::string> FailedDependencies;
   std::string StartTime;
   std::string ActualCommand;
   std::vector<std::string> Arguments;
diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx
index a6885aa..fc405ca 100644
--- a/Source/CTest/cmCTestSVN.cxx
+++ b/Source/CTest/cmCTestSVN.cxx
@@ -1,22 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestSVN.h"
 
 #include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessTools.h"
 #include "cmSystemTools.h"
 #include "cmXMLParser.h"
 #include "cmXMLWriter.h"
 
 #include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <ostream>
+#include <stdlib.h>
+#include <string.h>
 
 struct cmCTestSVN::Revision : public cmCTestVC::Revision
 {
@@ -62,7 +59,7 @@ private:
   cmsys::RegularExpression RegexRev;
   cmsys::RegularExpression RegexURL;
   cmsys::RegularExpression RegexRoot;
-  virtual bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexRev.find(this->Line)) {
       this->Rev = this->RegexRev.match(1);
@@ -80,11 +77,11 @@ static bool cmCTestSVNPathStarts(std::string const& p1, std::string const& p2)
   // Does path p1 start with path p2?
   if (p1.size() == p2.size()) {
     return p1 == p2;
-  } else if (p1.size() > p2.size() && p1[p2.size()] == '/') {
+  }
+  if (p1.size() > p2.size() && p1[p2.size()] == '/') {
     return strncmp(p1.c_str(), p2.c_str(), p2.size()) == 0;
-  } else {
-    return false;
   }
+  return false;
 }
 
 std::string cmCTestSVN::LoadInfo(SVNInfo& svninfo)
@@ -102,13 +99,8 @@ std::string cmCTestSVN::LoadInfo(SVNInfo& svninfo)
 
 void cmCTestSVN::NoteOldRevision()
 {
-  // Info for root repository
-  this->Repositories.push_back(SVNInfo(""));
-  this->RootInfo = &(this->Repositories.back());
-  // Info for the external repositories
-  this->LoadExternals();
+  this->LoadRepositories();
 
-  // Get info for all the repositories
   std::list<SVNInfo>::iterator itbeg = this->Repositories.begin();
   std::list<SVNInfo>::iterator itend = this->Repositories.end();
   for (; itbeg != itend; itbeg++) {
@@ -128,7 +120,8 @@ void cmCTestSVN::NoteOldRevision()
 
 void cmCTestSVN::NoteNewRevision()
 {
-  // Get info for the external repositories
+  this->LoadRepositories();
+
   std::list<SVNInfo>::iterator itbeg = this->Repositories.begin();
   std::list<SVNInfo>::iterator itend = this->Repositories.end();
   for (; itbeg != itend; itbeg++) {
@@ -206,7 +199,7 @@ private:
   cmCTestSVN* SVN;
   cmsys::RegularExpression RegexUpdate;
 
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexUpdate.find(this->Line)) {
       this->DoPath(this->RegexUpdate.match(1)[0],
@@ -271,8 +264,9 @@ bool cmCTestSVN::UpdateImpl()
 bool cmCTestSVN::RunSVNCommand(std::vector<char const*> const& parameters,
                                OutputParser* out, OutputParser* err)
 {
-  if (parameters.empty())
+  if (parameters.empty()) {
     return false;
+  }
 
   std::vector<char const*> args;
   args.push_back(this->CommandLineTool.c_str());
@@ -290,13 +284,12 @@ bool cmCTestSVN::RunSVNCommand(std::vector<char const*> const& parameters,
     args.push_back(i->c_str());
   }
 
-  args.push_back(0);
+  args.push_back(CM_NULLPTR);
 
   if (strcmp(parameters[0], "update") == 0) {
     return RunUpdateCommand(&args[0], out, err);
-  } else {
-    return RunChild(&args[0], out, err);
   }
+  return RunChild(&args[0], out, err);
 }
 
 class cmCTestSVN::LogParser : public cmCTestVC::OutputLogger,
@@ -310,7 +303,7 @@ public:
   {
     this->InitializeParser();
   }
-  ~LogParser() { this->CleanupParser(); }
+  ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
 private:
   cmCTestSVN* SVN;
   cmCTestSVN::SVNInfo& SVNRepo;
@@ -322,14 +315,14 @@ private:
   Change CurChange;
   std::vector<char> CData;
 
-  virtual bool ProcessChunk(const char* data, int length)
+  bool ProcessChunk(const char* data, int length) CM_OVERRIDE
   {
     this->OutputLogger::ProcessChunk(data, length);
     this->ParseChunk(data, length);
     return true;
   }
 
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     this->CData.clear();
     if (name == "logentry") {
@@ -347,12 +340,12 @@ private:
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     this->CData.insert(this->CData.end(), data, data + length);
   }
 
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "logentry") {
       this->SVN->DoRevisionSVN(this->Rev, this->Changes);
@@ -371,7 +364,7 @@ private:
     this->CData.clear();
   }
 
-  virtual void ReportError(int, int, const char* msg)
+  void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
   {
     this->SVN->Log << "Error parsing svn log xml: " << msg << "\n";
   }
@@ -440,7 +433,7 @@ public:
 private:
   cmCTestSVN* SVN;
   cmsys::RegularExpression RegexStatus;
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexStatus.find(this->Line)) {
       this->DoPath(this->RegexStatus.match(1)[0],
@@ -505,7 +498,7 @@ public:
 private:
   cmCTestSVN* SVN;
   cmsys::RegularExpression RegexExternal;
-  bool ProcessLine()
+  bool ProcessLine() CM_OVERRIDE
   {
     if (this->RegexExternal.find(this->Line)) {
       this->DoPath(this->RegexExternal.match(1));
@@ -528,8 +521,13 @@ private:
   }
 };
 
-void cmCTestSVN::LoadExternals()
+void cmCTestSVN::LoadRepositories()
 {
+  // Info for root repository
+  this->Repositories.clear();
+  this->Repositories.push_back(SVNInfo(""));
+  this->RootInfo = &(this->Repositories.back());
+
   // Run "svn status" to get the list of external repositories
   std::vector<const char*> svn_status;
   svn_status.push_back("status");
diff --git a/Source/CTest/cmCTestSVN.h b/Source/CTest/cmCTestSVN.h
index e596bdc..c0348c2 100644
--- a/Source/CTest/cmCTestSVN.h
+++ b/Source/CTest/cmCTestSVN.h
@@ -1,20 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestSVN_h
 #define cmCTestSVN_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGlobalVC.h"
 
+#include <iosfwd>
 #include <list>
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmXMLWriter;
 
 /** \class cmCTestSVN
  * \brief Interaction with subversion command-line tool
@@ -26,14 +25,14 @@ public:
   /** Construct with a CTest instance and update log stream.  */
   cmCTestSVN(cmCTest* ctest, std::ostream& log);
 
-  virtual ~cmCTestSVN();
+  ~cmCTestSVN() CM_OVERRIDE;
 
 private:
   // Implement cmCTestVC internal API.
-  virtual void CleanupImpl();
-  virtual void NoteOldRevision();
-  virtual void NoteNewRevision();
-  virtual bool UpdateImpl();
+  void CleanupImpl() CM_OVERRIDE;
+  void NoteOldRevision() CM_OVERRIDE;
+  void NoteNewRevision() CM_OVERRIDE;
+  bool UpdateImpl() CM_OVERRIDE;
 
   bool RunSVNCommand(std::vector<char const*> const& parameters,
                      OutputParser* out, OutputParser* err);
@@ -68,6 +67,7 @@ private:
 
   // Extended revision structure to include info about external it refers to.
   struct Revision;
+
   friend struct Revision;
 
   // Info of all the repositories (root, externals and nested ones).
@@ -77,9 +77,9 @@ private:
   SVNInfo* RootInfo;
 
   std::string LoadInfo(SVNInfo& svninfo);
-  void LoadExternals();
-  void LoadModifications();
-  void LoadRevisions();
+  void LoadRepositories();
+  void LoadModifications() CM_OVERRIDE;
+  void LoadRevisions() CM_OVERRIDE;
   void LoadRevisions(SVNInfo& svninfo);
 
   void GuessBase(SVNInfo& svninfo, std::vector<Change> const& changes);
@@ -87,14 +87,15 @@ private:
   void DoRevisionSVN(Revision const& revision,
                      std::vector<Change> const& changes);
 
-  void WriteXMLGlobal(cmXMLWriter& xml);
+  void WriteXMLGlobal(cmXMLWriter& xml) CM_OVERRIDE;
 
+  class ExternalParser;
   // Parsing helper classes.
   class InfoParser;
   class LogParser;
   class StatusParser;
   class UpdateParser;
-  class ExternalParser;
+
   friend class InfoParser;
   friend class LogParser;
   friend class StatusParser;
diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx
index 6389a9d..8848a70 100644
--- a/Source/CTest/cmCTestScriptHandler.cxx
+++ b/Source/CTest/cmCTestScriptHandler.cxx
@@ -1,44 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestScriptHandler.h"
 
 #include "cmCTest.h"
-#include "cmFunctionBlocker.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmake.h"
-
-//#include <cmsys/RegularExpression.hxx>
-#include <cmsys/Directory.hxx>
-#include <cmsys/Process.h>
-
-// used for sleep
-#ifdef _WIN32
-#include "windows.h"
-#endif
-
-#include <float.h>
-#include <math.h>
-#include <stdlib.h>
-#include <time.h>
-
-// needed for sleep
-#if !defined(_WIN32)
-#include <unistd.h>
-#endif
-
 #include "cmCTestBuildCommand.h"
+#include "cmCTestCommand.h"
 #include "cmCTestConfigureCommand.h"
 #include "cmCTestCoverageCommand.h"
 #include "cmCTestEmptyBinaryDirectoryCommand.h"
@@ -51,6 +17,31 @@
 #include "cmCTestTestCommand.h"
 #include "cmCTestUpdateCommand.h"
 #include "cmCTestUploadCommand.h"
+#include "cmFunctionBlocker.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <cmsys/Directory.hxx>
+#include <cmsys/Process.h>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+
+class cmExecutionStatus;
+struct cmListFileFunction;
 
 #define CTEST_INITIAL_CMAKE_OUTPUT_FILE_NAME "CTestInitialCMakeOutput.log"
 
@@ -59,9 +50,9 @@ class cmCTestScriptFunctionBlocker : public cmFunctionBlocker
 {
 public:
   cmCTestScriptFunctionBlocker() {}
-  virtual ~cmCTestScriptFunctionBlocker() {}
-  virtual bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
-                                 cmExecutionStatus&);
+  ~cmCTestScriptFunctionBlocker() CM_OVERRIDE {}
+  bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
+                         cmExecutionStatus& /*status*/) CM_OVERRIDE;
   // virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf);
   // virtual void ScopeEnded(cmMakefile &mf);
 
@@ -69,9 +60,9 @@ public:
 };
 
 // simply update the time and don't block anything
-bool cmCTestScriptFunctionBlocker::IsFunctionBlocked(const cmListFileFunction&,
-                                                     cmMakefile&,
-                                                     cmExecutionStatus&)
+bool cmCTestScriptFunctionBlocker::IsFunctionBlocked(
+  const cmListFileFunction& /*lff*/, cmMakefile& /*mf*/,
+  cmExecutionStatus& /*status*/)
 {
   this->CTestScriptHandler->UpdateElapsedTime();
   return false;
@@ -82,9 +73,9 @@ cmCTestScriptHandler::cmCTestScriptHandler()
   this->Backup = false;
   this->EmptyBinDir = false;
   this->EmptyBinDirOnce = false;
-  this->Makefile = 0;
-  this->CMake = 0;
-  this->GlobalGenerator = 0;
+  this->Makefile = CM_NULLPTR;
+  this->CMake = CM_NULLPTR;
+  this->GlobalGenerator = CM_NULLPTR;
 
   this->ScriptStartTime = 0;
 
@@ -121,10 +112,10 @@ void cmCTestScriptHandler::Initialize()
   this->ScriptStartTime = 0;
 
   delete this->Makefile;
-  this->Makefile = 0;
+  this->Makefile = CM_NULLPTR;
 
   delete this->GlobalGenerator;
-  this->GlobalGenerator = 0;
+  this->GlobalGenerator = CM_NULLPTR;
 
   delete this->CMake;
 }
@@ -200,7 +191,7 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
   for (size_t i = 1; i < initArgs.size(); ++i) {
     argv.push_back(initArgs[i].c_str());
   }
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   // Now create process object
   cmsysProcess* cp = cmsysProcess_New();
@@ -226,7 +217,7 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
   }
 
   // Properly handle output of the build command
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   int result = cmsysProcess_GetState(cp);
   int retVal = 0;
   bool failed = false;
@@ -265,7 +256,8 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
   return retVal;
 }
 
-static void ctestScriptProgressCallback(const char* m, float, void* cd)
+static void ctestScriptProgressCallback(const char* m, float /*unused*/,
+                                        void* cd)
 {
   cmCTest* ctest = static_cast<cmCTest*>(cd);
   if (m && *m) {
@@ -863,7 +855,7 @@ bool cmCTestScriptHandler::WriteInitialCache(const char* directory,
     return false;
   }
 
-  if (text != 0) {
+  if (text != CM_NULLPTR) {
     fout.write(text, strlen(text));
   }
 
diff --git a/Source/CTest/cmCTestScriptHandler.h b/Source/CTest/cmCTestScriptHandler.h
index e09e040..2bace58 100644
--- a/Source/CTest/cmCTestScriptHandler.h
+++ b/Source/CTest/cmCTestScriptHandler.h
@@ -1,26 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestScriptHandler_h
 #define cmCTestScriptHandler_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
-#include "cmListFileCache.h"
+#include <string>
+#include <vector>
 
-class cmMakefile;
+class cmCTest;
+class cmCTestCommand;
 class cmGlobalGenerator;
+class cmMakefile;
 class cmake;
-class cmCTestCommand;
 
 /** \class cmCTestScriptHandler
  * \brief A class that handles ctest -S invocations
@@ -71,7 +66,7 @@ public:
   /**
    * Run a dashboard using a specified confiuration script
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   /*
    * Run a script
@@ -104,9 +99,9 @@ public:
   double GetRemainingTimeAllowed();
 
   cmCTestScriptHandler();
-  ~cmCTestScriptHandler();
+  ~cmCTestScriptHandler() CM_OVERRIDE;
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   void CreateCMake();
   cmake* GetCMake() { return this->CMake; }
diff --git a/Source/CTest/cmCTestSleepCommand.cxx b/Source/CTest/cmCTestSleepCommand.cxx
index 102a303..2752cd3 100644
--- a/Source/CTest/cmCTestSleepCommand.cxx
+++ b/Source/CTest/cmCTestSleepCommand.cxx
@@ -1,23 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestSleepCommand.h"
 
 #include "cmCTestScriptHandler.h"
-#include <stdlib.h> // required for atoi
+
+#include <stdlib.h>
+
+class cmExecutionStatus;
 
 bool cmCTestSleepCommand::InitialPass(std::vector<std::string> const& args,
-                                      cmExecutionStatus&)
+                                      cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h
index ff7f146..b144012 100644
--- a/Source/CTest/cmCTestSleepCommand.h
+++ b/Source/CTest/cmCTestSleepCommand.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestSleepCommand_h
 #define cmCTestSleepCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+#include <vector>
+
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestSleep
  * \brief Run a ctest script
@@ -28,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestSleepCommand* ni = new cmCTestSleepCommand;
     ni->CTest = this->CTest;
@@ -40,13 +40,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_sleep"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_sleep"; }
 
   cmTypeMacro(cmCTestSleepCommand, cmCTestCommand);
 };
diff --git a/Source/CTest/cmCTestStartCommand.cxx b/Source/CTest/cmCTestStartCommand.cxx
index d561393..01a874b 100644
--- a/Source/CTest/cmCTestStartCommand.cxx
+++ b/Source/CTest/cmCTestStartCommand.cxx
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestStartCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestVC.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include <sstream>
+#include <stddef.h>
+
+class cmExecutionStatus;
 
 cmCTestStartCommand::cmCTestStartCommand()
 {
@@ -23,21 +20,21 @@ cmCTestStartCommand::cmCTestStartCommand()
 }
 
 bool cmCTestStartCommand::InitialPass(std::vector<std::string> const& args,
-                                      cmExecutionStatus&)
+                                      cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
 
   size_t cnt = 0;
   const char* smodel = args[cnt].c_str();
-  const char* src_dir = 0;
-  const char* bld_dir = 0;
+  const char* src_dir = CM_NULLPTR;
+  const char* bld_dir = CM_NULLPTR;
 
   cnt++;
 
-  this->CTest->SetSpecificTrack(0);
+  this->CTest->SetSpecificTrack(CM_NULLPTR);
   if (cnt < args.size() - 1) {
     if (args[cnt] == "TRACK") {
       cnt++;
diff --git a/Source/CTest/cmCTestStartCommand.h b/Source/CTest/cmCTestStartCommand.h
index 2aa6281..6bb0bc6 100644
--- a/Source/CTest/cmCTestStartCommand.h
+++ b/Source/CTest/cmCTestStartCommand.h
@@ -1,18 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestStartCommand_h
 #define cmCTestStartCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestCommand.h"
+#include "cmTypeMacro.h"
+
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestStart
  * \brief Run a ctest script
@@ -27,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestStartCommand* ni = new cmCTestStartCommand;
     ni->CTest = this->CTest;
@@ -41,8 +42,8 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * Will this invocation of ctest_start create a new TAG file?
@@ -57,7 +58,7 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_start"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_start"; }
 
   cmTypeMacro(cmCTestStartCommand, cmCTestCommand);
 
diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx
index 664552a..14b875f 100644
--- a/Source/CTest/cmCTestSubmitCommand.cxx
+++ b/Source/CTest/cmCTestSubmitCommand.cxx
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestSubmitCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
 #include "cmCTestSubmitHandler.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <sstream>
+
+class cmExecutionStatus;
 
 cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
 {
@@ -88,7 +86,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
                          extraFiles.end());
     if (!this->CTest->SubmitExtraFiles(newExtraFiles)) {
       this->SetError("problem submitting extra files.");
-      return 0;
+      return CM_NULLPTR;
     }
   }
 
@@ -96,7 +94,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
     this->CTest->GetInitializedHandler("submit");
   if (!handler) {
     this->SetError("internal CTest error. Cannot instantiate submit handler");
-    return 0;
+    return CM_NULLPTR;
   }
 
   // If no FILES or PARTS given, *all* PARTS are submitted by default.
diff --git a/Source/CTest/cmCTestSubmitCommand.h b/Source/CTest/cmCTestSubmitCommand.h
index 6323d8c..db8a604 100644
--- a/Source/CTest/cmCTestSubmitCommand.h
+++ b/Source/CTest/cmCTestSubmitCommand.h
@@ -1,20 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestSubmitCommand_h
 #define cmCTestSubmitCommand_h
 
-#include "cmCTestHandlerCommand.h"
+#include <cmConfigure.h>
 
 #include "cmCTest.h"
+#include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <set>
+#include <string>
+#include <vector>
+
+class cmCTestGenericHandler;
+class cmCommand;
+class cmExecutionStatus;
 
 /** \class cmCTestSubmit
  * \brief Run a ctest script
@@ -38,7 +39,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestSubmitCommand* ni = new cmCTestSubmitCommand;
     ni->CTest = this->CTest;
@@ -46,21 +47,21 @@ public:
     return ni;
   }
 
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_submit"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_submit"; }
 
   cmTypeMacro(cmCTestSubmitCommand, cmCTestHandlerCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
-  virtual bool CheckArgumentKeyword(std::string const& arg);
-  virtual bool CheckArgumentValue(std::string const& arg);
+  bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
+  bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
 
   enum
   {
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index f373348..06cd77f 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -1,37 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestSubmitHandler.h"
 
 #include "cmCTest.h"
+#include "cmCTestCurl.h"
 #include "cmCTestScriptHandler.h"
+#include "cmCurl.h"
 #include "cmGeneratedFileStream.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
-#include "cmVersion.h"
 #include "cmXMLParser.h"
 #include "cmake.h"
 
-#include <cmsys/Base64.h>
-#include <cmsys/Process.h>
-
-// For XML-RPC submission
-#include "cm_xmlrpc.h"
-
+#include <cm_curl.h>
 #include <cm_jsoncpp_reader.h>
-// For curl submission
-#include "cmCTestCurl.h"
-#include "cmCurl.h"
+#include <cm_jsoncpp_value.h>
+#include <cmsys/Process.h>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
 
+#if defined(CTEST_USE_XMLRPC)
+#include "cmVersion.h"
+#include <cm_xmlrpc.h>
 #include <sys/stat.h>
+#endif
 
 #define SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT 120
 
@@ -41,7 +34,7 @@ class cmCTestSubmitHandler::ResponseParser : public cmXMLParser
 {
 public:
   ResponseParser() { this->Status = STATUS_OK; }
-  ~ResponseParser() {}
+  ~ResponseParser() CM_OVERRIDE {}
 
 public:
   enum StatusType
@@ -69,7 +62,7 @@ private:
     return val;
   }
 
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     this->CurrentValue.clear();
     if (name == "cdash") {
@@ -77,12 +70,12 @@ private:
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     this->CurrentValue.insert(this->CurrentValue.end(), data, data + length);
   }
 
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "status") {
       std::string status = cmSystemTools::UpperCase(this->GetCurrentValue());
@@ -116,7 +109,8 @@ static size_t cmCTestSubmitHandlerWriteMemoryCallback(void* ptr, size_t size,
   return realsize;
 }
 
-static size_t cmCTestSubmitHandlerCurlDebugCallback(CURL*, curl_infotype,
+static size_t cmCTestSubmitHandlerCurlDebugCallback(CURL* /*unused*/,
+                                                    curl_infotype /*unused*/,
                                                     char* chPtr, size_t size,
                                                     void* data)
 {
@@ -150,7 +144,7 @@ void cmCTestSubmitHandler::Initialize()
   this->HTTPProxyAuth = "";
   this->FTPProxy = "";
   this->FTPProxyType = 0;
-  this->LogFile = 0;
+  this->LogFile = CM_NULLPTR;
   this->Files.clear();
 }
 
@@ -308,7 +302,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
   FILE* ftpfile;
   char error_buffer[1024];
   struct curl_slist* headers =
-    ::curl_slist_append(NULL, "Content-Type: text/xml");
+    ::curl_slist_append(CM_NULLPTR, "Content-Type: text/xml");
 
   /* In windows, this will init the winsock stuff */
   ::curl_global_init(CURL_GLOBAL_ALL);
@@ -507,10 +501,10 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
       // If curl failed for any reason, or checksum fails, wait and retry
       //
       if (res != CURLE_OK || this->HasErrors) {
-        std::string retryDelay = this->GetOption("RetryDelay") == NULL
+        std::string retryDelay = this->GetOption("RetryDelay") == CM_NULLPTR
           ? ""
           : this->GetOption("RetryDelay");
-        std::string retryCount = this->GetOption("RetryCount") == NULL
+        std::string retryCount = this->GetOption("RetryCount") == CM_NULLPTR
           ? ""
           : this->GetOption("RetryCount");
 
@@ -776,7 +770,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
   argv.push_back(scp_command.c_str()); // Scp command
   argv.push_back(scp_command.c_str()); // Dummy string for file
   argv.push_back(scp_command.c_str()); // Dummy string for remote url
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   cmsysProcess* cp = cmsysProcess_New();
   cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
@@ -807,12 +801,12 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
     char* data;
     int length;
 
-    while (cmsysProcess_WaitForData(cp, &data, &length, 0)) {
+    while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
       cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                          cmCTestLogWrite(data, length), this->Quiet);
     }
 
-    cmsysProcess_WaitForExit(cp, 0);
+    cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 
     int result = cmsysProcess_GetState(cp);
 
@@ -845,10 +839,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
     }
   }
   cmsysProcess_Delete(cp);
-  if (problems) {
-    return false;
-  }
-  return true;
+  return problems == 0;
 }
 
 bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix,
@@ -870,7 +861,6 @@ bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix,
   }
 
   cmCTest::SetOfStrings::const_iterator file;
-  bool problems = false;
   for (file = files.begin(); file != files.end(); ++file) {
     std::string lfname = localprefix;
     cmSystemTools::ConvertToUnixSlashes(lfname);
@@ -883,9 +873,6 @@ bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix,
   }
   std::string tagDoneFile = destination + "/" + remoteprefix + "DONE";
   cmSystemTools::Touch(tagDoneFile, true);
-  if (problems) {
-    return false;
-  }
   return true;
 }
 
@@ -909,8 +896,7 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
 
   /* Call the famous server at UserLand. */
   cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "   Submitting to: "
-                       << realURL.c_str() << " (" << remoteprefix.c_str()
-                       << ")" << std::endl,
+                       << realURL << " (" << remoteprefix << ")" << std::endl,
                      this->Quiet);
   cmCTest::SetOfStrings::const_iterator file;
   for (file = files.begin(); file != files.end(); ++file) {
@@ -921,12 +907,12 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
       local_file = localprefix + "/" + *file;
     }
     cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
-                       "   Submit file: " << local_file.c_str() << std::endl,
+                       "   Submit file: " << local_file << std::endl,
                        this->Quiet);
     struct stat st;
     if (::stat(local_file.c_str(), &st)) {
       cmCTestLog(this->CTest, ERROR_MESSAGE,
-                 "  Cannot find file: " << local_file.c_str() << std::endl);
+                 "  Cannot find file: " << local_file << std::endl);
       return false;
     }
 
@@ -934,15 +920,15 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
     // make sure the file is not too big.
     if (static_cast<off_t>(static_cast<size_t>(st.st_size)) !=
         static_cast<off_t>(st.st_size)) {
-      cmCTestLog(this->CTest, ERROR_MESSAGE,
-                 "  File too big: " << local_file.c_str() << std::endl);
+      cmCTestLog(this->CTest, ERROR_MESSAGE, "  File too big: " << local_file
+                                                                << std::endl);
       return false;
     }
     size_t fileSize = static_cast<size_t>(st.st_size);
     FILE* fp = cmsys::SystemTools::Fopen(local_file.c_str(), "rb");
     if (!fp) {
       cmCTestLog(this->CTest, ERROR_MESSAGE,
-                 "  Cannot open file: " << local_file.c_str() << std::endl);
+                 "  Cannot open file: " << local_file << std::endl);
       return false;
     }
 
@@ -951,7 +937,7 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
       delete[] fileBuffer;
       fclose(fp);
       cmCTestLog(this->CTest, ERROR_MESSAGE,
-                 "  Cannot read file: " << local_file.c_str() << std::endl);
+                 "  Cannot read file: " << local_file << std::endl);
       return false;
     }
     fclose(fp);
@@ -984,10 +970,9 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
   return true;
 }
 #else
-bool cmCTestSubmitHandler::SubmitUsingXMLRPC(std::string const&,
-                                             std::set<std::string> const&,
-                                             std::string const&,
-                                             std::string const&)
+bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
+  std::string const& /*unused*/, std::set<std::string> const& /*unused*/,
+  std::string const& /*unused*/, std::string const& /*unused*/)
 {
   return false;
 }
@@ -999,12 +984,12 @@ void cmCTestSubmitHandler::ConstructCDashURL(std::string& dropMethod,
   dropMethod = this->CTest->GetCTestConfiguration("DropMethod");
   url = dropMethod;
   url += "://";
-  if (this->CTest->GetCTestConfiguration("DropSiteUser").size() > 0) {
+  if (!this->CTest->GetCTestConfiguration("DropSiteUser").empty()) {
     url += this->CTest->GetCTestConfiguration("DropSiteUser");
     cmCTestOptionalLog(
       this->CTest, HANDLER_OUTPUT,
       this->CTest->GetCTestConfiguration("DropSiteUser").c_str(), this->Quiet);
-    if (this->CTest->GetCTestConfiguration("DropSitePassword").size() > 0) {
+    if (!this->CTest->GetCTestConfiguration("DropSitePassword").empty()) {
       url += ":" + this->CTest->GetCTestConfiguration("DropSitePassword");
       cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, ":******", this->Quiet);
     }
diff --git a/Source/CTest/cmCTestSubmitHandler.h b/Source/CTest/cmCTestSubmitHandler.h
index 87fa142..abe4fa2 100644
--- a/Source/CTest/cmCTestSubmitHandler.h
+++ b/Source/CTest/cmCTestSubmitHandler.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestSubmitHandler_h
 #define cmCTestSubmitHandler_h
 
+#include <cmConfigure.h>
+
+#include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
+
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
 
 /** \class cmCTestSubmitHandler
  * \brief Helper class for CTest
@@ -26,14 +26,14 @@ public:
   cmTypeMacro(cmCTestSubmitHandler, cmCTestGenericHandler);
 
   cmCTestSubmitHandler();
-  ~cmCTestSubmitHandler() { this->LogFile = 0; }
+  ~cmCTestSubmitHandler() CM_OVERRIDE { this->LogFile = CM_NULLPTR; }
 
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   /** Specify a set of parts (by name) to submit.  */
   void SelectParts(std::set<cmCTest::Part> const& parts);
@@ -84,6 +84,7 @@ private:
   std::string GetSubmitResultsPrefix();
 
   class ResponseParser;
+
   std::string HTTPProxy;
   int HTTPProxyType;
   std::string HTTPProxyAuth;
diff --git a/Source/CTest/cmCTestTestCommand.cxx b/Source/CTest/cmCTestTestCommand.cxx
index 7b437c6..a756188 100644
--- a/Source/CTest/cmCTestTestCommand.cxx
+++ b/Source/CTest/cmCTestTestCommand.cxx
@@ -1,18 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestTestCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include <sstream>
+#include <stdlib.h>
+#include <vector>
 
 cmCTestTestCommand::cmCTestTestCommand()
 {
@@ -27,7 +24,7 @@ cmCTestTestCommand::cmCTestTestCommand()
   this->Arguments[ctt_SCHEDULE_RANDOM] = "SCHEDULE_RANDOM";
   this->Arguments[ctt_STOP_TIME] = "STOP_TIME";
   this->Arguments[ctt_TEST_LOAD] = "TEST_LOAD";
-  this->Arguments[ctt_LAST] = 0;
+  this->Arguments[ctt_LAST] = CM_NULLPTR;
   this->Last = ctt_LAST;
 }
 
diff --git a/Source/CTest/cmCTestTestCommand.h b/Source/CTest/cmCTestTestCommand.h
index 212213e..6161acb 100644
--- a/Source/CTest/cmCTestTestCommand.h
+++ b/Source/CTest/cmCTestTestCommand.h
@@ -1,18 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestTestCommand_h
 #define cmCTestTestCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+
+class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestTest
  * \brief Run a ctest script
@@ -27,7 +26,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestTestCommand* ni = new cmCTestTestCommand;
     ni->CTest = this->CTest;
@@ -38,13 +37,13 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_test"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_test"; }
 
   cmTypeMacro(cmCTestTestCommand, cmCTestHandlerCommand);
 
 protected:
   virtual cmCTestGenericHandler* InitializeActualHandler();
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
   enum
   {
diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx
index 20ef693..0d0237f 100644
--- a/Source/CTest/cmCTestTestHandler.cxx
+++ b/Source/CTest/cmCTestTestHandler.cxx
@@ -1,40 +1,37 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestTestHandler.h"
 
 #include "cmCTest.h"
 #include "cmCTestBatchTestHandler.h"
 #include "cmCTestMultiProcessHandler.h"
-#include "cmCTestRunTest.h"
 #include "cmCommand.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
 #include "cm_utf8.h"
 #include "cmake.h"
+
+#include <algorithm>
 #include <cmsys/Base64.h>
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
-
-#include <float.h>
-#include <math.h>
+#include <functional>
+#include <iomanip>
+#include <iterator>
+#include <set>
+#include <sstream>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <time.h>
 
-#include <set>
+class cmExecutionStatus;
 
 class cmCTestSubdirCommand : public cmCommand
 {
@@ -42,7 +39,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestSubdirCommand* c = new cmCTestSubdirCommand;
     c->TestHandler = this->TestHandler;
@@ -53,13 +50,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& /*unused*/) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "subdirs"; }
+  std::string GetName() const CM_OVERRIDE { return "subdirs"; }
 
   cmTypeMacro(cmCTestSubdirCommand, cmCommand);
 
@@ -67,9 +64,9 @@ public:
 };
 
 bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args,
-                                       cmExecutionStatus&)
+                                       cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -123,7 +120,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestAddSubdirectoryCommand* c = new cmCTestAddSubdirectoryCommand;
     c->TestHandler = this->TestHandler;
@@ -134,13 +131,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& /*unused*/) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_subdirectory"; }
+  std::string GetName() const CM_OVERRIDE { return "add_subdirectory"; }
 
   cmTypeMacro(cmCTestAddSubdirectoryCommand, cmCommand);
 
@@ -148,9 +145,9 @@ public:
 };
 
 bool cmCTestAddSubdirectoryCommand::InitialPass(
-  std::vector<std::string> const& args, cmExecutionStatus&)
+  std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -197,7 +194,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestAddTestCommand* c = new cmCTestAddTestCommand;
     c->TestHandler = this->TestHandler;
@@ -208,13 +205,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const& /*args*/,
+                   cmExecutionStatus& /*unused*/) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_test"; }
+  std::string GetName() const CM_OVERRIDE { return "add_test"; }
 
   cmTypeMacro(cmCTestAddTestCommand, cmCommand);
 
@@ -222,7 +219,7 @@ public:
 };
 
 bool cmCTestAddTestCommand::InitialPass(std::vector<std::string> const& args,
-                                        cmExecutionStatus&)
+                                        cmExecutionStatus& /*unused*/)
 {
   if (args.size() < 2) {
     this->SetError("called with incorrect number of arguments");
@@ -237,7 +234,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestSetTestsPropertiesCommand* c = new cmCTestSetTestsPropertiesCommand;
     c->TestHandler = this->TestHandler;
@@ -248,13 +245,13 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
   */
-  virtual bool InitialPass(std::vector<std::string> const&,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const& /*args*/,
+                   cmExecutionStatus& /*unused*/) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_tests_properties"; }
+  std::string GetName() const CM_OVERRIDE { return "set_tests_properties"; }
 
   cmTypeMacro(cmCTestSetTestsPropertiesCommand, cmCommand);
 
@@ -262,7 +259,7 @@ public:
 };
 
 bool cmCTestSetTestsPropertiesCommand::InitialPass(
-  std::vector<std::string> const& args, cmExecutionStatus&)
+  std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
 {
   return this->TestHandler->SetTestsProperties(args);
 }
@@ -284,14 +281,13 @@ inline int GetNextNumber(std::string const& in, int& val,
     }
     pos = pos2 + 1;
     return 1;
+  }
+  if (in.size() - pos == 0) {
+    val = -1;
   } else {
-    if (in.size() - pos == 0) {
-      val = -1;
-    } else {
-      val = atoi(in.substr(pos, in.size() - pos).c_str());
-    }
-    return 0;
+    val = atoi(in.substr(pos, in.size() - pos).c_str());
   }
+  return 0;
 }
 
 // get the next number in a string with numbers separated by ,
@@ -311,14 +307,13 @@ inline int GetNextRealNumber(std::string const& in, double& val,
     }
     pos = pos2 + 1;
     return 1;
+  }
+  if (in.size() - pos == 0) {
+    val = -1;
   } else {
-    if (in.size() - pos == 0) {
-      val = -1;
-    } else {
-      val = atof(in.substr(pos, in.size() - pos).c_str());
-    }
-    return 0;
+    val = atof(in.substr(pos, in.size() - pos).c_str());
   }
+  return 0;
 }
 
 cmCTestTestHandler::cmCTestTestHandler()
@@ -336,7 +331,7 @@ cmCTestTestHandler::cmCTestTestHandler()
 
   this->MemCheck = false;
 
-  this->LogFile = 0;
+  this->LogFile = CM_NULLPTR;
 
   // regex to detect <DartMeasurement>...</DartMeasurement>
   this->DartStuff.compile("(<DartMeasurement.*/DartMeasurement[a-zA-Z]*>)");
@@ -550,7 +545,7 @@ int cmCTestTestHandler::ProcessHandler()
       cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot create "
                    << (this->MemCheck ? "memory check" : "testing")
                    << " XML file" << std::endl);
-      this->LogFile = 0;
+      this->LogFile = CM_NULLPTR;
       return 1;
     }
     cmXMLWriter xml(xmlfile);
@@ -558,15 +553,15 @@ int cmCTestTestHandler::ProcessHandler()
   }
 
   if (!this->PostProcessHandler()) {
-    this->LogFile = 0;
+    this->LogFile = CM_NULLPTR;
     return -1;
   }
 
   if (!failed.empty()) {
-    this->LogFile = 0;
+    this->LogFile = CM_NULLPTR;
     return -1;
   }
-  this->LogFile = 0;
+  this->LogFile = CM_NULLPTR;
   return 0;
 }
 
@@ -758,6 +753,9 @@ void cmCTestTestHandler::ComputeTestList()
     it->Index = cnt; // save the index into the test list for this test
     finalList.push_back(*it);
   }
+
+  UpdateForFixtures(finalList);
+
   // Save the total number of tests before exclusions
   this->TotalNumberOfTests = this->TestList.size();
   // Set the TestList to the final list of all test
@@ -787,6 +785,8 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed()
     finalList.push_back(*it);
   }
 
+  UpdateForFixtures(finalList);
+
   // Save the total number of tests before exclusions
   this->TotalNumberOfTests = this->TestList.size();
 
@@ -796,6 +796,169 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed()
   this->UpdateMaxTestNameWidth();
 }
 
+void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
+{
+  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+                     "Updating test list for fixtures" << std::endl,
+                     this->Quiet);
+
+  // Prepare some maps to help us find setup and cleanup tests for
+  // any given fixture
+  typedef std::set<ListOfTests::const_iterator> TestIteratorSet;
+  typedef std::map<std::string, TestIteratorSet> FixtureDependencies;
+  FixtureDependencies fixtureSetups;
+  FixtureDependencies fixtureDeps;
+
+  for (ListOfTests::const_iterator it = this->TestList.begin();
+       it != this->TestList.end(); ++it) {
+    const cmCTestTestProperties& p = *it;
+
+    const std::set<std::string>& setups = p.FixturesSetup;
+    for (std::set<std::string>::const_iterator depsIt = setups.begin();
+         depsIt != setups.end(); ++depsIt) {
+      fixtureSetups[*depsIt].insert(it);
+      fixtureDeps[*depsIt].insert(it);
+    }
+
+    const std::set<std::string>& cleanups = p.FixturesCleanup;
+    for (std::set<std::string>::const_iterator depsIt = cleanups.begin();
+         depsIt != cleanups.end(); ++depsIt) {
+      fixtureDeps[*depsIt].insert(it);
+    }
+  }
+
+  // Prepare fast lookup of tests already included in our list of tests
+  std::set<std::string> addedTests;
+  for (ListOfTests::const_iterator it = tests.begin(); it != tests.end();
+       ++it) {
+    const cmCTestTestProperties& p = *it;
+    addedTests.insert(p.Name);
+  }
+
+  // This is a lookup of fixture name to a list of indices into the
+  // final tests array for tests which require that fixture. It is
+  // needed at the end to populate dependencies of the cleanup tests
+  // in our final list of tests.
+  std::map<std::string, std::vector<size_t> > fixtureRequirements;
+
+  // Use integer index for iteration because we append to
+  // the tests vector as we go
+  size_t fixtureTestsAdded = 0;
+  std::set<std::string> addedFixtures;
+  for (size_t i = 0; i < tests.size(); ++i) {
+    if (tests[i].FixturesRequired.empty()) {
+      continue;
+    }
+    // Must copy the set of fixtures because we may invalidate
+    // the tests array by appending to it
+    const std::set<std::string> fixtures = tests[i].FixturesRequired;
+    for (std::set<std::string>::const_iterator fixturesIt = fixtures.begin();
+         fixturesIt != fixtures.end(); ++fixturesIt) {
+
+      const std::string& requiredFixtureName = *fixturesIt;
+      if (requiredFixtureName.empty()) {
+        continue;
+      }
+
+      fixtureRequirements[requiredFixtureName].push_back(i);
+
+      // Add dependencies to this test for all of the setup tests
+      // associated with the required fixture. If any of those setup
+      // tests fail, this test should not run. We make the fixture's
+      // cleanup tests depend on this test case later.
+      FixtureDependencies::const_iterator setupIt =
+        fixtureSetups.find(requiredFixtureName);
+      if (setupIt != fixtureSetups.end()) {
+        for (TestIteratorSet::const_iterator sIt = setupIt->second.begin();
+             sIt != setupIt->second.end(); ++sIt) {
+          const std::string& setupTestName = (**sIt).Name;
+          tests[i].RequireSuccessDepends.insert(setupTestName);
+          if (std::find(tests[i].Depends.begin(), tests[i].Depends.end(),
+                        setupTestName) == tests[i].Depends.end()) {
+            tests[i].Depends.push_back(setupTestName);
+          }
+        }
+      }
+
+      // Append any fixture setup/cleanup tests to our test list if they
+      // are not already in it (they could have been in the original
+      // set of tests passed to us at the outset or have already been
+      // added from a previously checked test). A fixture isn't required
+      // to have setup/cleanup tests.
+      if (!addedFixtures.insert(requiredFixtureName).second) {
+        // Already added this fixture
+        continue;
+      }
+      FixtureDependencies::const_iterator fixtureIt =
+        fixtureDeps.find(requiredFixtureName);
+      if (fixtureIt == fixtureDeps.end()) {
+        // No setup or cleanup tests for this fixture
+        continue;
+      }
+
+      const TestIteratorSet& testIters = fixtureIt->second;
+      for (TestIteratorSet::const_iterator depsIt = testIters.begin();
+           depsIt != testIters.end(); ++depsIt) {
+        ListOfTests::const_iterator lotIt = *depsIt;
+        const cmCTestTestProperties& p = *lotIt;
+
+        if (!addedTests.insert(p.Name).second) {
+          // Already have p in our test list
+          continue;
+        }
+
+        // This is a test not yet in our list, so add it and
+        // update its index to reflect where it was in the original
+        // full list of all tests (needed to track individual tests
+        // across ctest runs for re-run failed, etc.)
+        tests.push_back(p);
+        tests.back().Index =
+          1 + static_cast<int>(std::distance(this->TestList.begin(), lotIt));
+        ++fixtureTestsAdded;
+
+        cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Added test "
+                             << p.Name << " required by fixture "
+                             << requiredFixtureName << std::endl,
+                           this->Quiet);
+      }
+    }
+  }
+
+  // Now that we have the final list of tests, we can update all cleanup
+  // tests to depend on those tests which require that fixture
+  for (ListOfTests::iterator tIt = tests.begin(); tIt != tests.end(); ++tIt) {
+    cmCTestTestProperties& p = *tIt;
+    const std::set<std::string>& cleanups = p.FixturesCleanup;
+    for (std::set<std::string>::const_iterator fIt = cleanups.begin();
+         fIt != cleanups.end(); ++fIt) {
+      const std::string& fixture = *fIt;
+      std::map<std::string, std::vector<size_t> >::const_iterator cIt =
+        fixtureRequirements.find(fixture);
+      if (cIt == fixtureRequirements.end()) {
+        // No test cases require the fixture this cleanup test is for.
+        // This cleanup test must have been part of the original test
+        // list passed in (which is not an error)
+        continue;
+      }
+
+      const std::vector<size_t>& indices = cIt->second;
+      for (std::vector<size_t>::const_iterator indexIt = indices.begin();
+           indexIt != indices.end(); ++indexIt) {
+        const std::string& reqTestName = tests[*indexIt].Name;
+        if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) ==
+            p.Depends.end()) {
+          p.Depends.push_back(reqTestName);
+        }
+      }
+    }
+  }
+
+  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Added "
+                       << fixtureTestsAdded
+                       << " tests to meet fixture requirements" << std::endl,
+                     this->Quiet);
+}
+
 void cmCTestTestHandler::UpdateMaxTestNameWidth()
 {
   std::string::size_type max = this->CTest->GetMaxTestNameWidth();
@@ -936,7 +1099,7 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
 
   bool randomSchedule = this->CTest->GetScheduleType() == "Random";
   if (randomSchedule) {
-    srand((unsigned)time(0));
+    srand((unsigned)time(CM_NULLPTR));
   }
 
   for (ListOfTests::iterator it = this->TestList.begin();
@@ -986,7 +1149,8 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
   *this->LogFile << "End testing: " << this->CTest->CurrentTime() << std::endl;
 }
 
-void cmCTestTestHandler::GenerateTestCommand(std::vector<std::string>&, int)
+void cmCTestTestHandler::GenerateTestCommand(
+  std::vector<std::string>& /*unused*/, int /*unused*/)
 {
 }
 
@@ -1125,7 +1289,7 @@ void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml,
                                      cmCTestTestResult* result)
 {
   if (result->Status != cmCTestTestHandler::COMPLETED &&
-      result->Properties->AttachOnFail.size()) {
+      !result->Properties->AttachOnFail.empty()) {
     result->Properties->AttachedFiles.insert(
       result->Properties->AttachedFiles.end(),
       result->Properties->AttachOnFail.begin(),
@@ -1154,7 +1318,8 @@ int cmCTestTestHandler::ExecuteCommands(std::vector<std::string>& vec)
     int retVal = 0;
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                        "Run command: " << *it << std::endl, this->Quiet);
-    if (!cmSystemTools::RunSingleCommand(it->c_str(), 0, 0, &retVal, 0,
+    if (!cmSystemTools::RunSingleCommand(it->c_str(), CM_NULLPTR, CM_NULLPTR,
+                                         &retVal, CM_NULLPTR,
                                          cmSystemTools::OUTPUT_MERGE
                                          /*this->Verbose*/) ||
         retVal != 0) {
@@ -1321,7 +1486,7 @@ std::string cmCTestTestHandler::FindExecutable(
                  << "Looked in the following places:\n");
     for (std::vector<std::string>::iterator i = failed.begin();
          i != failed.end(); ++i) {
-      cmCTestLog(ctest, HANDLER_OUTPUT, i->c_str() << "\n");
+      cmCTestLog(ctest, HANDLER_OUTPUT, *i << "\n");
     }
   }
 
@@ -1351,7 +1516,7 @@ void cmCTestTestHandler::GetListOfTests()
   cm.SetHomeOutputDirectory("");
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator gg(&cm);
-  cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
   mf->AddDefinition("CTEST_CONFIGURATION_TYPE",
                     this->CTest->GetConfigType().c_str());
 
@@ -1406,7 +1571,7 @@ void cmCTestTestHandler::UseIncludeRegExp()
 void cmCTestTestHandler::UseExcludeRegExp()
 {
   this->UseExcludeRegExpFlag = true;
-  this->UseExcludeRegExpFirst = this->UseIncludeRegExpFlag ? false : true;
+  this->UseExcludeRegExpFirst = !this->UseIncludeRegExpFlag;
 }
 
 const char* cmCTestTestHandler::GetTestStatus(int status)
@@ -1677,7 +1842,7 @@ void cmCTestTestHandler::GenerateRegressionImages(cmXMLWriter& xml,
           xml.Attribute(measurementfile.match(3).c_str(),
                         measurementfile.match(4));
           xml.Attribute("encoding", "base64");
-          std::stringstream ostr;
+          std::ostringstream ostr;
           for (size_t cc = 0; cc < rlen; cc++) {
             ostr << encoded_buffer[cc];
             if (cc % 60 == 0 && cc) {
@@ -1823,6 +1988,24 @@ bool cmCTestTestHandler::SetTestsProperties(
 
             rtit->LockedResources.insert(lval.begin(), lval.end());
           }
+          if (key == "FIXTURES_SETUP") {
+            std::vector<std::string> lval;
+            cmSystemTools::ExpandListArgument(val, lval);
+
+            rtit->FixturesSetup.insert(lval.begin(), lval.end());
+          }
+          if (key == "FIXTURES_CLEANUP") {
+            std::vector<std::string> lval;
+            cmSystemTools::ExpandListArgument(val, lval);
+
+            rtit->FixturesCleanup.insert(lval.begin(), lval.end());
+          }
+          if (key == "FIXTURES_REQUIRED") {
+            std::vector<std::string> lval;
+            cmSystemTools::ExpandListArgument(val, lval);
+
+            rtit->FixturesRequired.insert(lval.begin(), lval.end());
+          }
           if (key == "TIMEOUT") {
             rtit->Timeout = atof(val.c_str());
             rtit->ExplicitTimeout = true;
diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h
index 4b74ce0..73b3174 100644
--- a/Source/CTest/cmCTestTestHandler.h
+++ b/Source/CTest/cmCTestTestHandler.h
@@ -1,22 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestTestHandler_h
 #define cmCTestTestHandler_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
 #include <cmsys/RegularExpression.hxx>
-
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <stddef.h>
+#include <string>
+#include <utility>
+#include <vector>
+
+class cmCTest;
 class cmMakefile;
 class cmXMLWriter;
 
@@ -36,7 +37,7 @@ public:
   /**
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   /**
    * When both -R and -I are used should te resulting test list be the
@@ -54,7 +55,7 @@ public:
   /**
    * This method is called when reading CTest custom file
    */
-  void PopulateCustomVectors(cmMakefile* mf);
+  void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
 
   ///! Control the use of the regular expresisons, call these methods to turn
   /// them on
@@ -90,7 +91,7 @@ public:
    */
   bool SetTestsProperties(const std::vector<std::string>& args);
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   // NOTE: This struct is Saved/Restored
   // in cmCTestTestHandler, if you add to this class
@@ -128,6 +129,10 @@ public:
     std::vector<std::string> Environment;
     std::vector<std::string> Labels;
     std::set<std::string> LockedResources;
+    std::set<std::string> FixturesSetup;
+    std::set<std::string> FixturesCleanup;
+    std::set<std::string> FixturesRequired;
+    std::set<std::string> RequireSuccessDepends;
   };
 
   struct cmCTestTestResult
@@ -240,6 +245,11 @@ private:
   // based on LastTestFailed.log
   void ComputeTestListForRerunFailed();
 
+  // add required setup/cleanup tests not already in the
+  // list of tests to be run and update dependencies between
+  // tests to account for fixture setup/cleanup
+  void UpdateForFixtures(ListOfTests& tests) const;
+
   void UpdateMaxTestNameWidth();
 
   bool GetValue(const char* tag, std::string& value, std::istream& fin);
diff --git a/Source/CTest/cmCTestUpdateCommand.cxx b/Source/CTest/cmCTestUpdateCommand.cxx
index f1bae5d..8c03754 100644
--- a/Source/CTest/cmCTestUpdateCommand.cxx
+++ b/Source/CTest/cmCTestUpdateCommand.cxx
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestUpdateCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include <vector>
 
 cmCTestGenericHandler* cmCTestUpdateCommand::InitializeHandler()
 {
@@ -83,12 +78,12 @@ cmCTestGenericHandler* cmCTestUpdateCommand::InitializeHandler()
     this->CTest->GetInitializedHandler("update");
   if (!handler) {
     this->SetError("internal CTest error. Cannot instantiate update handler");
-    return 0;
+    return CM_NULLPTR;
   }
   handler->SetCommand(this);
   if (source_dir.empty()) {
     this->SetError("source directory not specified. Please use SOURCE tag");
-    return 0;
+    return CM_NULLPTR;
   }
   handler->SetOption("SourceDirectory", source_dir.c_str());
   handler->SetQuiet(this->Quiet);
diff --git a/Source/CTest/cmCTestUpdateCommand.h b/Source/CTest/cmCTestUpdateCommand.h
index e807193..9d1a86e 100644
--- a/Source/CTest/cmCTestUpdateCommand.h
+++ b/Source/CTest/cmCTestUpdateCommand.h
@@ -1,18 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestUpdateCommand_h
 #define cmCTestUpdateCommand_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+
+class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestUpdate
  * \brief Run a ctest script
@@ -27,7 +26,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestUpdateCommand* ni = new cmCTestUpdateCommand;
     ni->CTest = this->CTest;
@@ -38,12 +37,12 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_update"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_update"; }
 
   cmTypeMacro(cmCTestUpdateCommand, cmCTestHandlerCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx
index 4eaa16b..0998d59 100644
--- a/Source/CTest/cmCTestUpdateHandler.cxx
+++ b/Source/CTest/cmCTestUpdateHandler.cxx
@@ -1,27 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestUpdateHandler.h"
 
 #include "cmCLocaleEnvironmentScope.h"
 #include "cmCTest.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmVersion.h"
-#include "cmXMLParser.h"
-#include "cmXMLWriter.h"
-#include "cmake.h"
-
 #include "cmCTestBZR.h"
 #include "cmCTestCVS.h"
 #include "cmCTestGIT.h"
@@ -29,20 +11,13 @@
 #include "cmCTestP4.h"
 #include "cmCTestSVN.h"
 #include "cmCTestVC.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+#include "cmVersion.h"
+#include "cmXMLWriter.h"
 
-#include <cmsys/auto_ptr.hxx>
-
-//#include <cmsys/RegularExpression.hxx>
-#include <cmsys/Process.h>
-
-// used for sleep
-#ifdef _WIN32
-#include "windows.h"
-#endif
-
-#include <float.h>
-#include <math.h>
-#include <stdlib.h>
+#include <cm_auto_ptr.hxx>
+#include <sstream>
 
 static const char* cmCTestUpdateHandlerUpdateStrings[] = {
   "Unknown", "CVS", "SVN", "BZR", "GIT", "HG", "P4"
@@ -159,7 +134,7 @@ int cmCTestUpdateHandler::ProcessHandler()
                      , this->Quiet);
 
   // Create an object to interact with the VCS tool.
-  cmsys::auto_ptr<cmCTestVC> vc;
+  CM_AUTO_PTR<cmCTestVC> vc;
   switch (this->UpdateType) {
     case e_CVS:
       vc.reset(new cmCTestCVS(this->CTest, ofs));
@@ -334,7 +309,7 @@ bool cmCTestUpdateHandler::SelectVCS()
 
   // If no update command was specified, lookup one for this VCS tool.
   if (this->UpdateCommand.empty()) {
-    const char* key = 0;
+    const char* key = CM_NULLPTR;
     switch (this->UpdateType) {
       case e_CVS:
         key = "CVSCommand";
diff --git a/Source/CTest/cmCTestUpdateHandler.h b/Source/CTest/cmCTestUpdateHandler.h
index d44e619..c9a8682 100644
--- a/Source/CTest/cmCTestUpdateHandler.h
+++ b/Source/CTest/cmCTestUpdateHandler.h
@@ -1,21 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestUpdateHandler_h
 #define cmCTestUpdateHandler_h
 
+#include <cmConfigure.h>
+
 #include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
-#include "cmListFileCache.h"
+#include <string>
+#include <utility>
+#include <vector>
 
 /** \class cmCTestUpdateHandler
  * \brief A class that handles ctest -S invocations
@@ -29,7 +24,7 @@ public:
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
   cmCTestUpdateHandler();
 
@@ -48,7 +43,7 @@ public:
   /**
    * Initialize handler
    */
-  virtual void Initialize();
+  void Initialize() CM_OVERRIDE;
 
 private:
   // Some structures needed for update
diff --git a/Source/CTest/cmCTestUploadCommand.cxx b/Source/CTest/cmCTestUploadCommand.cxx
index c85db02..9266bce 100644
--- a/Source/CTest/cmCTestUploadCommand.cxx
+++ b/Source/CTest/cmCTestUploadCommand.cxx
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestUploadCommand.h"
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
 #include "cmCTestUploadHandler.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <sstream>
 
 cmCTestGenericHandler* cmCTestUploadCommand::InitializeHandler()
 {
@@ -21,7 +17,7 @@ cmCTestGenericHandler* cmCTestUploadCommand::InitializeHandler()
     this->CTest->GetInitializedHandler("upload");
   if (!handler) {
     this->SetError("internal CTest error. Cannot instantiate upload handler");
-    return 0;
+    return CM_NULLPTR;
   }
   static_cast<cmCTestUploadHandler*>(handler)->SetFiles(this->Files);
 
@@ -40,23 +36,30 @@ bool cmCTestUploadCommand::CheckArgumentKeyword(std::string const& arg)
     this->Quiet = true;
     return true;
   }
+  if (arg == "CAPTURE_CMAKE_ERROR") {
+    this->ArgumentDoing = ArgumentDoingCaptureCMakeError;
+    return true;
+  }
   return false;
 }
 
 bool cmCTestUploadCommand::CheckArgumentValue(std::string const& arg)
 {
+  if (this->ArgumentDoing == ArgumentDoingCaptureCMakeError) {
+    this->Values[ct_CAPTURE_CMAKE_ERROR] = arg.c_str();
+    return true;
+  }
   if (this->ArgumentDoing == ArgumentDoingFiles) {
     if (cmSystemTools::FileExists(arg.c_str())) {
       this->Files.insert(arg);
       return true;
-    } else {
-      std::ostringstream e;
-      e << "File \"" << arg << "\" does not exist. Cannot submit "
-        << "a non-existent file.";
-      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-      this->ArgumentDoing = ArgumentDoingError;
-      return false;
     }
+    std::ostringstream e;
+    e << "File \"" << arg << "\" does not exist. Cannot submit "
+      << "a non-existent file.";
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    this->ArgumentDoing = ArgumentDoingError;
+    return false;
   }
 
   // Look for other arguments.
diff --git a/Source/CTest/cmCTestUploadCommand.h b/Source/CTest/cmCTestUploadCommand.h
index 551be2b..b858077 100644
--- a/Source/CTest/cmCTestUploadCommand.h
+++ b/Source/CTest/cmCTestUploadCommand.h
@@ -1,20 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestUploadCommand_h
 #define cmCTestUploadCommand_h
 
-#include "cmCTestHandlerCommand.h"
+#include <cmConfigure.h>
 
 #include "cmCTest.h"
+#include "cmCTestHandlerCommand.h"
+#include "cmTypeMacro.h"
+
+#include <string>
+
+class cmCTestGenericHandler;
+class cmCommand;
 
 /** \class cmCTestUpload
  * \brief Run a ctest script
@@ -30,7 +28,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmCTestUploadCommand* ni = new cmCTestUploadCommand;
     ni->CTest = this->CTest;
@@ -41,19 +39,20 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "ctest_upload"; }
+  std::string GetName() const CM_OVERRIDE { return "ctest_upload"; }
 
   cmTypeMacro(cmCTestUploadCommand, cmCTestHandlerCommand);
 
 protected:
-  cmCTestGenericHandler* InitializeHandler();
+  cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
-  virtual bool CheckArgumentKeyword(std::string const& arg);
-  virtual bool CheckArgumentValue(std::string const& arg);
+  bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
+  bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
 
   enum
   {
     ArgumentDoingFiles = Superclass::ArgumentDoingLast1,
+    ArgumentDoingCaptureCMakeError,
     ArgumentDoingLast2
   };
 
diff --git a/Source/CTest/cmCTestUploadHandler.cxx b/Source/CTest/cmCTestUploadHandler.cxx
index 6a3b830..05a3984 100644
--- a/Source/CTest/cmCTestUploadHandler.cxx
+++ b/Source/CTest/cmCTestUploadHandler.cxx
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestUploadHandler.h"
 
 #include "cmGeneratedFileStream.h"
 #include "cmVersion.h"
 #include "cmXMLWriter.h"
 
+#include <ostream>
+#include <set>
+#include <string>
+
 cmCTestUploadHandler::cmCTestUploadHandler()
 {
   this->Initialize();
diff --git a/Source/CTest/cmCTestUploadHandler.h b/Source/CTest/cmCTestUploadHandler.h
index 23ed35a..251cd3e 100644
--- a/Source/CTest/cmCTestUploadHandler.h
+++ b/Source/CTest/cmCTestUploadHandler.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestUploadHandler_h
 #define cmCTestUploadHandler_h
 
+#include <cmConfigure.h>
+
+#include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmTypeMacro.h"
 
 /** \class cmCTestUploadHandler
  * \brief Helper class for CTest
@@ -26,14 +21,14 @@ public:
   cmTypeMacro(cmCTestUploadHandler, cmCTestGenericHandler);
 
   cmCTestUploadHandler();
-  ~cmCTestUploadHandler() {}
+  ~cmCTestUploadHandler() CM_OVERRIDE {}
 
   /*
    * The main entry point for this class
    */
-  int ProcessHandler();
+  int ProcessHandler() CM_OVERRIDE;
 
-  void Initialize();
+  void Initialize() CM_OVERRIDE;
 
   /** Specify a set of files to submit.  */
   void SetFiles(cmCTest::SetOfStrings const& files);
diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx
index e9934e5..7a2fa69 100644
--- a/Source/CTest/cmCTestVC.cxx
+++ b/Source/CTest/cmCTestVC.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestVC.h"
 
 #include "cmCTest.h"
@@ -16,6 +7,10 @@
 #include "cmXMLWriter.h"
 
 #include <cmsys/Process.h>
+#include <sstream>
+#include <stdio.h>
+#include <time.h>
+#include <vector>
 
 cmCTestVC::cmCTestVC(cmCTest* ct, std::ostream& log)
   : CTest(ct)
@@ -65,7 +60,7 @@ bool cmCTestVC::InitialCheckout(const char* command)
        ai != args.end(); ++ai) {
     vc_co.push_back(ai->c_str());
   }
-  vc_co.push_back(0);
+  vc_co.push_back(CM_NULLPTR);
 
   // Run the initial checkout command and log its output.
   this->Log << "--- Begin Initial Checkout ---\n";
@@ -185,7 +180,7 @@ bool cmCTestVC::WriteXML(cmXMLWriter& xml)
   return result;
 }
 
-bool cmCTestVC::WriteXMLUpdates(cmXMLWriter&)
+bool cmCTestVC::WriteXMLUpdates(cmXMLWriter& /*unused*/)
 {
   cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
              "* CTest cannot extract updates for this VCS tool.\n");
diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h
index 4ae38eb..4f2bba0 100644
--- a/Source/CTest/cmCTestVC.h
+++ b/Source/CTest/cmCTestVC.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTestVC_h
 #define cmCTestVC_h
 
+#include <cmConfigure.h>
+
 #include "cmProcessTools.h"
 
+#include <iosfwd>
+#include <string>
+
 class cmCTest;
 class cmXMLWriter;
 
@@ -93,7 +89,6 @@ public:
   };
 
 protected:
-  struct File;
   friend struct File;
 
   /** Represent change to one file.  */
@@ -104,8 +99,8 @@ protected:
     Revision const* PriorRev;
     File()
       : Status(PathUpdated)
-      , Rev(0)
-      , PriorRev(0)
+      , Rev(CM_NULLPTR)
+      , PriorRev(CM_NULLPTR)
     {
     }
     File(PathStatus status, Revision const* rev, Revision const* priorRev)
@@ -121,11 +116,11 @@ protected:
 
   /** Run a command line and send output to given parsers.  */
   bool RunChild(char const* const* cmd, OutputParser* out, OutputParser* err,
-                const char* workDir = 0);
+                const char* workDir = CM_NULLPTR);
 
   /** Run VC update command line and send output to given parsers.  */
   bool RunUpdateCommand(char const* const* cmd, OutputParser* out,
-                        OutputParser* err = 0);
+                        OutputParser* err = CM_NULLPTR);
 
   /** Write xml element for one file.  */
   void WriteXMLEntry(cmXMLWriter& xml, std::string const& path,
diff --git a/Source/CTest/cmParseBlanketJSCoverage.cxx b/Source/CTest/cmParseBlanketJSCoverage.cxx
index fa539e4..6fa982e 100644
--- a/Source/CTest/cmParseBlanketJSCoverage.cxx
+++ b/Source/CTest/cmParseBlanketJSCoverage.cxx
@@ -1,20 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmParseBlanketJSCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
-#include <cmsys/Directory.hxx>
+
 #include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
 #include <stdio.h>
 #include <stdlib.h>
 
@@ -42,9 +34,8 @@ public:
       std::string foundFileName =
         line.substr(begIndex + 3, endIndex - (begIndex + 4));
       return foundFileName;
-    } else {
-      return line.substr(begIndex, line.npos);
     }
+    return line.substr(begIndex, line.npos);
   }
   bool ParseFile(std::string const& file)
   {
diff --git a/Source/CTest/cmParseBlanketJSCoverage.h b/Source/CTest/cmParseBlanketJSCoverage.h
index a4f6670..660590d 100644
--- a/Source/CTest/cmParseBlanketJSCoverage.h
+++ b/Source/CTest/cmParseBlanketJSCoverage.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseBlanketJSCoverage_h
 #define cmParseBlanketJSCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParseBlanketJSCoverage
  * \brief Parse BlanketJS coverage information
@@ -39,6 +35,7 @@ public:
 
 protected:
   class JSONParser;
+
   cmCTestCoverageHandlerContainer& Coverage;
   cmCTest* CTest;
 };
diff --git a/Source/CTest/cmParseCacheCoverage.cxx b/Source/CTest/cmParseCacheCoverage.cxx
index 0916da2..23176b5 100644
--- a/Source/CTest/cmParseCacheCoverage.cxx
+++ b/Source/CTest/cmParseCacheCoverage.cxx
@@ -1,11 +1,15 @@
 #include "cmParseCacheCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
+
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
+#include <map>
 #include <stdio.h>
 #include <stdlib.h>
+#include <utility>
 
 cmParseCacheCoverage::cmParseCacheCoverage(
   cmCTestCoverageHandlerContainer& cont, cmCTest* ctest)
diff --git a/Source/CTest/cmParseCacheCoverage.h b/Source/CTest/cmParseCacheCoverage.h
index bd331d0..645d710 100644
--- a/Source/CTest/cmParseCacheCoverage.h
+++ b/Source/CTest/cmParseCacheCoverage.h
@@ -1,20 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseCacheCoverage_h
 #define cmParseCacheCoverage_h
 
+#include <cmConfigure.h>
+
 #include "cmParseMumpsCoverage.h"
 
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
+
 /** \class cmParseCacheCoverage
  * \brief Parse Cache coverage information
  *
@@ -28,7 +26,7 @@ public:
 
 protected:
   // implement virtual from parent
-  bool LoadCoverageData(const char* dir);
+  bool LoadCoverageData(const char* dir) CM_OVERRIDE;
   // remove files with no coverage
   void RemoveUnCoveredFiles();
   // Read a single mcov file
diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx
index 3bdae17..0b6d3ce 100644
--- a/Source/CTest/cmParseCoberturaCoverage.cxx
+++ b/Source/CTest/cmParseCoberturaCoverage.cxx
@@ -1,9 +1,14 @@
 #include "cmParseCoberturaCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
 #include "cmXMLParser.h"
-#include <cmsys/Directory.hxx>
+
+#include <cmConfigure.h>
 #include <cmsys/FStream.hxx>
+#include <stdlib.h>
+#include <string.h>
 
 class cmParseCoberturaCoverage::XMLParser : public cmXMLParser
 {
@@ -20,10 +25,10 @@ public:
     this->CurFileName = "";
   }
 
-  virtual ~XMLParser() {}
+  ~XMLParser() CM_OVERRIDE {}
 
 protected:
-  virtual void EndElement(const std::string& name)
+  void EndElement(const std::string& name) CM_OVERRIDE
   {
     if (name == "source") {
       this->InSource = false;
@@ -34,7 +39,7 @@ protected:
     }
   }
 
-  virtual void CharacterDataHandler(const char* data, int length)
+  void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
   {
     std::string tmp;
     tmp.insert(0, data, length);
@@ -46,7 +51,7 @@ protected:
     }
   }
 
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     std::string FoundSource;
     std::string finalpath = "";
diff --git a/Source/CTest/cmParseCoberturaCoverage.h b/Source/CTest/cmParseCoberturaCoverage.h
index 4fa6d10..077eb80 100644
--- a/Source/CTest/cmParseCoberturaCoverage.h
+++ b/Source/CTest/cmParseCoberturaCoverage.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseCoberturaCoverage_h
 #define cmParseCoberturaCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParsePythonCoverage
  * \brief Parse coverage.py Python coverage information
@@ -40,6 +36,7 @@ public:
 
 private:
   class XMLParser;
+
   cmCTestCoverageHandlerContainer& Coverage;
   cmCTest* CTest;
   std::string CurFileName;
diff --git a/Source/CTest/cmParseDelphiCoverage.cxx b/Source/CTest/cmParseDelphiCoverage.cxx
index 9d86ce9..7fe91f4 100644
--- a/Source/CTest/cmParseDelphiCoverage.cxx
+++ b/Source/CTest/cmParseDelphiCoverage.cxx
@@ -1,8 +1,9 @@
 #include "cmParseDelphiCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
-#include "cmXMLParser.h"
-#include <cmsys/Directory.hxx>
+
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
 #include <stdio.h>
diff --git a/Source/CTest/cmParseDelphiCoverage.h b/Source/CTest/cmParseDelphiCoverage.h
index c1c495c..278fbeb 100644
--- a/Source/CTest/cmParseDelphiCoverage.h
+++ b/Source/CTest/cmParseDelphiCoverage.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseDelphiCoverage_h
 #define cmParseDelphiCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParseDelphiCoverage
  * \brief Parse Delphi coverage information
@@ -35,6 +31,7 @@ public:
 
 protected:
   class HTMLParser;
+
   cmCTestCoverageHandlerContainer& Coverage;
   cmCTest* CTest;
 };
diff --git a/Source/CTest/cmParseGTMCoverage.cxx b/Source/CTest/cmParseGTMCoverage.cxx
index 33ad839..214ce5a 100644
--- a/Source/CTest/cmParseGTMCoverage.cxx
+++ b/Source/CTest/cmParseGTMCoverage.cxx
@@ -1,11 +1,15 @@
 #include "cmParseGTMCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
+
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
+#include <map>
 #include <stdio.h>
 #include <stdlib.h>
+#include <vector>
 
 cmParseGTMCoverage::cmParseGTMCoverage(cmCTestCoverageHandlerContainer& cont,
                                        cmCTest* ctest)
diff --git a/Source/CTest/cmParseGTMCoverage.h b/Source/CTest/cmParseGTMCoverage.h
index bc2f2ec..34721ff 100644
--- a/Source/CTest/cmParseGTMCoverage.h
+++ b/Source/CTest/cmParseGTMCoverage.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseGTMCoverage_h
 #define cmParseGTMCoverage_h
 
+#include <cmConfigure.h>
+
 #include "cmParseMumpsCoverage.h"
 
+#include <string>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
+
 /** \class cmParseGTMCoverage
  * \brief Parse GTM coverage information
  *
@@ -28,7 +25,7 @@ public:
 
 protected:
   // implement virtual from parent
-  bool LoadCoverageData(const char* dir);
+  bool LoadCoverageData(const char* dir) CM_OVERRIDE;
   // Read a single mcov file
   bool ReadMCovFile(const char* f);
   // find out what line in a mumps file (filepath) the given entry point
diff --git a/Source/CTest/cmParseJacocoCoverage.cxx b/Source/CTest/cmParseJacocoCoverage.cxx
index 335535d..0e36c01 100644
--- a/Source/CTest/cmParseJacocoCoverage.cxx
+++ b/Source/CTest/cmParseJacocoCoverage.cxx
@@ -1,12 +1,17 @@
 #include "cmParseJacocoCoverage.h"
 
+#include <cmConfigure.h>
+
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
 #include "cmXMLParser.h"
+
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 
 class cmParseJacocoCoverage::XMLParser : public cmXMLParser
 {
@@ -20,12 +25,12 @@ public:
     this->PackageName = "";
   }
 
-  virtual ~XMLParser() {}
+  ~XMLParser() CM_OVERRIDE {}
 
 protected:
-  virtual void EndElement(const std::string&) {}
+  void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
 
-  virtual void StartElement(const std::string& name, const char** atts)
+  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     if (name == "package") {
       this->PackageName = atts[1];
@@ -111,7 +116,7 @@ protected:
     gl.RecurseThroughSymlinksOn();
     gl.FindFiles(packageGlob);
     std::vector<std::string> const& files = gl.GetFiles();
-    if (files.size() == 0) {
+    if (files.empty()) {
       return false;
     }
 
diff --git a/Source/CTest/cmParseJacocoCoverage.h b/Source/CTest/cmParseJacocoCoverage.h
index bcd472e..04f1949 100644
--- a/Source/CTest/cmParseJacocoCoverage.h
+++ b/Source/CTest/cmParseJacocoCoverage.h
@@ -1,19 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseJacocoCoverage_h
 #define cmParseJacocoCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
+#include <vector>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParseJacocoCoverage
  * \brief Parse JaCoCO coverage information
@@ -47,6 +44,7 @@ private:
   bool LoadSource(std::string d);
 
   class XMLParser;
+
   std::map<std::string, std::string> RoutineToDirectory;
   cmCTestCoverageHandlerContainer& Coverage;
   cmCTest* CTest;
diff --git a/Source/CTest/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx
index e5dd74a..ab8be76 100644
--- a/Source/CTest/cmParseMumpsCoverage.cxx
+++ b/Source/CTest/cmParseMumpsCoverage.cxx
@@ -1,11 +1,16 @@
-#include "cmParseGTMCoverage.h"
+#include "cmParseMumpsCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
-#include <cmsys/Directory.hxx>
+
+#include <cmConfigure.h>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-#include <stdio.h>
-#include <stdlib.h>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
 
 cmParseMumpsCoverage::cmParseMumpsCoverage(
   cmCTestCoverageHandlerContainer& cont, cmCTest* ctest)
@@ -128,16 +133,15 @@ bool cmParseMumpsCoverage::FindMumpsFile(std::string const& routine,
   if (i != this->RoutineToDirectory.end()) {
     filepath = i->second;
     return true;
-  } else {
-    // try some alternate names
-    const char* tryname[] = { "GUX", "GTM", "ONT", 0 };
-    for (int k = 0; tryname[k] != 0; k++) {
-      std::string routine2 = routine + tryname[k];
-      i = this->RoutineToDirectory.find(routine2);
-      if (i != this->RoutineToDirectory.end()) {
-        filepath = i->second;
-        return true;
-      }
+  }
+  // try some alternate names
+  const char* tryname[] = { "GUX", "GTM", "ONT", CM_NULLPTR };
+  for (int k = 0; tryname[k] != CM_NULLPTR; k++) {
+    std::string routine2 = routine + tryname[k];
+    i = this->RoutineToDirectory.find(routine2);
+    if (i != this->RoutineToDirectory.end()) {
+      filepath = i->second;
+      return true;
     }
   }
   return false;
diff --git a/Source/CTest/cmParseMumpsCoverage.h b/Source/CTest/cmParseMumpsCoverage.h
index 3761ba6..c4ed175 100644
--- a/Source/CTest/cmParseMumpsCoverage.h
+++ b/Source/CTest/cmParseMumpsCoverage.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseMumpsCoverage_h
 #define cmParseMumpsCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParseMumpsCoverage
  * \brief Parse Mumps coverage information
diff --git a/Source/CTest/cmParsePHPCoverage.cxx b/Source/CTest/cmParsePHPCoverage.cxx
index eb0d962..d8bb31b 100644
--- a/Source/CTest/cmParsePHPCoverage.cxx
+++ b/Source/CTest/cmParsePHPCoverage.cxx
@@ -1,8 +1,13 @@
 #include "cmParsePHPCoverage.h"
 
+#include "cmCTest.h"
+#include "cmCTestCoverageHandler.h"
 #include "cmSystemTools.h"
+
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
+#include <stdlib.h>
+#include <string.h>
 
 /*
   To setup coverage for php.
@@ -27,10 +32,7 @@ bool cmParsePHPCoverage::ReadUntil(std::istream& in, char until)
   char c = 0;
   while (in.get(c) && c != until) {
   }
-  if (c != until) {
-    return false;
-  }
-  return true;
+  return c == until;
 }
 bool cmParsePHPCoverage::ReadCoverageArray(std::istream& in,
                                            std::string const& fileName)
diff --git a/Source/CTest/cmParsePHPCoverage.h b/Source/CTest/cmParsePHPCoverage.h
index 72f9129..4bcad6d 100644
--- a/Source/CTest/cmParsePHPCoverage.h
+++ b/Source/CTest/cmParsePHPCoverage.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParsePHPCoverage_h
 #define cmParsePHPCoverage_h
 
-#include "cmCTestCoverageHandler.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
+#include <string>
+
+class cmCTest;
+class cmCTestCoverageHandlerContainer;
 
 /** \class cmParsePHPCoverage
  * \brief Parse xdebug PHP coverage information
diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx
index db5151c..cf3c7ac 100644
--- a/Source/CTest/cmProcess.cxx
+++ b/Source/CTest/cmProcess.cxx
@@ -1,22 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
-#include <cmProcess.h>
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmProcess.h"
 
+#include <cmConfigure.h>
 #include <cmSystemTools.h>
+#include <iostream>
 
 cmProcess::cmProcess()
 {
-  this->Process = 0;
+  this->Process = CM_NULLPTR;
   this->Timeout = 0;
   this->TotalTime = 0;
   this->ExitValue = 0;
@@ -52,7 +44,7 @@ bool cmProcess::StartProcess()
        i != this->Arguments.end(); ++i) {
     this->ProcessArgs.push_back(i->c_str());
   }
-  this->ProcessArgs.push_back(0); // null terminate the list
+  this->ProcessArgs.push_back(CM_NULLPTR); // null terminate the list
   this->Process = cmsysProcess_New();
   cmsysProcess_SetCommand(this->Process, &*this->ProcessArgs.begin());
   if (!this->WorkingDirectory.empty()) {
@@ -124,10 +116,10 @@ int cmProcess::GetNextOutputLine(std::string& line, double timeout)
     int p = cmsysProcess_WaitForData(this->Process, &data, &length, &timeout);
     if (p == cmsysProcess_Pipe_Timeout) {
       return cmsysProcess_Pipe_Timeout;
-    } else if (p == cmsysProcess_Pipe_STDOUT) {
+    }
+    if (p == cmsysProcess_Pipe_STDOUT) {
       this->Output.insert(this->Output.end(), data, data + length);
-    } else // p == cmsysProcess_Pipe_None
-    {
+    } else { // p == cmsysProcess_Pipe_None
       // The process will provide no more data.
       break;
     }
diff --git a/Source/CTest/cmProcess.h b/Source/CTest/cmProcess.h
index d5e2721..9d201d1 100644
--- a/Source/CTest/cmProcess.h
+++ b/Source/CTest/cmProcess.h
@@ -1,20 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmProcess_h
 #define cmProcess_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/Process.h>
+#include <string>
+#include <vector>
 
 /** \class cmProcess
  * \brief run a process with c++
diff --git a/Source/Checks/cm_cxx11_unordered_map.cmake b/Source/Checks/cm_cxx11_unordered_map.cmake
deleted file mode 100644
index 80fe391..0000000
--- a/Source/Checks/cm_cxx11_unordered_map.cmake
+++ /dev/null
@@ -1,25 +0,0 @@
-
-if(CMAKE_CXX_STANDARD AND NOT DEFINED CMake_HAVE_CXX11_UNORDERED_MAP)
-  message(STATUS "Checking if compiler supports C++11 unordered_map")
-  try_compile(CMake_HAVE_CXX11_UNORDERED_MAP
-    ${CMAKE_CURRENT_BINARY_DIR}
-    ${CMAKE_CURRENT_LIST_DIR}/cm_cxx11_unordered_map.cpp
-    CMAKE_FLAGS -DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}
-    OUTPUT_VARIABLE OUTPUT
-    )
-  if(CMake_HAVE_CXX11_UNORDERED_MAP)
-    message(STATUS "Checking if compiler supports C++11 unordered_map - yes")
-    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
-      "Determining if compiler supports C++11 unordered_map passed with the following output:\n"
-      "${OUTPUT}\n"
-      "\n"
-      )
-  else()
-    message(STATUS "Checking if compiler supports C++11 unordered_map - no")
-    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
-      "Determining if compiler supports C++11 unordered_map failed with the following output:\n"
-      "${OUTPUT}\n"
-      "\n"
-      )
-  endif()
-endif()
diff --git a/Source/Checks/cm_cxx_auto_ptr.cxx b/Source/Checks/cm_cxx_auto_ptr.cxx
new file mode 100644
index 0000000..d3100fd
--- /dev/null
+++ b/Source/Checks/cm_cxx_auto_ptr.cxx
@@ -0,0 +1,18 @@
+#include <memory>
+
+std::auto_ptr<int> get_auto_ptr()
+{
+  std::auto_ptr<int> ptr;
+  ptr = std::auto_ptr<int>(new int(0));
+  return ptr;
+}
+
+int use_auto_ptr(std::auto_ptr<int> ptr)
+{
+  return *ptr;
+}
+
+int main()
+{
+  return use_auto_ptr(get_auto_ptr());
+}
diff --git a/Source/Checks/cm_cxx_features.cmake b/Source/Checks/cm_cxx_features.cmake
new file mode 100644
index 0000000..80c9f3b
--- /dev/null
+++ b/Source/Checks/cm_cxx_features.cmake
@@ -0,0 +1,45 @@
+
+function(cm_check_cxx_feature name)
+  string(TOUPPER ${name} FEATURE)
+  if(NOT DEFINED CMake_HAVE_CXX_${FEATURE})
+    message(STATUS "Checking if compiler supports C++ ${name}")
+    try_compile(CMake_HAVE_CXX_${FEATURE}
+      ${CMAKE_CURRENT_BINARY_DIR}
+      ${CMAKE_CURRENT_LIST_DIR}/cm_cxx_${name}.cxx
+      CMAKE_FLAGS -DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}
+      OUTPUT_VARIABLE OUTPUT
+      )
+    # If using the feature causes warnings, treat it as broken/unavailable.
+    if(OUTPUT MATCHES "warning")
+      set(CMake_HAVE_CXX_${FEATURE} OFF CACHE INTERNAL "TRY_COMPILE" FORCE)
+    endif()
+    if(CMake_HAVE_CXX_${FEATURE})
+      message(STATUS "Checking if compiler supports C++ ${name} - yes")
+      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+        "Determining if compiler supports C++ ${name} passed with the following output:\n"
+        "${OUTPUT}\n"
+        "\n"
+        )
+    else()
+      message(STATUS "Checking if compiler supports C++ ${name} - no")
+      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+        "Determining if compiler supports C++ ${name} failed with the following output:\n"
+        "${OUTPUT}\n"
+        "\n"
+        )
+    endif()
+  endif()
+endfunction()
+
+if(CMAKE_CXX_STANDARD)
+  cm_check_cxx_feature(auto_ptr)
+  cm_check_cxx_feature(make_unique)
+  if(CMake_HAVE_CXX_MAKE_UNIQUE)
+    set(CMake_HAVE_CXX_UNIQUE_PTR 1)
+  endif()
+  cm_check_cxx_feature(nullptr)
+  cm_check_cxx_feature(override)
+  cm_check_cxx_feature(unique_ptr)
+  cm_check_cxx_feature(unordered_map)
+  cm_check_cxx_feature(unordered_set)
+endif()
diff --git a/Source/Checks/cm_cxx_make_unique.cxx b/Source/Checks/cm_cxx_make_unique.cxx
new file mode 100644
index 0000000..a3ff68f
--- /dev/null
+++ b/Source/Checks/cm_cxx_make_unique.cxx
@@ -0,0 +1,6 @@
+#include <memory>
+int main()
+{
+  std::unique_ptr<int> u = std::make_unique<int>(0);
+  return *u;
+}
diff --git a/Source/Checks/cm_cxx_nullptr.cxx b/Source/Checks/cm_cxx_nullptr.cxx
new file mode 100644
index 0000000..500684a
--- /dev/null
+++ b/Source/Checks/cm_cxx_nullptr.cxx
@@ -0,0 +1,14 @@
+int test(int)
+{
+  return -1;
+}
+
+int test(int*)
+{
+  return 0;
+}
+
+int main()
+{
+  return test(nullptr);
+}
diff --git a/Source/Checks/cm_cxx_override.cxx b/Source/Checks/cm_cxx_override.cxx
new file mode 100644
index 0000000..5a33fbb
--- /dev/null
+++ b/Source/Checks/cm_cxx_override.cxx
@@ -0,0 +1,24 @@
+struct Foo
+{
+  Foo() {}
+  virtual ~Foo() {}
+  virtual int test() const = 0;
+};
+
+struct Bar : Foo
+{
+  Bar() {}
+  ~Bar() override {}
+  int test() const override { return 0; }
+};
+
+int test(Foo const& foo)
+{
+  return foo.test();
+}
+
+int main()
+{
+  Bar const bar;
+  return test(bar);
+}
diff --git a/Source/Checks/cm_cxx_unique_ptr.cxx b/Source/Checks/cm_cxx_unique_ptr.cxx
new file mode 100644
index 0000000..a9d4ce5
--- /dev/null
+++ b/Source/Checks/cm_cxx_unique_ptr.cxx
@@ -0,0 +1,6 @@
+#include <memory>
+int main()
+{
+  std::unique_ptr<int> u(new int(0));
+  return *u;
+}
diff --git a/Source/Checks/cm_cxx11_unordered_map.cpp b/Source/Checks/cm_cxx_unordered_map.cxx
similarity index 100%
rename from Source/Checks/cm_cxx11_unordered_map.cpp
rename to Source/Checks/cm_cxx_unordered_map.cxx
diff --git a/Source/Checks/cm_cxx_unordered_set.cxx b/Source/Checks/cm_cxx_unordered_set.cxx
new file mode 100644
index 0000000..de4bb77
--- /dev/null
+++ b/Source/Checks/cm_cxx_unordered_set.cxx
@@ -0,0 +1,7 @@
+#include <unordered_set>
+int main()
+{
+  std::unordered_set<int> set;
+  set.insert(0);
+  return 0;
+}
diff --git a/Source/CursesDialog/CMakeLists.txt b/Source/CursesDialog/CMakeLists.txt
index 93ff425..c5ac1f1 100644
--- a/Source/CursesDialog/CMakeLists.txt
+++ b/Source/CursesDialog/CMakeLists.txt
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 set( CURSES_SRCS
               CursesDialog/cmCursesOptionsWidget
@@ -48,4 +39,4 @@ else()
 endif()
 
 CMake_OPTIONAL_COMPONENT(ccmake)
-install(TARGETS ccmake DESTINATION bin ${COMPONENT})
+install(TARGETS ccmake DESTINATION ${CMAKE_BIN_DIR} ${COMPONENT})
diff --git a/Source/CursesDialog/ccmake.cxx b/Source/CursesDialog/ccmake.cxx
index be8751c..919be4d 100644
--- a/Source/CursesDialog/ccmake.cxx
+++ b/Source/CursesDialog/ccmake.cxx
@@ -1,56 +1,51 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include <cmConfigure.h>
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+#include "cmCursesForm.h"
+#include "cmCursesMainForm.h"
 #include "cmCursesStandardIncludes.h"
+#include "cmDocumentation.h"
+#include "cmDocumentationEntry.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
 
-#include "../cmDocumentation.h"
-#include "../cmSystemTools.h"
-#include "../cmake.h"
-
-#include <signal.h>
-#include <sys/ioctl.h>
-
-#include "cmCursesMainForm.h"
 #include <cmsys/Encoding.hxx>
-
-#include <form.h>
+#include <iostream>
+#include <signal.h>
+#include <string.h>
+#include <string>
+#include <vector>
 
 static const char* cmDocumentationName[][2] = {
-  { 0, "  ccmake - Curses Interface for CMake." },
-  { 0, 0 }
+  { CM_NULLPTR, "  ccmake - Curses Interface for CMake." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationUsage[][2] = {
-  { 0, "  ccmake <path-to-source>\n"
-       "  ccmake <path-to-existing-build>" },
-  { 0, "Specify a source directory to (re-)generate a build system for "
-       "it in the current working directory.  Specify an existing build "
-       "directory to re-generate its build system." },
-  { 0, 0 }
+  { CM_NULLPTR, "  ccmake <path-to-source>\n"
+                "  ccmake <path-to-existing-build>" },
+  { CM_NULLPTR,
+    "Specify a source directory to (re-)generate a build system for "
+    "it in the current working directory.  Specify an existing build "
+    "directory to re-generate its build system." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationUsageNote[][2] = {
-  { 0, "Run 'ccmake --help' for more information." },
-  { 0, 0 }
+  { CM_NULLPTR, "Run 'ccmake --help' for more information." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationOptions[]
                                          [2] = { CMAKE_STANDARD_OPTIONS_TABLE,
-                                                 { 0, 0 } };
+                                                 { CM_NULLPTR, CM_NULLPTR } };
 
-cmCursesForm* cmCursesForm::CurrentForm = 0;
+cmCursesForm* cmCursesForm::CurrentForm = CM_NULLPTR;
 
 extern "C" {
 
-void onsig(int)
+void onsig(int /*unused*/)
 {
   if (cmCursesForm::CurrentForm) {
     endwin();
@@ -69,8 +64,8 @@ void onsig(int)
 }
 }
 
-void CMakeMessageHandler(const char* message, const char* title, bool&,
-                         void* clientData)
+void CMakeMessageHandler(const char* message, const char* title,
+                         bool& /*unused*/, void* clientData)
 {
   cmCursesForm* self = static_cast<cmCursesForm*>(clientData);
   self->AddError(message, title);
@@ -176,7 +171,7 @@ int main(int argc, char const* const* argv)
   touchwin(stdscr);
   endwin();
   delete cmCursesForm::CurrentForm;
-  cmCursesForm::CurrentForm = 0;
+  cmCursesForm::CurrentForm = CM_NULLPTR;
 
   std::cout << std::endl << std::endl;
 
diff --git a/Source/CursesDialog/cmCursesBoolWidget.cxx b/Source/CursesDialog/cmCursesBoolWidget.cxx
index 0055e88..5268a5d 100644
--- a/Source/CursesDialog/cmCursesBoolWidget.cxx
+++ b/Source/CursesDialog/cmCursesBoolWidget.cxx
@@ -1,17 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesBoolWidget.h"
 
-#include "cmCursesMainForm.h"
+#include "cmCursesWidget.h"
+#include "cmState.h"
+
+#include <string>
 
 cmCursesBoolWidget::cmCursesBoolWidget(int width, int height, int left,
                                        int top)
@@ -24,11 +18,13 @@ cmCursesBoolWidget::cmCursesBoolWidget(int width, int height, int left,
   this->SetValueAsBool(false);
 }
 
-bool cmCursesBoolWidget::HandleInput(int& key, cmCursesMainForm*, WINDOW* w)
+bool cmCursesBoolWidget::HandleInput(int& key, cmCursesMainForm* /*fm*/,
+                                     WINDOW* w)
 {
 
+  // toggle boolean values with enter or space
   // 10 == enter
-  if (key == 10 || key == KEY_ENTER) {
+  if (key == 10 || key == KEY_ENTER || key == ' ') {
     if (this->GetValueAsBool()) {
       this->SetValueAsBool(false);
     } else {
@@ -38,9 +34,8 @@ bool cmCursesBoolWidget::HandleInput(int& key, cmCursesMainForm*, WINDOW* w)
     touchwin(w);
     wrefresh(w);
     return true;
-  } else {
-    return false;
   }
+  return false;
 }
 
 void cmCursesBoolWidget::SetValueAsBool(bool value)
@@ -54,9 +49,5 @@ void cmCursesBoolWidget::SetValueAsBool(bool value)
 
 bool cmCursesBoolWidget::GetValueAsBool()
 {
-  if (this->Value == "ON") {
-    return true;
-  } else {
-    return false;
-  }
+  return this->Value == "ON";
 }
diff --git a/Source/CursesDialog/cmCursesBoolWidget.h b/Source/CursesDialog/cmCursesBoolWidget.h
index 49be45a..f79f7e8 100644
--- a/Source/CursesDialog/cmCursesBoolWidget.h
+++ b/Source/CursesDialog/cmCursesBoolWidget.h
@@ -1,17 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesBoolWidget_h
 #define cmCursesBoolWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
 
 class cmCursesMainForm;
@@ -25,7 +19,7 @@ public:
   // Handle user input. Called by the container of this widget
   // when this widget has focus. Returns true if the input was
   // handled.
-  virtual bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w);
+  bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
 
   // Description:
   // Set/Get the value (on/off).
diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
index bdfc8e9..93785e0 100644
--- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
+++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
@@ -1,28 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesCacheEntryComposite.h"
 
-#include "../cmState.h"
-#include "../cmSystemTools.h"
-#include "../cmake.h"
 #include "cmCursesBoolWidget.h"
-#include "cmCursesDummyWidget.h"
 #include "cmCursesFilePathWidget.h"
 #include "cmCursesLabelWidget.h"
 #include "cmCursesOptionsWidget.h"
 #include "cmCursesPathWidget.h"
 #include "cmCursesStringWidget.h"
+#include "cmCursesWidget.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
 
 #include <assert.h>
+#include <cmConfigure.h>
+#include <vector>
 
 cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
   const std::string& key, int labelwidth, int entrywidth)
@@ -32,7 +25,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
 {
   this->Label = new cmCursesLabelWidget(this->LabelWidth, 1, 1, 1, key);
   this->IsNewLabel = new cmCursesLabelWidget(1, 1, 1, 1, " ");
-  this->Entry = 0;
+  this->Entry = CM_NULLPTR;
   this->Entry = new cmCursesStringWidget(this->EntryWidth, 1, 1, 1);
 }
 
@@ -50,7 +43,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
     this->IsNewLabel = new cmCursesLabelWidget(1, 1, 1, 1, " ");
   }
 
-  this->Entry = 0;
+  this->Entry = CM_NULLPTR;
   const char* value = cm->GetState()->GetCacheEntryValue(key);
   assert(value);
   switch (cm->GetState()->GetCacheEntryType(key)) {
@@ -110,7 +103,6 @@ const char* cmCursesCacheEntryComposite::GetValue()
 {
   if (this->Label) {
     return this->Label->GetValue();
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.h b/Source/CursesDialog/cmCursesCacheEntryComposite.h
index 8ed3902..59a1fd7 100644
--- a/Source/CursesDialog/cmCursesCacheEntryComposite.h
+++ b/Source/CursesDialog/cmCursesCacheEntryComposite.h
@@ -1,18 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesCacheEntryComposite_h
 #define cmCursesCacheEntryComposite_h
 
-#include "cmCursesLabelWidget.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+
+class cmCursesLabelWidget;
+class cmCursesWidget;
+class cmake;
 
 class cmCursesCacheEntryComposite
 {
diff --git a/Source/CursesDialog/cmCursesDummyWidget.cxx b/Source/CursesDialog/cmCursesDummyWidget.cxx
index 3cd36af..61d07e2 100644
--- a/Source/CursesDialog/cmCursesDummyWidget.cxx
+++ b/Source/CursesDialog/cmCursesDummyWidget.cxx
@@ -1,16 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesDummyWidget.h"
 
+#include "cmCursesWidget.h"
+#include "cmState.h"
+
 cmCursesDummyWidget::cmCursesDummyWidget(int width, int height, int left,
                                          int top)
   : cmCursesWidget(width, height, left, top)
@@ -18,7 +12,8 @@ cmCursesDummyWidget::cmCursesDummyWidget(int width, int height, int left,
   this->Type = cmState::INTERNAL;
 }
 
-bool cmCursesDummyWidget::HandleInput(int&, cmCursesMainForm*, WINDOW*)
+bool cmCursesDummyWidget::HandleInput(int& /*key*/, cmCursesMainForm* /*fm*/,
+                                      WINDOW* /*w*/)
 {
   return false;
 }
diff --git a/Source/CursesDialog/cmCursesDummyWidget.h b/Source/CursesDialog/cmCursesDummyWidget.h
index 9a3df29..fe43de5 100644
--- a/Source/CursesDialog/cmCursesDummyWidget.h
+++ b/Source/CursesDialog/cmCursesDummyWidget.h
@@ -1,17 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesDummyWidget_h
 #define cmCursesDummyWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
 
 class cmCursesMainForm;
@@ -25,7 +19,7 @@ public:
   // Handle user input. Called by the container of this widget
   // when this widget has focus. Returns true if the input was
   // handled.
-  virtual bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w);
+  bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
 
 protected:
   cmCursesDummyWidget(const cmCursesDummyWidget& from);
diff --git a/Source/CursesDialog/cmCursesFilePathWidget.cxx b/Source/CursesDialog/cmCursesFilePathWidget.cxx
index 28a74a9..670c50f 100644
--- a/Source/CursesDialog/cmCursesFilePathWidget.cxx
+++ b/Source/CursesDialog/cmCursesFilePathWidget.cxx
@@ -1,16 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesFilePathWidget.h"
 
+#include "cmCursesPathWidget.h"
+#include "cmState.h"
+
 cmCursesFilePathWidget::cmCursesFilePathWidget(int width, int height, int left,
                                                int top)
   : cmCursesPathWidget(width, height, left, top)
diff --git a/Source/CursesDialog/cmCursesFilePathWidget.h b/Source/CursesDialog/cmCursesFilePathWidget.h
index 72adc77..7df7f00 100644
--- a/Source/CursesDialog/cmCursesFilePathWidget.h
+++ b/Source/CursesDialog/cmCursesFilePathWidget.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesFilePathWidget_h
 #define cmCursesFilePathWidget_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmCursesPathWidget.h"
 
 class cmCursesFilePathWidget : public cmCursesPathWidget
diff --git a/Source/CursesDialog/cmCursesForm.cxx b/Source/CursesDialog/cmCursesForm.cxx
index aa4710f..0eb16cb 100644
--- a/Source/CursesDialog/cmCursesForm.cxx
+++ b/Source/CursesDialog/cmCursesForm.cxx
@@ -1,22 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesForm.h"
 
+#include <cmConfigure.h>
+
 cmsys::ofstream cmCursesForm::DebugFile;
 bool cmCursesForm::Debug = false;
 
 cmCursesForm::cmCursesForm()
 {
-  this->Form = 0;
+  this->Form = CM_NULLPTR;
 }
 
 cmCursesForm::~cmCursesForm()
@@ -24,7 +17,7 @@ cmCursesForm::~cmCursesForm()
   if (this->Form) {
     unpost_form(this->Form);
     free_form(this->Form);
-    this->Form = 0;
+    this->Form = CM_NULLPTR;
   }
 }
 
diff --git a/Source/CursesDialog/cmCursesForm.h b/Source/CursesDialog/cmCursesForm.h
index c0192fc..85a80c2 100644
--- a/Source/CursesDialog/cmCursesForm.h
+++ b/Source/CursesDialog/cmCursesForm.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesForm_h
 #define cmCursesForm_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmCursesStandardIncludes.h"
 
 #include <cmsys/FStream.hxx>
diff --git a/Source/CursesDialog/cmCursesLabelWidget.cxx b/Source/CursesDialog/cmCursesLabelWidget.cxx
index e9da71e..1dfd4ce 100644
--- a/Source/CursesDialog/cmCursesLabelWidget.cxx
+++ b/Source/CursesDialog/cmCursesLabelWidget.cxx
@@ -1,16 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesLabelWidget.h"
 
+#include "cmCursesWidget.h"
+
 cmCursesLabelWidget::cmCursesLabelWidget(int width, int height, int left,
                                          int top, const std::string& name)
   : cmCursesWidget(width, height, left, top)
@@ -25,7 +18,8 @@ cmCursesLabelWidget::~cmCursesLabelWidget()
 {
 }
 
-bool cmCursesLabelWidget::HandleInput(int&, cmCursesMainForm*, WINDOW*)
+bool cmCursesLabelWidget::HandleInput(int& /*key*/, cmCursesMainForm* /*fm*/,
+                                      WINDOW* /*w*/)
 {
   // Static text. No input is handled here.
   return false;
diff --git a/Source/CursesDialog/cmCursesLabelWidget.h b/Source/CursesDialog/cmCursesLabelWidget.h
index c31a58c..4d63f48 100644
--- a/Source/CursesDialog/cmCursesLabelWidget.h
+++ b/Source/CursesDialog/cmCursesLabelWidget.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesLabelWidget_h
 #define cmCursesLabelWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
 
+#include <string>
+
 class cmCursesMainForm;
 
 class cmCursesLabelWidget : public cmCursesWidget
@@ -21,13 +17,13 @@ class cmCursesLabelWidget : public cmCursesWidget
 public:
   cmCursesLabelWidget(int width, int height, int left, int top,
                       const std::string& name);
-  virtual ~cmCursesLabelWidget();
+  ~cmCursesLabelWidget() CM_OVERRIDE;
 
   // Description:
   // Handle user input. Called by the container of this widget
   // when this widget has focus. Returns true if the input was
   // handled
-  virtual bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w);
+  bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
 
 protected:
   cmCursesLabelWidget(const cmCursesLabelWidget& from);
diff --git a/Source/CursesDialog/cmCursesLongMessageForm.cxx b/Source/CursesDialog/cmCursesLongMessageForm.cxx
index 84672ae..d299547 100644
--- a/Source/CursesDialog/cmCursesLongMessageForm.cxx
+++ b/Source/CursesDialog/cmCursesLongMessageForm.cxx
@@ -1,20 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesLongMessageForm.h"
 
-#include "../cmSystemTools.h"
-#include "../cmVersion.h"
-#include "../cmake.h"
+#include "cmCursesForm.h"
 #include "cmCursesMainForm.h"
+#include "cmCursesStandardIncludes.h"
+#include "cmVersion.h"
+
+#include <stdio.h>
+#include <string.h>
 
 inline int ctrl(int z)
 {
@@ -32,8 +26,8 @@ cmCursesLongMessageForm::cmCursesLongMessageForm(
     this->Messages += "\n\n";
   }
   this->Title = title;
-  this->Fields[0] = 0;
-  this->Fields[1] = 0;
+  this->Fields[0] = CM_NULLPTR;
+  this->Fields[1] = CM_NULLPTR;
 }
 
 cmCursesLongMessageForm::~cmCursesLongMessageForm()
@@ -54,9 +48,9 @@ void cmCursesLongMessageForm::UpdateStatusBar()
     size = cmCursesMainForm::MAX_WIDTH - 1;
   }
   strncpy(bar, this->Title.c_str(), size);
-  for (size_t i = size - 1; i < cmCursesMainForm::MAX_WIDTH; i++)
+  for (size_t i = size - 1; i < cmCursesMainForm::MAX_WIDTH; i++) {
     bar[i] = ' ';
-
+  }
   int width;
   if (x < cmCursesMainForm::MAX_WIDTH) {
     width = x;
@@ -102,7 +96,8 @@ void cmCursesLongMessageForm::PrintKeys()
   pos_form_cursor(this->Form);
 }
 
-void cmCursesLongMessageForm::Render(int, int, int, int)
+void cmCursesLongMessageForm::Render(int /*left*/, int /*top*/, int /*width*/,
+                                     int /*height*/)
 {
   int x, y;
   getmaxyx(stdscr, y, x);
@@ -110,7 +105,7 @@ void cmCursesLongMessageForm::Render(int, int, int, int)
   if (this->Form) {
     unpost_form(this->Form);
     free_form(this->Form);
-    this->Form = 0;
+    this->Form = CM_NULLPTR;
   }
 
   const char* msg = this->Messages.c_str();
@@ -119,7 +114,7 @@ void cmCursesLongMessageForm::Render(int, int, int, int)
 
   if (this->Fields[0]) {
     free_field(this->Fields[0]);
-    this->Fields[0] = 0;
+    this->Fields[0] = CM_NULLPTR;
   }
 
   this->Fields[0] = new_field(y - 6, x - 2, 1, 1, 0, 0);
diff --git a/Source/CursesDialog/cmCursesLongMessageForm.h b/Source/CursesDialog/cmCursesLongMessageForm.h
index 73ccfc4..e9eae7c 100644
--- a/Source/CursesDialog/cmCursesLongMessageForm.h
+++ b/Source/CursesDialog/cmCursesLongMessageForm.h
@@ -1,38 +1,31 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesLongMessageForm_h
 #define cmCursesLongMessageForm_h
 
-#include "cmCursesStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include "cmCursesForm.h"
+#include "cmCursesStandardIncludes.h"
 
-class cmCursesCacheEntryComposite;
+#include <string>
+#include <vector>
 
 class cmCursesLongMessageForm : public cmCursesForm
 {
 public:
   cmCursesLongMessageForm(std::vector<std::string> const& messages,
                           const char* title);
-  virtual ~cmCursesLongMessageForm();
+  ~cmCursesLongMessageForm() CM_OVERRIDE;
 
   // Description:
   // Handle user input.
-  virtual void HandleInput();
+  void HandleInput() CM_OVERRIDE;
 
   // Description:
   // Display form. Use a window of size width x height, starting
   // at top, left.
-  virtual void Render(int left, int top, int width, int height);
+  void Render(int left, int top, int width, int height) CM_OVERRIDE;
 
   // Description:
   // This method should normally  called only by the form.
@@ -42,7 +35,7 @@ public:
   // Description:
   // This method should normally  called only by the form.
   // The only exception is during a resize.
-  virtual void UpdateStatusBar();
+  void UpdateStatusBar() CM_OVERRIDE;
 
 protected:
   cmCursesLongMessageForm(const cmCursesLongMessageForm& from);
diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx
index b740eb0..0c3d29d 100644
--- a/Source/CursesDialog/cmCursesMainForm.cxx
+++ b/Source/CursesDialog/cmCursesMainForm.cxx
@@ -1,29 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesMainForm.h"
 
-#include "../cmSystemTools.h"
-#include "../cmVersion.h"
-#include "../cmake.h"
 #include "cmAlgorithms.h"
-#include "cmCursesBoolWidget.h"
 #include "cmCursesCacheEntryComposite.h"
 #include "cmCursesDummyWidget.h"
-#include "cmCursesFilePathWidget.h"
+#include "cmCursesForm.h"
 #include "cmCursesLabelWidget.h"
 #include "cmCursesLongMessageForm.h"
-#include "cmCursesPathWidget.h"
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesStringWidget.h"
+#include "cmCursesWidget.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmVersion.h"
+#include "cmake.h"
+
+#include <stdio.h>
+#include <string.h>
 
 inline int ctrl(int z)
 {
@@ -36,8 +30,8 @@ cmCursesMainForm::cmCursesMainForm(std::vector<std::string> const& args,
   , InitialWidth(initWidth)
 {
   this->NumberOfPages = 0;
-  this->Fields = 0;
-  this->Entries = 0;
+  this->Fields = CM_NULLPTR;
+  this->Entries = CM_NULLPTR;
   this->AdvancedMode = false;
   this->NumberOfVisibleEntries = 0;
   this->OkToGenerate = false;
@@ -64,7 +58,7 @@ cmCursesMainForm::~cmCursesMainForm()
   if (this->Form) {
     unpost_form(this->Form);
     free_form(this->Form);
-    this->Form = 0;
+    this->Form = CM_NULLPTR;
   }
   delete[] this->Fields;
 
@@ -75,7 +69,7 @@ cmCursesMainForm::~cmCursesMainForm()
   delete this->Entries;
   if (this->CMakeInstance) {
     delete this->CMakeInstance;
-    this->CMakeInstance = 0;
+    this->CMakeInstance = CM_NULLPTR;
   }
 }
 
@@ -185,7 +179,7 @@ void cmCursesMainForm::RePost()
   if (this->Form) {
     unpost_form(this->Form);
     free_form(this->Form);
-    this->Form = 0;
+    this->Form = CM_NULLPTR;
   }
   delete[] this->Fields;
   if (this->AdvancedMode) {
@@ -215,7 +209,7 @@ void cmCursesMainForm::RePost()
   this->Fields = new FIELD*[3 * this->NumberOfVisibleEntries + 1];
   size_t cc;
   for (cc = 0; cc < 3 * this->NumberOfVisibleEntries + 1; cc++) {
-    this->Fields[cc] = 0;
+    this->Fields[cc] = CM_NULLPTR;
   }
 
   // Assign fields
@@ -244,7 +238,7 @@ void cmCursesMainForm::RePost()
     this->NumberOfVisibleEntries = 1;
   }
   // Has to be null terminated.
-  this->Fields[3 * this->NumberOfVisibleEntries] = 0;
+  this->Fields[3 * this->NumberOfVisibleEntries] = CM_NULLPTR;
 }
 
 void cmCursesMainForm::Render(int left, int top, int width, int height)
@@ -263,7 +257,7 @@ void cmCursesMainForm::Render(int left, int top, int width, int height)
     // Delete the previous form
     unpost_form(this->Form);
     free_form(this->Form);
-    this->Form = 0;
+    this->Form = CM_NULLPTR;
   }
 
   // Wrong window size
@@ -345,7 +339,7 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
   }
 
   // Give the current widget (if it exists), a chance to print keys
-  cmCursesWidget* cw = 0;
+  cmCursesWidget* cw = CM_NULLPTR;
   if (this->Form) {
     FIELD* currentField = current_field(this->Form);
     cw = reinterpret_cast<cmCursesWidget*>(field_userptr(currentField));
@@ -388,7 +382,7 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
 
   curses_move(y - 4, 0);
   char fmt_s[] = "%s";
-  char fmt[512] = "Press [enter] to edit option";
+  char fmt[512] = "Press [enter] to edit option Press [d] to delete an entry";
   if (process) {
     strcpy(fmt, "                           ");
   }
@@ -434,7 +428,7 @@ void cmCursesMainForm::UpdateStatusBar(const char* message)
   // Get the key of the current entry
   FIELD* cur = current_field(this->Form);
   int findex = field_index(cur);
-  cmCursesWidget* lbl = 0;
+  cmCursesWidget* lbl = CM_NULLPTR;
   if (findex >= 0) {
     lbl = reinterpret_cast<cmCursesWidget*>(
       field_userptr(this->Fields[findex - 2]));
@@ -566,7 +560,7 @@ int cmCursesMainForm::Configure(int noconfigure)
   this->FillCacheManagerFromUI();
   this->CMakeInstance->SaveCache(
     this->CMakeInstance->GetHomeOutputDirectory());
-  this->LoadCache(0);
+  this->LoadCache(CM_NULLPTR);
 
   // Get rid of previous errors
   this->Errors = std::vector<std::string>();
@@ -583,7 +577,7 @@ int cmCursesMainForm::Configure(int noconfigure)
   } else {
     retVal = this->CMakeInstance->Configure();
   }
-  this->CMakeInstance->SetProgressCallback(0, 0);
+  this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
 
   keypad(stdscr, TRUE); /* Use key symbols as
                            KEY_DOWN*/
@@ -638,7 +632,7 @@ int cmCursesMainForm::Generate()
   // run the generate process
   int retVal = this->CMakeInstance->Generate();
 
-  this->CMakeInstance->SetProgressCallback(0, 0);
+  this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
   keypad(stdscr, TRUE); /* Use key symbols as
                            KEY_DOWN*/
 
@@ -675,7 +669,7 @@ int cmCursesMainForm::Generate()
   return 0;
 }
 
-void cmCursesMainForm::AddError(const char* message, const char*)
+void cmCursesMainForm::AddError(const char* message, const char* /*unused*/)
 {
   this->Errors.push_back(message);
 }
@@ -742,8 +736,6 @@ void cmCursesMainForm::FixValue(cmState::CacheEntryType type,
   }
 }
 
-#include <unistd.h>
-
 void cmCursesMainForm::HandleInput()
 {
   int x = 0, y = 0;
@@ -837,7 +829,9 @@ void cmCursesMainForm::HandleInput()
       // therefore, the label field for the prev. entry is index-5
       // and the label field for the next entry is index+1
       // (index always corresponds to the value field)
-      else if (key == KEY_DOWN || key == ctrl('n')) {
+      // scroll down with arrow down, ctrl+n (emacs binding), or j (vim
+      // binding)
+      else if (key == KEY_DOWN || key == ctrl('n') || key == 'j') {
         FIELD* cur = current_field(this->Form);
         size_t findex = field_index(cur);
         if (findex == 3 * this->NumberOfVisibleEntries - 1) {
@@ -854,7 +848,8 @@ void cmCursesMainForm::HandleInput()
       // therefore, the label field for the prev. entry is index-5
       // and the label field for the next entry is index+1
       // (index always corresponds to the value field)
-      else if (key == KEY_UP || key == ctrl('p')) {
+      // scroll down with arrow up, ctrl+p (emacs binding), or k (vim binding)
+      else if (key == KEY_UP || key == ctrl('p') || key == 'k') {
         FIELD* cur = current_field(this->Form);
         int findex = field_index(cur);
         if (findex == 2) {
@@ -888,7 +883,7 @@ void cmCursesMainForm::HandleInput()
         cmCursesWidget* lbl = reinterpret_cast<cmCursesWidget*>(
           field_userptr(this->Fields[findex - 2]));
         const char* curField = lbl->GetValue();
-        const char* helpString = 0;
+        const char* helpString = CM_NULLPTR;
 
         const char* existingValue =
           this->CMakeInstance->GetState()->GetCacheEntryValue(curField);
@@ -973,7 +968,7 @@ void cmCursesMainForm::HandleInput()
         // (findex always corresponds to the value field)
         FIELD* nextCur;
         if (findex == 2) {
-          nextCur = 0;
+          nextCur = CM_NULLPTR;
         } else if (findex == 3 * this->NumberOfVisibleEntries - 1) {
           nextCur = this->Fields[findex - 5];
         } else {
@@ -1003,7 +998,7 @@ void cmCursesMainForm::HandleInput()
 
           if (nextCur) {
             // make the next or prev. current field after deletion
-            nextCur = 0;
+            nextCur = CM_NULLPTR;
             std::vector<cmCursesCacheEntryComposite*>::iterator it;
             for (it = this->Entries->begin(); it != this->Entries->end();
                  ++it) {
@@ -1025,7 +1020,7 @@ void cmCursesMainForm::HandleInput()
   }
 }
 
-int cmCursesMainForm::LoadCache(const char*)
+int cmCursesMainForm::LoadCache(const char* /*unused*/)
 
 {
   int r = this->CMakeInstance->LoadCache();
@@ -1052,7 +1047,7 @@ void cmCursesMainForm::JumpToCacheEntry(const char* astr)
   int findex = start_index;
   for (;;) {
     if (!str.empty()) {
-      cmCursesWidget* lbl = 0;
+      cmCursesWidget* lbl = CM_NULLPTR;
       if (findex >= 0) {
         lbl = reinterpret_cast<cmCursesWidget*>(
           field_userptr(this->Fields[findex - 2]));
@@ -1122,16 +1117,17 @@ const char* cmCursesMainForm::s_ConstHelpMessage =
   "Navigation: "
   "You can use the arrow keys and page up, down to navigate the options. "
   "Alternatively, you can use the following keys: \n"
-  " C-n : next option\n"
-  " C-p : previous options\n"
+  " C-n or j : next option\n"
+  " C-p or k : previous options\n"
   " C-d : down one page\n"
   " C-u : up one page\n\n"
   "Editing options: "
   "To change an option  press enter or return. If the current options is a "
-  "boolean, this will toggle it's value. "
-  "Otherwise, ccmake will enter edit mode. In this mode you can edit an "
-  "option using arrow keys and backspace. Alternatively, you can use the "
-  "following keys:\n"
+  "boolean, this will toggle its value. "
+  "Otherwise, ccmake will enter edit mode. Alternatively, you can toggle "
+  "a bool variable by pressing space, and enter edit mode with i."
+  "In this mode you can edit an option using arrow keys and backspace. "
+  "Alternatively, you can use the following keys:\n"
   " C-b : back one character\n"
   " C-f : forward one character\n"
   " C-a : go to the beginning of the field\n"
@@ -1140,7 +1136,6 @@ const char* cmCursesMainForm::s_ConstHelpMessage =
   " C-k : kill the rest of the field\n"
   " Esc : Restore field (discard last changes)\n"
   " Enter : Leave edit mode\n"
-  "You can also delete an option by pressing 'd'\n\n"
   "Commands:\n"
   " q : quit ccmake without generating build files\n"
   " h : help, shows this screen\n"
@@ -1148,6 +1143,7 @@ const char* cmCursesMainForm::s_ConstHelpMessage =
   " g : generate build files and exit, only available when there are no "
   "new options and no errors have been detected during last configuration.\n"
   " l : shows last errors\n"
+  " d : delete an option\n"
   " t : toggles advanced mode. In normal mode, only the most important "
   "options are shown. In advanced mode, all options are shown. We recommend "
   "using normal mode unless you are an expert.\n"
diff --git a/Source/CursesDialog/cmCursesMainForm.h b/Source/CursesDialog/cmCursesMainForm.h
index 9aa0f67..4bf452d 100644
--- a/Source/CursesDialog/cmCursesMainForm.h
+++ b/Source/CursesDialog/cmCursesMainForm.h
@@ -1,24 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesMainForm_h
 #define cmCursesMainForm_h
 
-#include "cmCursesStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include "../cmState.h"
 #include "cmCursesForm.h"
+#include "cmCursesStandardIncludes.h"
+#include "cmState.h"
+
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmCursesCacheEntryComposite;
-class cmCursesWidget;
 class cmake;
 
 /** \class cmCursesMainForm
@@ -30,7 +25,7 @@ class cmCursesMainForm : public cmCursesForm
 {
 public:
   cmCursesMainForm(std::vector<std::string> const& args, int initwidth);
-  virtual ~cmCursesMainForm();
+  ~cmCursesMainForm() CM_OVERRIDE;
 
   /**
    * Set the widgets which represent the cache entries.
@@ -40,13 +35,13 @@ public:
   /**
    * Handle user input.
    */
-  virtual void HandleInput();
+  void HandleInput() CM_OVERRIDE;
 
   /**
    * Display form. Use a window of size width x height, starting
    * at top, left.
    */
-  virtual void Render(int left, int top, int width, int height);
+  void Render(int left, int top, int width, int height) CM_OVERRIDE;
 
   /**
    * Returns true if an entry with the given key is in the
@@ -67,7 +62,7 @@ public:
    * exception is during a resize. The optional argument specifies the
    * string to be displayed in the status bar.
    */
-  virtual void UpdateStatusBar() { this->UpdateStatusBar(0); }
+  void UpdateStatusBar() CM_OVERRIDE { this->UpdateStatusBar(CM_NULLPTR); }
   virtual void UpdateStatusBar(const char* message);
 
   /**
@@ -83,7 +78,7 @@ public:
    * During a CMake run, an error handle should add errors
    * to be displayed afterwards.
    */
-  virtual void AddError(const char* message, const char* title);
+  void AddError(const char* message, const char* title) CM_OVERRIDE;
 
   /**
    * Used to do a configure. If argument is specified, it does only the check
diff --git a/Source/CursesDialog/cmCursesOptionsWidget.cxx b/Source/CursesDialog/cmCursesOptionsWidget.cxx
index 1a3a8c2..e23a82d 100644
--- a/Source/CursesDialog/cmCursesOptionsWidget.cxx
+++ b/Source/CursesDialog/cmCursesOptionsWidget.cxx
@@ -1,22 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesOptionsWidget.h"
 
-#include "cmCursesMainForm.h"
+#include "cmCursesWidget.h"
+#include "cmState.h"
 
-inline int ctrl(int z)
-{
-  return (z & 037);
-}
+#define ctrl(z) ((z)&037)
 
 cmCursesOptionsWidget::cmCursesOptionsWidget(int width, int height, int left,
                                              int top)
@@ -31,27 +20,30 @@ cmCursesOptionsWidget::cmCursesOptionsWidget(int width, int height, int left,
   field_opts_off(this->Field, O_STATIC);
 }
 
-bool cmCursesOptionsWidget::HandleInput(int& key, cmCursesMainForm*, WINDOW* w)
+bool cmCursesOptionsWidget::HandleInput(int& key, cmCursesMainForm* /*fm*/,
+                                        WINDOW* w)
 {
-
-  // 10 == enter
-  if (key == 10 || key == KEY_ENTER) {
-    this->NextOption();
-    touchwin(w);
-    wrefresh(w);
-    return true;
-  } else if (key == KEY_LEFT || key == ctrl('b')) {
-    touchwin(w);
-    wrefresh(w);
-    this->PreviousOption();
-    return true;
-  } else if (key == KEY_RIGHT || key == ctrl('f')) {
-    this->NextOption();
-    touchwin(w);
-    wrefresh(w);
-    return true;
-  } else {
-    return false;
+  switch (key) {
+    case 10: // 10 == enter
+    case KEY_ENTER:
+      this->NextOption();
+      touchwin(w);
+      wrefresh(w);
+      return true;
+    case KEY_LEFT:
+    case ctrl('b'):
+      touchwin(w);
+      wrefresh(w);
+      this->PreviousOption();
+      return true;
+    case KEY_RIGHT:
+    case ctrl('f'):
+      this->NextOption();
+      touchwin(w);
+      wrefresh(w);
+      return true;
+    default:
+      return false;
   }
 }
 
diff --git a/Source/CursesDialog/cmCursesOptionsWidget.h b/Source/CursesDialog/cmCursesOptionsWidget.h
index a17f2d5..75065a2 100644
--- a/Source/CursesDialog/cmCursesOptionsWidget.h
+++ b/Source/CursesDialog/cmCursesOptionsWidget.h
@@ -1,19 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesOptionsWidget_h
 #define cmCursesOptionsWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
 
+#include <string>
+#include <vector>
+
 class cmCursesMainForm;
 
 class cmCursesOptionsWidget : public cmCursesWidget
@@ -25,7 +22,7 @@ public:
   // Handle user input. Called by the container of this widget
   // when this widget has focus. Returns true if the input was
   // handled.
-  virtual bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w);
+  bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
   void SetOption(const std::string&);
   void AddOption(std::string const&);
   void NextOption();
diff --git a/Source/CursesDialog/cmCursesPathWidget.cxx b/Source/CursesDialog/cmCursesPathWidget.cxx
index 33fffd1..d208598 100644
--- a/Source/CursesDialog/cmCursesPathWidget.cxx
+++ b/Source/CursesDialog/cmCursesPathWidget.cxx
@@ -1,19 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesPathWidget.h"
 
 #include "cmCursesMainForm.h"
+#include "cmCursesStringWidget.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 
+#include <vector>
+
 cmCursesPathWidget::cmCursesPathWidget(int width, int height, int left,
                                        int top)
   : cmCursesStringWidget(width, height, left, top)
diff --git a/Source/CursesDialog/cmCursesPathWidget.h b/Source/CursesDialog/cmCursesPathWidget.h
index 18d298a..63ed05b 100644
--- a/Source/CursesDialog/cmCursesPathWidget.h
+++ b/Source/CursesDialog/cmCursesPathWidget.h
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesPathWidget_h
 #define cmCursesPathWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesStringWidget.h"
 
+#include <string>
+
+class cmCursesMainForm;
+
 class cmCursesPathWidget : public cmCursesStringWidget
 {
 public:
@@ -23,9 +21,9 @@ public:
    * This method is called when different keys are pressed. The
    * subclass can have a special implementation handler for this.
    */
-  virtual void OnTab(cmCursesMainForm* fm, WINDOW* w);
-  virtual void OnReturn(cmCursesMainForm* fm, WINDOW* w);
-  virtual void OnType(int& key, cmCursesMainForm* fm, WINDOW* w);
+  void OnTab(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+  void OnReturn(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+  void OnType(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
 
 protected:
   cmCursesPathWidget(const cmCursesPathWidget& from);
diff --git a/Source/CursesDialog/cmCursesStandardIncludes.h b/Source/CursesDialog/cmCursesStandardIncludes.h
index 7b44df9..7818e3e 100644
--- a/Source/CursesDialog/cmCursesStandardIncludes.h
+++ b/Source/CursesDialog/cmCursesStandardIncludes.h
@@ -1,22 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesStandardIncludes_h
 #define cmCursesStandardIncludes_h
 
-#include "../cmStandardIncludes.h"
-
-#if defined(__sun__) && defined(__GNUC__)
-#define _MSE_INT_H
-#endif
+#include <cmConfigure.h>
 
 #if defined(__hpux)
 #define _BOOL_DEFINED
diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx
index 3707d0d..f068f67 100644
--- a/Source/CursesDialog/cmCursesStringWidget.cxx
+++ b/Source/CursesDialog/cmCursesStringWidget.cxx
@@ -1,17 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesStringWidget.h"
 
+#include "cmCursesForm.h"
 #include "cmCursesMainForm.h"
+#include "cmCursesStandardIncludes.h"
+#include "cmCursesWidget.h"
+#include "cmState.h"
+
+#include <stdio.h>
+#include <string.h>
 
 inline int ctrl(int z)
 {
@@ -29,12 +27,13 @@ cmCursesStringWidget::cmCursesStringWidget(int width, int height, int left,
   field_opts_off(this->Field, O_STATIC);
 }
 
-void cmCursesStringWidget::OnTab(cmCursesMainForm*, WINDOW*)
+void cmCursesStringWidget::OnTab(cmCursesMainForm* /*unused*/,
+                                 WINDOW* /*unused*/)
 {
   // FORM* form = fm->GetForm();
 }
 
-void cmCursesStringWidget::OnReturn(cmCursesMainForm* fm, WINDOW*)
+void cmCursesStringWidget::OnReturn(cmCursesMainForm* fm, WINDOW* /*unused*/)
 {
   FORM* form = fm->GetForm();
   if (this->InEdit) {
@@ -56,7 +55,8 @@ void cmCursesStringWidget::OnReturn(cmCursesMainForm* fm, WINDOW*)
   }
 }
 
-void cmCursesStringWidget::OnType(int& key, cmCursesMainForm* fm, WINDOW*)
+void cmCursesStringWidget::OnType(int& key, cmCursesMainForm* fm,
+                                  WINDOW* /*unused*/)
 {
   form_driver(fm->GetForm(), key);
 }
@@ -67,12 +67,14 @@ bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm,
   int x, y;
 
   FORM* form = fm->GetForm();
+  // when not in edit mode, edit mode is entered by pressing enter or i (vim
+  // binding)
   // 10 == enter
-  if (!this->InEdit && (key != 10 && key != KEY_ENTER)) {
+  if (!this->InEdit && (key != 10 && key != KEY_ENTER && key != 'i')) {
     return false;
   }
 
-  this->OriginalString = 0;
+  this->OriginalString = CM_NULLPTR;
   this->Done = false;
 
   char debugMessage[128];
@@ -90,18 +92,21 @@ bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm,
       // quit
       if (key == 'q') {
         return false;
-      } else {
-        key = getch();
-        continue;
       }
+      key = getch();
+      continue;
     }
 
     // If resize occurred during edit, move out of edit mode
-    if (!this->InEdit && (key != 10 && key != KEY_ENTER)) {
+    if (!this->InEdit && (key != 10 && key != KEY_ENTER && key != 'i')) {
       return false;
     }
-    // 10 == enter
-    if (key == 10 || key == KEY_ENTER) {
+    // enter edit with return and i (vim binding)
+    if (!this->InEdit && (key == 10 || key == KEY_ENTER || key == 'i')) {
+      this->OnReturn(fm, w);
+    }
+    // leave edit with return (but not i -- not a toggle)
+    else if (this->InEdit && (key == 10 || key == KEY_ENTER)) {
       this->OnReturn(fm, w);
     } else if (key == KEY_DOWN || key == ctrl('n') || key == KEY_UP ||
                key == ctrl('p') || key == KEY_NPAGE || key == ctrl('d') ||
@@ -199,7 +204,6 @@ bool cmCursesStringWidget::PrintKeys()
     curses_move(y - 3, 0);
     printw(fmt_s, "Editing option, press [enter] to leave edit.");
     return true;
-  } else {
-    return false;
   }
+  return false;
 }
diff --git a/Source/CursesDialog/cmCursesStringWidget.h b/Source/CursesDialog/cmCursesStringWidget.h
index fc1b2ba..b3c1089 100644
--- a/Source/CursesDialog/cmCursesStringWidget.h
+++ b/Source/CursesDialog/cmCursesStringWidget.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesStringWidget_h
 #define cmCursesStringWidget_h
 
+#include <cmConfigure.h>
+
+#include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
 
+#include <string>
+
 class cmCursesMainForm;
 
 /** \class cmCursesStringWidget
@@ -32,14 +28,14 @@ public:
    * when this widget has focus. Returns true if the input was
    * handled.
    */
-  virtual bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w);
+  bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
 
   /**
    * Set/Get the string.
    */
   void SetString(const std::string& value);
   const char* GetString();
-  virtual const char* GetValue();
+  const char* GetValue() CM_OVERRIDE;
 
   /**
    * Set/Get InEdit flag. Can be used to tell the widget to leave
@@ -61,7 +57,7 @@ public:
    * in the toolbar and return true. Otherwise, return false
    * and the parent widget will print.
    */
-  virtual bool PrintKeys();
+  bool PrintKeys() CM_OVERRIDE;
 
 protected:
   cmCursesStringWidget(const cmCursesStringWidget& from);
diff --git a/Source/CursesDialog/cmCursesWidget.cxx b/Source/CursesDialog/cmCursesWidget.cxx
index 100ed1d..6c76764 100644
--- a/Source/CursesDialog/cmCursesWidget.cxx
+++ b/Source/CursesDialog/cmCursesWidget.cxx
@@ -1,16 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCursesWidget.h"
 
+#include <cmConfigure.h>
+
 cmCursesWidget::cmCursesWidget(int width, int height, int left, int top)
 {
   this->Field = new_field(height, width, top, left, 0, 0);
@@ -23,7 +16,7 @@ cmCursesWidget::~cmCursesWidget()
 {
   if (this->Field) {
     free_field(this->Field);
-    this->Field = 0;
+    this->Field = CM_NULLPTR;
   }
 }
 
diff --git a/Source/CursesDialog/cmCursesWidget.h b/Source/CursesDialog/cmCursesWidget.h
index 2ac5bb8..bb26cf6 100644
--- a/Source/CursesDialog/cmCursesWidget.h
+++ b/Source/CursesDialog/cmCursesWidget.h
@@ -1,20 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCursesWidget_h
 #define cmCursesWidget_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmCursesStandardIncludes.h"
+#include "cmState.h"
 
-#include "../cmState.h"
+#include <string>
 
 class cmCursesMainForm;
 
diff --git a/Source/CursesDialog/form/CMakeLists.txt b/Source/CursesDialog/form/CMakeLists.txt
index 4e07fa0..0677043 100644
--- a/Source/CursesDialog/form/CMakeLists.txt
+++ b/Source/CursesDialog/form/CMakeLists.txt
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 project(CMAKE_FORM)
 
 include_regular_expression("^.*$")
diff --git a/Source/CursesDialog/form/cmFormConfigure.h.in b/Source/CursesDialog/form/cmFormConfigure.h.in
index a43169d..511c525 100644
--- a/Source/CursesDialog/form/cmFormConfigure.h.in
+++ b/Source/CursesDialog/form/cmFormConfigure.h.in
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef CMFORMCONFIGURE_H
 #define CMFORMCONFIGURE_H
 
diff --git a/Source/CursesDialog/form/form.h b/Source/CursesDialog/form/form.h
index 1219cb5..b65a3ca 100644
--- a/Source/CursesDialog/form/form.h
+++ b/Source/CursesDialog/form/form.h
@@ -33,10 +33,6 @@
 #ifndef FORM_H
 #define FORM_H
 
-#if defined(__sun__) && defined(__GNUC__)
- #define _MSE_INT_H
-#endif
-
 #include <cmFormConfigure.h>
 
 /* figure out which curses.h to include */
diff --git a/Source/Modules/FindJsonCpp.cmake b/Source/Modules/FindJsonCpp.cmake
index 014d3bd..1951b61 100644
--- a/Source/Modules/FindJsonCpp.cmake
+++ b/Source/Modules/FindJsonCpp.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 #[=======================================================================[.rst:
 FindJsonCpp
 -----------
@@ -45,19 +48,6 @@ The cache variables should not be used by project code.
 They may be set by end users to point at JsonCpp components.
 #]=======================================================================]
 
-#=============================================================================
-# Copyright 2014-2015 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 #-----------------------------------------------------------------------------
 find_library(JsonCpp_LIBRARY
   NAMES jsoncpp
diff --git a/Source/Modules/FindLibUV.cmake b/Source/Modules/FindLibUV.cmake
new file mode 100644
index 0000000..b8cb365
--- /dev/null
+++ b/Source/Modules/FindLibUV.cmake
@@ -0,0 +1,121 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindLibUV
+---------
+
+Find libuv includes and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+An :ref:`imported target <Imported targets>` named
+``LibUV::LibUV`` is provided if libuv has been found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module defines the following variables:
+
+``LibUV_FOUND``
+  True if libuv was found, false otherwise.
+``LibUV_INCLUDE_DIRS``
+  Include directories needed to include libuv headers.
+``LibUV_LIBRARIES``
+  Libraries needed to link to libuv.
+``LibUV_VERSION``
+  The version of libuv found.
+``LibUV_VERSION_MAJOR``
+  The major version of libuv.
+``LibUV_VERSION_MINOR``
+  The minor version of libuv.
+``LibUV_VERSION_PATCH``
+  The patch version of libuv.
+
+Cache Variables
+^^^^^^^^^^^^^^^
+
+This module uses the following cache variables:
+
+``LibUV_LIBRARY``
+  The location of the libuv library file.
+``LibUV_INCLUDE_DIR``
+  The location of the libuv include directory containing ``uv.h``.
+
+The cache variables should not be used by project code.
+They may be set by end users to point at libuv components.
+#]=======================================================================]
+
+#-----------------------------------------------------------------------------
+find_library(LibUV_LIBRARY
+  NAMES uv
+  )
+mark_as_advanced(LibUV_LIBRARY)
+
+find_path(LibUV_INCLUDE_DIR
+  NAMES uv.h
+  )
+mark_as_advanced(LibUV_INCLUDE_DIR)
+
+#-----------------------------------------------------------------------------
+# Extract version number if possible.
+set(_LibUV_H_REGEX "#[ \t]*define[ \t]+UV_VERSION_(MAJOR|MINOR|PATCH)[ \t]+[0-9]+")
+if(LibUV_INCLUDE_DIR AND EXISTS "${LibUV_INCLUDE_DIR}/uv-version.h")
+  file(STRINGS "${LibUV_INCLUDE_DIR}/uv-version.h" _LibUV_H REGEX "${_LibUV_H_REGEX}")
+elseif(LibUV_INCLUDE_DIR AND EXISTS "${LibUV_INCLUDE_DIR}/uv.h")
+  file(STRINGS "${LibUV_INCLUDE_DIR}/uv.h" _LibUV_H REGEX "${_LibUV_H_REGEX}")
+else()
+  set(_LibUV_H "")
+endif()
+foreach(c MAJOR MINOR PATCH)
+  if(_LibUV_H MATCHES "#[ \t]*define[ \t]+UV_VERSION_${c}[ \t]+([0-9]+)")
+    set(_LibUV_VERSION_${c} "${CMAKE_MATCH_1}")
+  else()
+    unset(_LibUV_VERSION_${c})
+  endif()
+endforeach()
+if(DEFINED _LibUV_VERSION_MAJOR AND DEFINED _LibUV_VERSION_MINOR)
+  set(LibUV_VERSION_MAJOR "${_LibUV_VERSION_MAJOR}")
+  set(LibUV_VERSION_MINOR "${_LibUV_VERSION_MINOR}")
+  set(LibUV_VERSION "${LibUV_VERSION_MAJOR}.${LibUV_VERSION_MINOR}")
+  if(DEFINED _LibUV_VERSION_PATCH)
+    set(LibUV_VERSION_PATCH "${_LibUV_VERSION_PATCH}")
+    set(LibUV_VERSION "${LibUV_VERSION}.${LibUV_VERSION_PATCH}")
+  else()
+    unset(LibUV_VERSION_PATCH)
+  endif()
+else()
+  set(LibUV_VERSION_MAJOR "")
+  set(LibUV_VERSION_MINOR "")
+  set(LibUV_VERSION_PATCH "")
+  set(LibUV_VERSION "")
+endif()
+unset(_LibUV_VERSION_MAJOR)
+unset(_LibUV_VERSION_MINOR)
+unset(_LibUV_VERSION_PATCH)
+unset(_LibUV_H_REGEX)
+unset(_LibUV_H)
+
+#-----------------------------------------------------------------------------
+include(${CMAKE_CURRENT_LIST_DIR}/../../Modules/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibUV
+  FOUND_VAR LibUV_FOUND
+  REQUIRED_VARS LibUV_LIBRARY LibUV_INCLUDE_DIR
+  VERSION_VAR LibUV_VERSION
+  )
+set(LIBUV_FOUND ${LibUV_FOUND})
+
+#-----------------------------------------------------------------------------
+# Provide documented result variables and targets.
+if(LibUV_FOUND)
+  set(LibUV_INCLUDE_DIRS ${LibUV_INCLUDE_DIR})
+  set(LibUV_LIBRARIES ${LibUV_LIBRARY})
+  if(NOT TARGET LibUV::LibUV)
+    add_library(LibUV::LibUV UNKNOWN IMPORTED)
+    set_target_properties(LibUV::LibUV PROPERTIES
+      IMPORTED_LOCATION "${LibUV_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${LibUV_INCLUDE_DIRS}"
+      )
+  endif()
+endif()
diff --git a/Source/QtDialog/AddCacheEntry.cxx b/Source/QtDialog/AddCacheEntry.cxx
index dc7a4b0..daf4bd1 100644
--- a/Source/QtDialog/AddCacheEntry.cxx
+++ b/Source/QtDialog/AddCacheEntry.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "AddCacheEntry.h"
 
 #include <QCompleter>
@@ -64,7 +54,8 @@ QVariant AddCacheEntry::value() const
   QWidget* w = this->StackedWidget->currentWidget();
   if (qobject_cast<QLineEdit*>(w)) {
     return static_cast<QLineEdit*>(w)->text();
-  } else if (qobject_cast<QCheckBox*>(w)) {
+  }
+  if (qobject_cast<QCheckBox*>(w)) {
     return static_cast<QCheckBox*>(w)->isChecked();
   }
   return QVariant();
diff --git a/Source/QtDialog/AddCacheEntry.h b/Source/QtDialog/AddCacheEntry.h
index 05469af..cc710f5 100644
--- a/Source/QtDialog/AddCacheEntry.h
+++ b/Source/QtDialog/AddCacheEntry.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef AddCacheEntry_h
 #define AddCacheEntry_h
 
diff --git a/Source/QtDialog/CMakeLists.txt b/Source/QtDialog/CMakeLists.txt
index a906f4a..10fd718 100644
--- a/Source/QtDialog/CMakeLists.txt
+++ b/Source/QtDialog/CMakeLists.txt
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 project(QtDialog)
 if(POLICY CMP0020)
@@ -36,6 +27,12 @@ if (Qt5Widgets_FOUND)
 
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}")
 
+  if(CMake_QT_STATIC_QXcbIntegrationPlugin_LIBRARIES)
+    list(APPEND CMake_QT_LIBRARIES ${CMake_QT_STATIC_QXcbIntegrationPlugin_LIBRARIES})
+    set_property(SOURCE CMakeSetup.cxx
+      PROPERTY COMPILE_DEFINITIONS USE_QXcbIntegrationPlugin)
+  endif()
+
   # We need to install platform plugin and add qt.conf for Qt5 on Mac and Windows.
   # FIXME: This should be part of Qt5 CMake scripts, but unfortunatelly
   # Qt5 support is missing there.
@@ -150,12 +147,12 @@ if(APPLE)
     MACOSX_PACKAGE_LOCATION Resources)
 endif()
 
-if(CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL)
-  install(FILES ${CMake_SOURCE_DIR}/Licenses/LGPLv2.1.txt
+if(USE_LGPL)
+  install(FILES ${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt
     DESTINATION ${CMAKE_DATA_DIR}/Licenses
     ${COMPONENT})
   set_property(SOURCE CMakeSetupDialog.cxx
-    PROPERTY COMPILE_DEFINITIONS CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL)
+    PROPERTY COMPILE_DEFINITIONS USE_LGPL="${USE_LGPL}")
 endif()
 
 set(CMAKE_INCLUDE_CURRENT_DIR ON)
diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx
index c849d52..fad8075 100644
--- a/Source/QtDialog/CMakeSetup.cxx
+++ b/Source/QtDialog/CMakeSetup.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "QCMake.h" // include to disable MS warnings
 
 #include "CMakeSetupDialog.h"
@@ -22,28 +13,36 @@
 #include <QString>
 #include <QTextCodec>
 #include <QTranslator>
+#include <QtPlugin>
 #include <cmsys/CommandLineArguments.hxx>
 #include <cmsys/Encoding.hxx>
 #include <cmsys/SystemTools.hxx>
 
-static const char* cmDocumentationName[][2] = { { 0,
+#include "cmSystemTools.h" // IWYU pragma: keep
+
+static const char* cmDocumentationName[][2] = { { CM_NULLPTR,
                                                   "  cmake-gui - CMake GUI." },
-                                                { 0, 0 } };
+                                                { CM_NULLPTR, CM_NULLPTR } };
 
 static const char* cmDocumentationUsage[][2] = {
-  { 0, "  cmake-gui [options]\n"
-       "  cmake-gui [options] <path-to-source>\n"
-       "  cmake-gui [options] <path-to-existing-build>" },
-  { 0, 0 }
+  { CM_NULLPTR, "  cmake-gui [options]\n"
+                "  cmake-gui [options] <path-to-source>\n"
+                "  cmake-gui [options] <path-to-existing-build>" },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
-static const char* cmDocumentationOptions[][2] = { { 0, 0 } };
+static const char* cmDocumentationOptions[]
+                                         [2] = { { CM_NULLPTR, CM_NULLPTR } };
 
 #if defined(Q_OS_MAC)
 static int cmOSXInstall(std::string dir);
 static void cmAddPluginPath();
 #endif
 
+#if defined(USE_QXcbIntegrationPlugin)
+Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
+#endif
+
 int main(int argc, char** argv)
 {
   cmsys::Encoding::CommandLineArguments encoding_args =
@@ -101,11 +100,13 @@ int main(int argc, char** argv)
   QTextCodec::setCodecForLocale(utf8_codec);
 #endif
 
+#if QT_VERSION < 0x050000
   // clean out standard Qt paths for plugins, which we don't use anyway
   // when creating Mac bundles, it potentially causes problems
   foreach (QString p, QApplication::libraryPaths()) {
     QApplication::removeLibraryPath(p);
   }
+#endif
 
   // tell the cmake library where cmake is
   QDir cmExecDir(QApplication::applicationDirPath());
diff --git a/Source/QtDialog/CMakeSetup64.png b/Source/QtDialog/CMakeSetup64.png
new file mode 100644
index 0000000..43a8cc6
Binary files /dev/null and b/Source/QtDialog/CMakeSetup64.png differ
diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx
index 712611d..111b28a 100644
--- a/Source/QtDialog/CMakeSetupDialog.cxx
+++ b/Source/QtDialog/CMakeSetupDialog.cxx
@@ -1,19 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "CMakeSetupDialog.h"
 
 #include <QCloseEvent>
 #include <QCoreApplication>
+#include <QDesktopServices>
 #include <QDialogButtonBox>
 #include <QDragEnterEvent>
 #include <QFileDialog>
@@ -41,7 +32,7 @@
 
 QCMakeThread::QCMakeThread(QObject* p)
   : QThread(p)
-  , CMakeInstance(NULL)
+  , CMakeInstance(CM_NULLPTR)
 {
 }
 
@@ -57,7 +48,7 @@ void QCMakeThread::run()
   emit this->cmakeInitialized();
   this->exec();
   delete this->CMakeInstance;
-  this->CMakeInstance = NULL;
+  this->CMakeInstance = CM_NULLPTR;
 }
 
 CMakeSetupDialog::CMakeSetupDialog()
@@ -227,6 +218,8 @@ void CMakeSetupDialog::initialize()
 
   QObject::connect(this->GenerateButton, SIGNAL(clicked(bool)), this,
                    SLOT(doGenerate()));
+  QObject::connect(this->OpenProjectButton, SIGNAL(clicked(bool)), this,
+                   SLOT(doOpenProject()));
 
   QObject::connect(this->BrowseSourceDirectoryButton, SIGNAL(clicked(bool)),
                    this, SLOT(doSourceBrowse()));
@@ -499,6 +492,26 @@ void CMakeSetupDialog::doGenerate()
   this->ConfigureNeeded = true;
 }
 
+QString CMakeSetupDialog::getProjectFilename()
+{
+  QStringList nameFilter;
+  nameFilter << "*.sln"
+             << "*.xcodeproj";
+  QDir directory(this->BinaryDirectory->currentText());
+  QStringList nlnFile = directory.entryList(nameFilter);
+
+  if (nlnFile.count() == 1) {
+    return this->BinaryDirectory->currentText() + "/" + nlnFile.at(0);
+  }
+
+  return QString();
+}
+
+void CMakeSetupDialog::doOpenProject()
+{
+  QDesktopServices::openUrl(QUrl::fromLocalFile(this->getProjectFilename()));
+}
+
 void CMakeSetupDialog::closeEvent(QCloseEvent* e)
 {
   // prompt for close if there are unsaved changes, and we're not busy
@@ -617,6 +630,11 @@ void CMakeSetupDialog::updateBinaryDirectory(const QString& dir)
     this->BinaryDirectory->setEditText(dir);
     this->BinaryDirectory->blockSignals(false);
   }
+  if (!this->getProjectFilename().isEmpty()) {
+    this->OpenProjectButton->setEnabled(true);
+  } else {
+    this->OpenProjectButton->setEnabled(false);
+  }
 }
 
 void CMakeSetupDialog::doBinaryBrowse()
@@ -830,17 +848,18 @@ void CMakeSetupDialog::doAbout()
     "\n"
     "CMake GUI maintained by csimsoft,\n"
     "built using Qt %2 (qt-project.org).\n"
-#ifdef CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL
+#ifdef USE_LGPL
     "\n"
     "The Qt Toolkit is Copyright (C) Digia Plc and/or its subsidiary(-ies).\n"
-    "Qt is licensed under terms of the GNU LGPLv2.1, available at:\n"
+    "Qt is licensed under terms of the GNU LGPLv" USE_LGPL ", available at:\n"
     " \"%3\""
 #endif
     );
   msg = msg.arg(cmVersion::GetCMakeVersion());
   msg = msg.arg(qVersion());
-#ifdef CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL
-  std::string lgpl = cmSystemTools::GetCMakeRoot() + "/Licenses/LGPLv2.1.txt";
+#ifdef USE_LGPL
+  std::string lgpl =
+    cmSystemTools::GetCMakeRoot() + "/Licenses/LGPLv" USE_LGPL ".txt";
   msg = msg.arg(lgpl.c_str());
 #endif
 
@@ -1001,22 +1020,28 @@ void CMakeSetupDialog::enterState(CMakeSetupDialog::State s)
   if (s == Interrupting) {
     this->ConfigureButton->setEnabled(false);
     this->GenerateButton->setEnabled(false);
+    this->OpenProjectButton->setEnabled(false);
   } else if (s == Configuring) {
     this->setEnabledState(false);
     this->GenerateButton->setEnabled(false);
     this->GenerateAction->setEnabled(false);
+    this->OpenProjectButton->setEnabled(false);
     this->ConfigureButton->setText(tr("&Stop"));
   } else if (s == Generating) {
     this->CacheModified = false;
     this->setEnabledState(false);
     this->ConfigureButton->setEnabled(false);
     this->GenerateAction->setEnabled(false);
+    this->OpenProjectButton->setEnabled(false);
     this->GenerateButton->setText(tr("&Stop"));
   } else if (s == ReadyConfigure) {
     this->setEnabledState(true);
     this->GenerateButton->setEnabled(true);
     this->GenerateAction->setEnabled(true);
     this->ConfigureButton->setEnabled(true);
+    if (!this->getProjectFilename().isEmpty()) {
+      this->OpenProjectButton->setEnabled(true);
+    }
     this->ConfigureButton->setText(tr("&Configure"));
     this->GenerateButton->setText(tr("&Generate"));
   } else if (s == ReadyGenerate) {
@@ -1024,6 +1049,9 @@ void CMakeSetupDialog::enterState(CMakeSetupDialog::State s)
     this->GenerateButton->setEnabled(true);
     this->GenerateAction->setEnabled(true);
     this->ConfigureButton->setEnabled(true);
+    if (!this->getProjectFilename().isEmpty()) {
+      this->OpenProjectButton->setEnabled(true);
+    }
     this->ConfigureButton->setText(tr("&Configure"));
     this->GenerateButton->setText(tr("&Generate"));
   }
diff --git a/Source/QtDialog/CMakeSetupDialog.h b/Source/QtDialog/CMakeSetupDialog.h
index 2a4ea7a..1abdb46 100644
--- a/Source/QtDialog/CMakeSetupDialog.h
+++ b/Source/QtDialog/CMakeSetupDialog.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef CMakeSetupDialog_h
 #define CMakeSetupDialog_h
 
@@ -41,6 +31,8 @@ protected slots:
   void initialize();
   void doConfigure();
   void doGenerate();
+  QString getProjectFilename();
+  void doOpenProject();
   void doInstallForCommandLine();
   void doHelp();
   void doAbout();
diff --git a/Source/QtDialog/CMakeSetupDialog.ui b/Source/QtDialog/CMakeSetupDialog.ui
index b04bd93..8d8e0cd 100644
--- a/Source/QtDialog/CMakeSetupDialog.ui
+++ b/Source/QtDialog/CMakeSetupDialog.ui
@@ -238,6 +238,13 @@
            </property>
           </widget>
          </item>
+          <item>
+            <widget class="QPushButton" name="OpenProjectButton">
+              <property name="text">
+                <string>Open &Project</string>
+              </property>
+            </widget>
+          </item>
          <item>
           <widget class="QLabel" name="Generator">
            <property name="text">
diff --git a/Source/QtDialog/Compilers.h b/Source/QtDialog/Compilers.h
index bdb1962..276e2a5 100644
--- a/Source/QtDialog/Compilers.h
+++ b/Source/QtDialog/Compilers.h
@@ -3,6 +3,8 @@
 #ifndef COMPILERS_HPP
 #define COMPILERS_HPP
 
+#include <cmConfigure.h>
+
 #include <QWidget>
 
 #include <ui_Compilers.h>
@@ -11,7 +13,7 @@ class Compilers : public QWidget, public Ui::Compilers
 {
   Q_OBJECT
 public:
-  Compilers(QWidget* p = NULL)
+  Compilers(QWidget* p = CM_NULLPTR)
     : QWidget(p)
   {
     this->setupUi(this);
diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx
index ca5e3b5..c34751a 100644
--- a/Source/QtDialog/FirstConfigure.cxx
+++ b/Source/QtDialog/FirstConfigure.cxx
@@ -129,8 +129,9 @@ bool StartCompilerSetup::crossCompilerSetup() const
 
 void StartCompilerSetup::onSelectionChanged(bool on)
 {
-  if (on)
+  if (on) {
     selectionChanged();
+  }
 }
 
 void StartCompilerSetup::onGeneratorChanged(QString const& name)
@@ -144,12 +145,15 @@ void StartCompilerSetup::onGeneratorChanged(QString const& name)
 
 int StartCompilerSetup::nextId() const
 {
-  if (compilerSetup())
+  if (compilerSetup()) {
     return NativeSetup;
-  if (crossCompilerSetup())
+  }
+  if (crossCompilerSetup()) {
     return CrossSetup;
-  if (crossCompilerToolChainFile())
+  }
+  if (crossCompilerToolChainFile()) {
     return ToolchainSetup;
+  }
   return -1;
 }
 
@@ -515,7 +519,8 @@ QString FirstConfigure::getCCompiler() const
 {
   if (this->compilerSetup()) {
     return this->mNativeCompilerSetupPage->getCCompiler();
-  } else if (this->crossCompilerSetup()) {
+  }
+  if (this->crossCompilerSetup()) {
     return this->mCrossCompilerSetupPage->getCCompiler();
   }
   return QString();
@@ -525,7 +530,8 @@ QString FirstConfigure::getCXXCompiler() const
 {
   if (this->compilerSetup()) {
     return this->mNativeCompilerSetupPage->getCXXCompiler();
-  } else if (this->crossCompilerSetup()) {
+  }
+  if (this->crossCompilerSetup()) {
     return this->mCrossCompilerSetupPage->getCXXCompiler();
   }
   return QString();
@@ -535,7 +541,8 @@ QString FirstConfigure::getFortranCompiler() const
 {
   if (this->compilerSetup()) {
     return this->mNativeCompilerSetupPage->getFortranCompiler();
-  } else if (this->crossCompilerSetup()) {
+  }
+  if (this->crossCompilerSetup()) {
     return this->mCrossCompilerSetupPage->getFortranCompiler();
   }
   return QString();
diff --git a/Source/QtDialog/QCMake.cxx b/Source/QtDialog/QCMake.cxx
index c84e153..cfb10f3 100644
--- a/Source/QtDialog/QCMake.cxx
+++ b/Source/QtDialog/QCMake.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "QCMake.h"
 
 #include <QCoreApplication>
diff --git a/Source/QtDialog/QCMake.h b/Source/QtDialog/QCMake.h
index a818c6b..12f6037 100644
--- a/Source/QtDialog/QCMake.h
+++ b/Source/QtDialog/QCMake.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef QCMake_h
 #define QCMake_h
 
+#include <cmConfigure.h>
+
 #include "cmake.h"
 
 #ifdef _MSC_VER
@@ -71,7 +63,7 @@ class QCMake : public QObject
 {
   Q_OBJECT
 public:
-  QCMake(QObject* p = 0);
+  QCMake(QObject* p = CM_NULLPTR);
   ~QCMake();
 public slots:
   /// load the cache file in a directory
diff --git a/Source/QtDialog/QCMakeCacheView.cxx b/Source/QtDialog/QCMakeCacheView.cxx
index cc1f4aa..9f5208a 100644
--- a/Source/QtDialog/QCMakeCacheView.cxx
+++ b/Source/QtDialog/QCMakeCacheView.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "QCMakeCacheView.h"
 
 #include <QApplication>
@@ -33,7 +23,7 @@ public:
   }
 
 protected:
-  bool filterAcceptsRow(int row, const QModelIndex& p) const
+  bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE
   {
     QStringList strs;
     const QAbstractItemModel* m = this->sourceModel();
@@ -87,7 +77,7 @@ public:
 protected:
   bool ShowAdvanced;
 
-  bool filterAcceptsRow(int row, const QModelIndex& p) const
+  bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE
   {
     const QAbstractItemModel* m = this->sourceModel();
     QModelIndex idx = m->index(row, 0, p);
@@ -95,10 +85,7 @@ protected:
     // if there are no children
     if (!m->hasChildren(idx)) {
       bool adv = m->data(idx, QCMakeCacheModel::AdvancedRole).toBool();
-      if (!adv || (adv && this->ShowAdvanced)) {
-        return true;
-      }
-      return false;
+      return !adv || this->ShowAdvanced;
     }
 
     // check children
@@ -160,7 +147,8 @@ QModelIndex QCMakeCacheView::moveCursor(CursorAction act,
   // want home/end to go to begin/end of rows, not columns
   if (act == MoveHome) {
     return this->model()->index(0, 1);
-  } else if (act == MoveEnd) {
+  }
+  if (act == MoveEnd) {
     return this->model()->index(this->model()->rowCount() - 1, 1);
   }
   return QTreeView::moveCursor(act, mod);
@@ -538,28 +526,31 @@ void QCMakeCacheModelDelegate::setFileDialogFlag(bool f)
   this->FileDialogFlag = f;
 }
 
-QWidget* QCMakeCacheModelDelegate::createEditor(QWidget* p,
-                                                const QStyleOptionViewItem&,
-                                                const QModelIndex& idx) const
+QWidget* QCMakeCacheModelDelegate::createEditor(
+  QWidget* p, const QStyleOptionViewItem& /*option*/,
+  const QModelIndex& idx) const
 {
   QModelIndex var = idx.sibling(idx.row(), 0);
   int type = var.data(QCMakeCacheModel::TypeRole).toInt();
   if (type == QCMakeProperty::BOOL) {
-    return NULL;
-  } else if (type == QCMakeProperty::PATH) {
+    return CM_NULLPTR;
+  }
+  if (type == QCMakeProperty::PATH) {
     QCMakePathEditor* editor =
       new QCMakePathEditor(p, var.data(Qt::DisplayRole).toString());
     QObject::connect(editor, SIGNAL(fileDialogExists(bool)), this,
                      SLOT(setFileDialogFlag(bool)));
     return editor;
-  } else if (type == QCMakeProperty::FILEPATH) {
+  }
+  if (type == QCMakeProperty::FILEPATH) {
     QCMakeFilePathEditor* editor =
       new QCMakeFilePathEditor(p, var.data(Qt::DisplayRole).toString());
     QObject::connect(editor, SIGNAL(fileDialogExists(bool)), this,
                      SLOT(setFileDialogFlag(bool)));
     return editor;
-  } else if (type == QCMakeProperty::STRING &&
-             var.data(QCMakeCacheModel::StringsRole).isValid()) {
+  }
+  if (type == QCMakeProperty::STRING &&
+      var.data(QCMakeCacheModel::StringsRole).isValid()) {
     QCMakeComboBox* editor = new QCMakeComboBox(
       p, var.data(QCMakeCacheModel::StringsRole).toStringList());
     editor->setFrame(false);
@@ -645,7 +636,7 @@ QSize QCMakeCacheModelDelegate::sizeHint(const QStyleOptionViewItem& option,
   QStyleOptionButton opt;
   opt.QStyleOption::operator=(option);
   sz = sz.expandedTo(
-    style->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt, NULL)
+    style->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt, CM_NULLPTR)
       .size());
 
   return sz;
diff --git a/Source/QtDialog/QCMakeCacheView.h b/Source/QtDialog/QCMakeCacheView.h
index 6ad56fb..c1debf5 100644
--- a/Source/QtDialog/QCMakeCacheView.h
+++ b/Source/QtDialog/QCMakeCacheView.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef QCMakeCacheView_h
 #define QCMakeCacheView_h
 
diff --git a/Source/QtDialog/QCMakeWidgets.cxx b/Source/QtDialog/QCMakeWidgets.cxx
index 4b3eb34..6a55a76 100644
--- a/Source/QtDialog/QCMakeWidgets.cxx
+++ b/Source/QtDialog/QCMakeWidgets.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "QCMakeWidgets.h"
 
 #include <QDirModel>
@@ -67,7 +57,7 @@ void QCMakeFilePathEditor::chooseFile()
   this->fileDialogExists(true);
   path =
     QFileDialog::getOpenFileName(this, title, info.absolutePath(), QString(),
-                                 NULL, QFileDialog::DontResolveSymlinks);
+                                 CM_NULLPTR, QFileDialog::DontResolveSymlinks);
   this->fileDialogExists(false);
 
   if (!path.isEmpty()) {
@@ -99,7 +89,7 @@ void QCMakePathEditor::chooseFile()
 // use same QDirModel for all completers
 static QDirModel* fileDirModel()
 {
-  static QDirModel* m = NULL;
+  static QDirModel* m = CM_NULLPTR;
   if (!m) {
     m = new QDirModel();
   }
@@ -107,7 +97,7 @@ static QDirModel* fileDirModel()
 }
 static QDirModel* pathDirModel()
 {
-  static QDirModel* m = NULL;
+  static QDirModel* m = CM_NULLPTR;
   if (!m) {
     m = new QDirModel();
     m->setFilter(QDir::AllDirs | QDir::Drives | QDir::NoDotAndDotDot);
diff --git a/Source/QtDialog/QCMakeWidgets.h b/Source/QtDialog/QCMakeWidgets.h
index f1e87ce..0db810c 100644
--- a/Source/QtDialog/QCMakeWidgets.h
+++ b/Source/QtDialog/QCMakeWidgets.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef QCMakeWidgets_h
 #define QCMakeWidgets_h
 
+#include <cmConfigure.h>
+
 #include <QComboBox>
 #include <QCompleter>
 #include <QLineEdit>
@@ -43,7 +35,7 @@ class QCMakePathEditor : public QCMakeFileEditor
 {
   Q_OBJECT
 public:
-  QCMakePathEditor(QWidget* p = NULL, const QString& var = QString());
+  QCMakePathEditor(QWidget* p = CM_NULLPTR, const QString& var = QString());
   void chooseFile();
 };
 
@@ -52,7 +44,8 @@ class QCMakeFilePathEditor : public QCMakeFileEditor
 {
   Q_OBJECT
 public:
-  QCMakeFilePathEditor(QWidget* p = NULL, const QString& var = QString());
+  QCMakeFilePathEditor(QWidget* p = CM_NULLPTR,
+                       const QString& var = QString());
   void chooseFile();
 };
 
diff --git a/Source/QtDialog/RegexExplorer.cxx b/Source/QtDialog/RegexExplorer.cxx
index d23a08c..1512166 100644
--- a/Source/QtDialog/RegexExplorer.cxx
+++ b/Source/QtDialog/RegexExplorer.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Gregor Jasny
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "RegexExplorer.h"
 
 RegexExplorer::RegexExplorer(QWidget* p)
diff --git a/Source/QtDialog/RegexExplorer.h b/Source/QtDialog/RegexExplorer.h
index 3ac8a24..f1c1e5f 100644
--- a/Source/QtDialog/RegexExplorer.h
+++ b/Source/QtDialog/RegexExplorer.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Gregor Jasny
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef RegexExplorer_h
 #define RegexExplorer_h
 
diff --git a/Source/QtDialog/WarningMessagesDialog.cxx b/Source/QtDialog/WarningMessagesDialog.cxx
index 3be6798..f608a84 100644
--- a/Source/QtDialog/WarningMessagesDialog.cxx
+++ b/Source/QtDialog/WarningMessagesDialog.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Gregor Jasny
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "WarningMessagesDialog.h"
 
 WarningMessagesDialog::WarningMessagesDialog(QWidget* prnt, QCMake* instance)
diff --git a/Source/QtDialog/WarningMessagesDialog.h b/Source/QtDialog/WarningMessagesDialog.h
index 4bb739c..acb830d 100644
--- a/Source/QtDialog/WarningMessagesDialog.h
+++ b/Source/QtDialog/WarningMessagesDialog.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Gregor Jasny
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef WarningMessagesDialog_h
 #define WarningMessagesDialog_h
 
diff --git a/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in b/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in
new file mode 100644
index 0000000..e3d8554
--- /dev/null
+++ b/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in
@@ -0,0 +1,21 @@
+// Component: CMake.Reference.DoxygenHTML
+
+function Component()
+{
+    // Default constructor
+}
+
+Component.prototype.createOperations = function()
+{
+    // Create shortcut
+    if (installer.value("os") === "win") {
+
+        component.addOperation("CreateShortcut",
+                               installer.value("TargetDir") + "/@CMAKE_DOC_DIR@/developer-reference/html/index.html",
+                               installer.value("StartMenuDir") + "/CMake Developer Reference.lnk");
+
+    }
+
+    // Call default implementation
+    component.createOperations();
+}
diff --git a/Source/QtIFW/cmake.org.html b/Source/QtIFW/cmake.org.html
index cf5649d..001d634 100644
--- a/Source/QtIFW/cmake.org.html
+++ b/Source/QtIFW/cmake.org.html
@@ -1,6 +1,6 @@
 <html>
 <head>
-<meta http-equiv="Refresh" content="0; url=http://cmake.org/" />
+<meta http-equiv="Refresh" content="0; url=https://cmake.org/" />
 </head>
 <body>
 </body>
diff --git a/Source/QtIFW/installscript.qs.in b/Source/QtIFW/installscript.qs.in
index 3411e34..39a8795 100644
--- a/Source/QtIFW/installscript.qs.in
+++ b/Source/QtIFW/installscript.qs.in
@@ -1,6 +1,7 @@
 function Component()
 {
-    // default constructor
+    // Do not show component selection page
+    installer.setDefaultPageVisible(QInstaller.ComponentSelection, false);
 }
 
 Component.prototype.createOperations = function()
diff --git a/Source/bindexplib.cxx b/Source/bindexplib.cxx
index b179f83..db97c47 100644
--- a/Source/bindexplib.cxx
+++ b/Source/bindexplib.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*-------------------------------------------------------------------------
   Portions of this source have been derived from the 'bindexplib' tool
   provided by the CERN ROOT Data Analysis Framework project (root.cern.ch).
@@ -244,9 +235,7 @@ public:
    *----------------------------------------------------------------------
    */
   void DumpObjFile() {
-     if(!HaveExportedObjects()) {
-        this->DumpExternalsObjects();
-     }
+    this->DumpExternalsObjects();
   }
 
   /*
diff --git a/Source/bindexplib.h b/Source/bindexplib.h
index 8661a4a..1a0c3a3 100644
--- a/Source/bindexplib.h
+++ b/Source/bindexplib.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef bindexplib_h
 #define bindexplib_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 
diff --git a/Source/cmAddCompileOptionsCommand.cxx b/Source/cmAddCompileOptionsCommand.cxx
index 2223cf4..9265cba 100644
--- a/Source/cmAddCompileOptionsCommand.cxx
+++ b/Source/cmAddCompileOptionsCommand.cxx
@@ -1,20 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCompileOptionsCommand.h"
 
 bool cmAddCompileOptionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h
index 5c073c8..52c4b51 100644
--- a/Source/cmAddCompileOptionsCommand.h
+++ b/Source/cmAddCompileOptionsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddCompileOptionsCommand_h
 #define cmAddCompileOptionsCommand_h
 
@@ -20,19 +11,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddCompileOptionsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddCompileOptionsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_compile_options"; }
+  std::string GetName() const CM_OVERRIDE { return "add_compile_options"; }
 
   cmTypeMacro(cmAddCompileOptionsCommand, cmCommand);
 };
diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx
index d8fd1d8..1ab4ef6 100644
--- a/Source/cmAddCustomCommandCommand.cxx
+++ b/Source/cmAddCustomCommandCommand.cxx
@@ -1,20 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCustomCommandCommand.h"
 
 #include "cmTarget.h"
 
 #include "cmSourceFile.h"
 
+#include "cmGlobalGenerator.h"
+
 // cmAddCustomCommandCommand
 bool cmAddCustomCommandCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -28,9 +21,9 @@ bool cmAddCustomCommandCommand::InitialPass(
     return false;
   }
 
-  std::string source, target, main_dependency, working;
+  std::string source, target, main_dependency, working, depfile;
   std::string comment_buffer;
-  const char* comment = 0;
+  const char* comment = CM_NULLPTR;
   std::vector<std::string> depends, outputs, output, byproducts;
   bool verbatim = false;
   bool append = false;
@@ -60,6 +53,7 @@ bool cmAddCustomCommandCommand::InitialPass(
     doing_byproducts,
     doing_comment,
     doing_working_directory,
+    doing_depfile,
     doing_nothing
   };
 
@@ -110,6 +104,13 @@ bool cmAddCustomCommandCommand::InitialPass(
       doing = doing_implicit_depends_lang;
     } else if (copy == "COMMENT") {
       doing = doing_comment;
+    } else if (copy == "DEPFILE") {
+      doing = doing_depfile;
+      if (this->Makefile->GetGlobalGenerator()->GetName() != "Ninja") {
+        this->SetError("Option DEPFILE not supported by " +
+                       this->Makefile->GetGlobalGenerator()->GetName());
+        return false;
+      }
     } else {
       std::string filename;
       switch (doing) {
@@ -147,6 +148,9 @@ bool cmAddCustomCommandCommand::InitialPass(
         filename = cmSystemTools::CollapseFullPath(filename);
       }
       switch (doing) {
+        case doing_depfile:
+          depfile = copy;
+          break;
         case doing_working_directory:
           working = copy;
           break;
@@ -250,8 +254,8 @@ bool cmAddCustomCommandCommand::InitialPass(
 
     // No command for this output exists.
     std::ostringstream e;
-    e << "given APPEND option with output \"" << output[0]
-      << "\" which is not already a custom command output.";
+    e << "given APPEND option with output\n\"" << output[0]
+      << "\"\nwhich is not already a custom command output.";
     this->SetError(e.str());
     return false;
   }
@@ -269,12 +273,12 @@ bool cmAddCustomCommandCommand::InitialPass(
     std::vector<std::string> no_depends;
     this->Makefile->AddCustomCommandToTarget(
       target, byproducts, no_depends, commandLines, cctype, comment,
-      working.c_str(), escapeOldStyle, uses_terminal);
+      working.c_str(), escapeOldStyle, uses_terminal, depfile);
   } else if (target.empty()) {
     // Target is empty, use the output.
     this->Makefile->AddCustomCommandToOutput(
       output, byproducts, depends, main_dependency, commandLines, comment,
-      working.c_str(), false, escapeOldStyle, uses_terminal);
+      working.c_str(), false, escapeOldStyle, uses_terminal, depfile);
 
     // Add implicit dependency scanning requests if any were given.
     if (!implicit_depends.empty()) {
diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h
index ccbd50c..527bb6c 100644
--- a/Source/cmAddCustomCommandCommand.h
+++ b/Source/cmAddCustomCommandCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddCustomCommandCommand_h
 #define cmAddCustomCommandCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddCustomCommandCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomCommandCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_custom_command"; }
+  std::string GetName() const CM_OVERRIDE { return "add_custom_command"; }
 
   cmTypeMacro(cmAddCustomCommandCommand, cmCommand);
 
diff --git a/Source/cmAddCustomTargetCommand.cxx b/Source/cmAddCustomTargetCommand.cxx
index ac08cb2..9c41dac 100644
--- a/Source/cmAddCustomTargetCommand.cxx
+++ b/Source/cmAddCustomTargetCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCustomTargetCommand.h"
 
 #include "cmGeneratorExpression.h"
@@ -18,7 +9,7 @@
 bool cmAddCustomTargetCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -47,7 +38,7 @@ bool cmAddCustomTargetCommand::InitialPass(
   bool verbatim = false;
   bool uses_terminal = false;
   std::string comment_buffer;
-  const char* comment = 0;
+  const char* comment = CM_NULLPTR;
   std::vector<std::string> sources;
 
   // Keep track of parser state.
diff --git a/Source/cmAddCustomTargetCommand.h b/Source/cmAddCustomTargetCommand.h
index 9c376c0..a4475c7 100644
--- a/Source/cmAddCustomTargetCommand.h
+++ b/Source/cmAddCustomTargetCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddCustomTargetCommand_h
 #define cmAddCustomTargetCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddCustomTargetCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomTargetCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_custom_target"; }
+  std::string GetName() const CM_OVERRIDE { return "add_custom_target"; }
 
   cmTypeMacro(cmAddCustomTargetCommand, cmCommand);
 };
diff --git a/Source/cmAddDefinitionsCommand.cxx b/Source/cmAddDefinitionsCommand.cxx
index 2d0d026..8d82e71 100644
--- a/Source/cmAddDefinitionsCommand.cxx
+++ b/Source/cmAddDefinitionsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddDefinitionsCommand.h"
 
 // cmAddDefinitionsCommand
@@ -16,7 +7,7 @@ bool cmAddDefinitionsCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
   // it is OK to have no arguments
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmAddDefinitionsCommand.h b/Source/cmAddDefinitionsCommand.h
index 959ed64..43d0199 100644
--- a/Source/cmAddDefinitionsCommand.h
+++ b/Source/cmAddDefinitionsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddDefinitionsCommand_h
 #define cmAddDefinitionsCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddDefinitionsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddDefinitionsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_definitions"; }
+  std::string GetName() const CM_OVERRIDE { return "add_definitions"; }
 
   cmTypeMacro(cmAddDefinitionsCommand, cmCommand);
 };
diff --git a/Source/cmAddDependenciesCommand.cxx b/Source/cmAddDependenciesCommand.cxx
index 5cf9d3b..0fa8943 100644
--- a/Source/cmAddDependenciesCommand.cxx
+++ b/Source/cmAddDependenciesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddDependenciesCommand.h"
 
 #include "cmGlobalGenerator.h"
diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h
index 202d072..95e2ac6 100644
--- a/Source/cmAddDependenciesCommand.h
+++ b/Source/cmAddDependenciesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependenciessCommand_h
 #define cmDependenciessCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddDependenciesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddDependenciesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_dependencies"; }
+  std::string GetName() const CM_OVERRIDE { return "add_dependencies"; }
 
   cmTypeMacro(cmAddDependenciesCommand, cmCommand);
 };
diff --git a/Source/cmAddExecutableCommand.cxx b/Source/cmAddExecutableCommand.cxx
index fec5eb8..96ad82a 100644
--- a/Source/cmAddExecutableCommand.cxx
+++ b/Source/cmAddExecutableCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddExecutableCommand.h"
 
 // cmExecutableCommand
diff --git a/Source/cmAddExecutableCommand.h b/Source/cmAddExecutableCommand.h
index 1e3181f..fc08e8b 100644
--- a/Source/cmAddExecutableCommand.h
+++ b/Source/cmAddExecutableCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExecutablesCommand_h
 #define cmExecutablesCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddExecutableCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddExecutableCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_executable"; }
+  std::string GetName() const CM_OVERRIDE { return "add_executable"; }
 
   cmTypeMacro(cmAddExecutableCommand, cmCommand);
 };
diff --git a/Source/cmAddLibraryCommand.cxx b/Source/cmAddLibraryCommand.cxx
index 4516ed2..26e38b8 100644
--- a/Source/cmAddLibraryCommand.cxx
+++ b/Source/cmAddLibraryCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddLibraryCommand.h"
 
 #include "cmState.h"
@@ -18,7 +9,7 @@
 bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
                                       cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmAddLibraryCommand.h b/Source/cmAddLibraryCommand.h
index 0f0f768..d072b80 100644
--- a/Source/cmAddLibraryCommand.h
+++ b/Source/cmAddLibraryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLibrarysCommand_h
 #define cmLibrarysCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddLibraryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddLibraryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_library"; }
+  std::string GetName() const CM_OVERRIDE { return "add_library"; }
 
   cmTypeMacro(cmAddLibraryCommand, cmCommand);
 };
diff --git a/Source/cmAddSubDirectoryCommand.cxx b/Source/cmAddSubDirectoryCommand.cxx
index 63a9051..bb1e239 100644
--- a/Source/cmAddSubDirectoryCommand.cxx
+++ b/Source/cmAddSubDirectoryCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddSubDirectoryCommand.h"
 
 // cmAddSubDirectoryCommand
 bool cmAddSubDirectoryCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmAddSubDirectoryCommand.h b/Source/cmAddSubDirectoryCommand.h
index 786c8b0..7347482 100644
--- a/Source/cmAddSubDirectoryCommand.h
+++ b/Source/cmAddSubDirectoryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddSubDirectoryCommand_h
 #define cmAddSubDirectoryCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddSubDirectoryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddSubDirectoryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_subdirectory"; }
+  std::string GetName() const CM_OVERRIDE { return "add_subdirectory"; }
 
   cmTypeMacro(cmAddSubDirectoryCommand, cmCommand);
 };
diff --git a/Source/cmAddTestCommand.cxx b/Source/cmAddTestCommand.cxx
index 204dd97..11342ee 100644
--- a/Source/cmAddTestCommand.cxx
+++ b/Source/cmAddTestCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddTestCommand.h"
 
 #include "cmTestGenerator.h"
diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h
index 295fb78..92db7bc 100644
--- a/Source/cmAddTestCommand.h
+++ b/Source/cmAddTestCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAddTestCommand_h
 #define cmAddTestCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAddTestCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAddTestCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "add_test"; }
+  std::string GetName() const CM_OVERRIDE { return "add_test"; }
 
   cmTypeMacro(cmAddTestCommand, cmCommand);
 
diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h
index ee803c8..aa55379 100644
--- a/Source/cmAlgorithms.h
+++ b/Source/cmAlgorithms.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAlgorithms_h
 #define cmAlgorithms_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 inline bool cmHasLiteralPrefixImpl(const std::string& str1, const char* str2,
diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx
index a0150ec..879c2ca 100644
--- a/Source/cmArchiveWrite.cxx
+++ b/Source/cmArchiveWrite.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmArchiveWrite.h"
 
 #include "cmLocale.h"
@@ -16,7 +7,11 @@
 #include "cm_get_date.h"
 #include <cm_libarchive.h>
 #include <cmsys/Directory.hxx>
+#include <cmsys/Encoding.hxx>
 #include <cmsys/FStream.hxx>
+#include <iostream>
+#include <string.h>
+#include <time.h>
 
 #ifndef __LA_SSIZE_T
 #define __LA_SSIZE_T la_ssize_t
@@ -64,15 +59,15 @@ public:
 struct cmArchiveWrite::Callback
 {
   // archive_write_callback
-  static __LA_SSIZE_T Write(struct archive*, void* cd, const void* b, size_t n)
+  static __LA_SSIZE_T Write(struct archive* /*unused*/, void* cd,
+                            const void* b, size_t n)
   {
     cmArchiveWrite* self = static_cast<cmArchiveWrite*>(cd);
     if (self->Stream.write(static_cast<const char*>(b),
                            static_cast<std::streamsize>(n))) {
       return static_cast<__LA_SSIZE_T>(n);
-    } else {
-      return static_cast<__LA_SSIZE_T>(-1);
     }
+    return static_cast<__LA_SSIZE_T>(-1);
   }
 };
 
@@ -151,9 +146,9 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c,
   }
 
   if (archive_write_open(
-        this->Archive, this, 0,
+        this->Archive, this, CM_NULLPTR,
         reinterpret_cast<archive_write_callback*>(&Callback::Write),
-        0) != ARCHIVE_OK) {
+        CM_NULLPTR) != ARCHIVE_OK) {
     this->Error = "archive_write_open: ";
     this->Error += cm_archive_error_string(this->Archive);
     return;
@@ -229,7 +224,8 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix)
   Entry e;
   cm_archive_entry_copy_sourcepath(e, file);
   cm_archive_entry_copy_pathname(e, dest);
-  if (archive_read_disk_entry_from_file(this->Disk, e, -1, 0) != ARCHIVE_OK) {
+  if (archive_read_disk_entry_from_file(this->Disk, e, -1, CM_NULLPTR) !=
+      ARCHIVE_OK) {
     this->Error = "archive_read_disk_entry_from_file '";
     this->Error += file;
     this->Error += "': ";
@@ -255,7 +251,7 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix)
     archive_entry_set_gid(e, this->Gid.Get());
   }
 
-  if (this->Uname.size() && this->Gname.size()) {
+  if (!this->Uname.empty() && !this->Gname.empty()) {
     archive_entry_set_uname(e, this->Uname.c_str());
     archive_entry_set_gname(e, this->Gname.c_str());
   }
@@ -266,7 +262,7 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix)
   }
 
   if (this->PermissionsMask.IsSet()) {
-    mode_t perm = archive_entry_perm(e);
+    int perm = archive_entry_perm(e);
     archive_entry_set_perm(e, perm & this->PermissionsMask.Get());
   }
 
diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h
index 72d8f3a..27c62b9 100644
--- a/Source/cmArchiveWrite.h
+++ b/Source/cmArchiveWrite.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmArchiveWrite_h
 #define cmArchiveWrite_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
+#include <stddef.h>
+#include <string>
 
 #if !defined(CMAKE_BUILD_WITH_CMAKE)
 #error "cmArchiveWrite not allowed during bootstrap build!"
@@ -72,13 +67,13 @@ public:
    * skip.  The remaining part of the input path is appended to the
    * "prefix" value to construct the final name in the archive.
    */
-  bool Add(std::string path, size_t skip = 0, const char* prefix = 0,
+  bool Add(std::string path, size_t skip = 0, const char* prefix = CM_NULLPTR,
            bool recursive = true);
 
   /** Returns true if there has been no error.  */
   operator safe_bool() const
   {
-    return this->Okay() ? &cmArchiveWrite::safe_bool_true : 0;
+    return this->Okay() ? &cmArchiveWrite::safe_bool_true : CM_NULLPTR;
   }
 
   /** Returns true if there has been an error.  */
@@ -94,7 +89,7 @@ public:
   void SetMTime(std::string const& t) { this->MTime = t; }
 
   //! Sets the permissions of the added files/folders
-  void SetPermissions(mode_t permissions_)
+  void SetPermissions(int permissions_)
   {
     this->Permissions.Set(permissions_);
   }
@@ -107,7 +102,7 @@ public:
   //! The permissions will be copied from the existing file
   //! or folder. The mask will then be applied to unset
   //! some of them
-  void SetPermissionsMask(mode_t permissionsMask_)
+  void SetPermissionsMask(int permissionsMask_)
   {
     this->PermissionsMask.Set(permissionsMask_);
   }
@@ -177,8 +172,8 @@ private:
   //!@}
 
   //! Permissions on files/folders
-  cmArchiveWriteOptional<mode_t> Permissions;
-  cmArchiveWriteOptional<mode_t> PermissionsMask;
+  cmArchiveWriteOptional<int> Permissions;
+  cmArchiveWriteOptional<int> PermissionsMask;
 };
 
 #endif
diff --git a/Source/cmAuxSourceDirectoryCommand.cxx b/Source/cmAuxSourceDirectoryCommand.cxx
index 78f67a4..6655911 100644
--- a/Source/cmAuxSourceDirectoryCommand.cxx
+++ b/Source/cmAuxSourceDirectoryCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAuxSourceDirectoryCommand.h"
 
 #include "cmSourceFile.h"
@@ -41,6 +32,8 @@ bool cmAuxSourceDirectoryCommand::InitialPass(
     sourceListValue = def;
   }
 
+  std::vector<std::string> files;
+
   // Load all the files in the directory
   cmsys::Directory dir;
   if (dir.Load(tdir.c_str())) {
@@ -64,14 +57,16 @@ bool cmAuxSourceDirectoryCommand::InitialPass(
           // depends can be done
           cmSourceFile* sf = this->Makefile->GetOrCreateSource(fullname);
           sf->SetProperty("ABSTRACT", "0");
-          if (!sourceListValue.empty()) {
-            sourceListValue += ";";
-          }
-          sourceListValue += fullname;
+          files.push_back(fullname);
         }
       }
     }
   }
+  std::sort(files.begin(), files.end());
+  if (!sourceListValue.empty()) {
+    sourceListValue += ";";
+  }
+  sourceListValue += cmJoin(files, ";");
   this->Makefile->AddDefinition(args[1], sourceListValue.c_str());
   return true;
 }
diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h
index b5943f5..cca70dc 100644
--- a/Source/cmAuxSourceDirectoryCommand.h
+++ b/Source/cmAuxSourceDirectoryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmAuxSourceDirectoryCommand_h
 #define cmAuxSourceDirectoryCommand_h
 
@@ -29,19 +20,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmAuxSourceDirectoryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmAuxSourceDirectoryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "aux_source_directory"; }
+  std::string GetName() const CM_OVERRIDE { return "aux_source_directory"; }
 
   cmTypeMacro(cmAuxSourceDirectoryCommand, cmCommand);
 };
diff --git a/Source/cmBase32.cxx b/Source/cmBase32.cxx
new file mode 100644
index 0000000..091d619
--- /dev/null
+++ b/Source/cmBase32.cxx
@@ -0,0 +1,99 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmBase32.h"
+
+// -- Static functions
+
+static const unsigned char Base32EncodeTable[33] =
+  "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+
+inline unsigned char Base32EncodeChar(int schar)
+{
+  return Base32EncodeTable[schar];
+}
+
+void Base32Encode5(const unsigned char src[5], char dst[8])
+{
+  // [0]:5 bits
+  dst[0] = Base32EncodeChar((src[0] >> 3) & 0x1F);
+  // [0]:3 bits + [1]:2 bits
+  dst[1] = Base32EncodeChar(((src[0] << 2) & 0x1C) + ((src[1] >> 6) & 0x03));
+  // [1]:5 bits
+  dst[2] = Base32EncodeChar((src[1] >> 1) & 0x1F);
+  // [1]:1 bit + [2]:4 bits
+  dst[3] = Base32EncodeChar(((src[1] << 4) & 0x10) + ((src[2] >> 4) & 0x0F));
+  // [2]:4 bits + [3]:1 bit
+  dst[4] = Base32EncodeChar(((src[2] << 1) & 0x1E) + ((src[3] >> 7) & 0x01));
+  // [3]:5 bits
+  dst[5] = Base32EncodeChar((src[3] >> 2) & 0x1F);
+  // [3]:2 bits + [4]:3 bit
+  dst[6] = Base32EncodeChar(((src[3] << 3) & 0x18) + ((src[4] >> 5) & 0x07));
+  // [4]:5 bits
+  dst[7] = Base32EncodeChar((src[4] << 0) & 0x1F);
+}
+
+// -- Class methods
+
+cmBase32Encoder::cmBase32Encoder()
+{
+}
+
+cmBase32Encoder::~cmBase32Encoder()
+{
+}
+
+std::string cmBase32Encoder::encodeString(const unsigned char* input,
+                                          size_t len, bool padding)
+{
+  std::string res;
+
+  static const size_t blockSize = 5;
+  static const size_t bufferSize = 8;
+  char buffer[bufferSize];
+
+  const unsigned char* end = input + len;
+  while ((input + blockSize) <= end) {
+    Base32Encode5(input, buffer);
+    res.append(buffer, bufferSize);
+    input += blockSize;
+  }
+
+  size_t remain(end - input);
+  if (remain != 0) {
+    // Temporary source buffer filled up with 0s
+    unsigned char extended[blockSize];
+    for (size_t ii = 0; ii != remain; ++ii) {
+      extended[ii] = input[ii];
+    }
+    for (size_t ii = remain; ii != blockSize; ++ii) {
+      extended[ii] = 0;
+    }
+
+    Base32Encode5(extended, buffer);
+    size_t numPad(0);
+    switch (remain) {
+      case 1:
+        numPad = 6;
+        break;
+      case 2:
+        numPad = 4;
+        break;
+      case 3:
+        numPad = 3;
+        break;
+      case 4:
+        numPad = 1;
+        break;
+      default:
+        break;
+    }
+    res.append(buffer, bufferSize - numPad);
+    if (padding) {
+      for (size_t ii = 0; ii != numPad; ++ii) {
+        res.push_back(paddingChar);
+      }
+    }
+  }
+
+  return res;
+}
diff --git a/Source/cmBase32.h b/Source/cmBase32.h
new file mode 100644
index 0000000..44bca2f
--- /dev/null
+++ b/Source/cmBase32.h
@@ -0,0 +1,33 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmBase32_h
+#define cmBase32_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <stddef.h>
+#include <string>
+
+/** \class cmBase32Encoder
+ * \brief Encodes a byte sequence to a Base32 byte sequence according to
+ * RFC4648
+ *
+ */
+class cmBase32Encoder
+{
+public:
+  static const char paddingChar = '=';
+
+public:
+  cmBase32Encoder();
+  ~cmBase32Encoder();
+
+  // Encodes the given input byte sequence into a string
+  // @arg input Input data pointer
+  // @arg len Input data size
+  // @arg padding Flag to append "=" on demand
+  std::string encodeString(const unsigned char* input, size_t len,
+                           bool padding = true);
+};
+
+#endif
diff --git a/Source/cmBootstrapCommands1.cxx b/Source/cmBootstrapCommands1.cxx
index 2de8770..2b3b62f 100644
--- a/Source/cmBootstrapCommands1.cxx
+++ b/Source/cmBootstrapCommands1.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 // This file is used to compile all the commands
 // that CMake knows about at compile time.
 // This is sort of a boot strapping approach since you would
diff --git a/Source/cmBootstrapCommands2.cxx b/Source/cmBootstrapCommands2.cxx
index 38d008d..625c3e0 100644
--- a/Source/cmBootstrapCommands2.cxx
+++ b/Source/cmBootstrapCommands2.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 // This file is used to compile all the commands
 // that CMake knows about at compile time.
 // This is sort of a boot strapping approach since you would
diff --git a/Source/cmBreakCommand.cxx b/Source/cmBreakCommand.cxx
index fd57705..a5b6e84 100644
--- a/Source/cmBreakCommand.cxx
+++ b/Source/cmBreakCommand.cxx
@@ -1,16 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBreakCommand.h"
 
+#include "cmExecutionStatus.h"
+
 // cmBreakCommand
 bool cmBreakCommand::InitialPass(std::vector<std::string> const& args,
                                  cmExecutionStatus& status)
diff --git a/Source/cmBreakCommand.h b/Source/cmBreakCommand.h
index 270d3e6..ab58ab2 100644
--- a/Source/cmBreakCommand.h
+++ b/Source/cmBreakCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmBreakCommand_h
 #define cmBreakCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmBreakCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmBreakCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "break"; }
+  std::string GetName() const CM_OVERRIDE { return "break"; }
 
   cmTypeMacro(cmBreakCommand, cmCommand);
 };
diff --git a/Source/cmBuildCommand.cxx b/Source/cmBuildCommand.cxx
index 586e8a8..365a426 100644
--- a/Source/cmBuildCommand.cxx
+++ b/Source/cmBuildCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBuildCommand.h"
 
 #include "cmGlobalGenerator.h"
@@ -27,7 +18,7 @@ bool cmBuildCommand::InitialPass(std::vector<std::string> const& args,
 
 bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("requires at least one argument naming a CMake variable");
     return false;
   }
@@ -36,8 +27,8 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
   const char* variable = args[0].c_str();
 
   // Parse remaining arguments.
-  const char* configuration = 0;
-  const char* project_name = 0;
+  std::string configuration;
+  std::string project_name;
   std::string target;
   enum Doing
   {
@@ -56,10 +47,10 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
       doing = DoingTarget;
     } else if (doing == DoingConfiguration) {
       doing = DoingNone;
-      configuration = args[i].c_str();
+      configuration = args[i];
     } else if (doing == DoingProjectName) {
       doing = DoingNone;
-      project_name = args[i].c_str();
+      project_name = args[i];
     } else if (doing == DoingTarget) {
       doing = DoingNone;
       target = args[i];
@@ -76,14 +67,14 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
   // so we put this code here to end up with the same default configuration
   // as the original 2-arg build_command signature:
   //
-  if (!configuration || !*configuration) {
-    configuration = getenv("CMAKE_CONFIG_TYPE");
+  if (configuration.empty()) {
+    cmSystemTools::GetEnv("CMAKE_CONFIG_TYPE", configuration);
   }
-  if (!configuration || !*configuration) {
+  if (configuration.empty()) {
     configuration = "Release";
   }
 
-  if (project_name && *project_name) {
+  if (!project_name.empty()) {
     this->Makefile->IssueMessage(
       cmake::AUTHOR_WARNING,
       "Ignoring PROJECT_NAME option because it has no effect.");
@@ -91,7 +82,8 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
 
   std::string makecommand =
     this->Makefile->GetGlobalGenerator()->GenerateCMakeBuildCommand(
-      target, configuration, "", this->Makefile->IgnoreErrorsCMP0061());
+      target, configuration.c_str(), "",
+      this->Makefile->IgnoreErrorsCMP0061());
 
   this->Makefile->AddDefinition(variable, makecommand.c_str());
 
@@ -108,10 +100,10 @@ bool cmBuildCommand::TwoArgsSignature(std::vector<std::string> const& args)
   const char* define = args[0].c_str();
   const char* cacheValue = this->Makefile->GetDefinition(define);
 
-  std::string configType = "Release";
-  const char* cfg = getenv("CMAKE_CONFIG_TYPE");
-  if (cfg && *cfg) {
-    configType = cfg;
+  std::string configType;
+  if (!cmSystemTools::GetEnv("CMAKE_CONFIG_TYPE", configType) ||
+      configType.empty()) {
+    configType = "Release";
   }
 
   std::string makecommand =
diff --git a/Source/cmBuildCommand.h b/Source/cmBuildCommand.h
index 6cbf3ca..a53a099 100644
--- a/Source/cmBuildCommand.h
+++ b/Source/cmBuildCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmBuildCommand_h
 #define cmBuildCommand_h
 
@@ -25,14 +16,14 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmBuildCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmBuildCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The primary command signature with optional, KEYWORD-based args.
@@ -47,7 +38,7 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "build_command"; }
+  std::string GetName() const CM_OVERRIDE { return "build_command"; }
 
   cmTypeMacro(cmBuildCommand, cmCommand);
 
diff --git a/Source/cmBuildNameCommand.cxx b/Source/cmBuildNameCommand.cxx
index 27234d7..9134b9a 100644
--- a/Source/cmBuildNameCommand.cxx
+++ b/Source/cmBuildNameCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBuildNameCommand.h"
 
 #include <cmsys/RegularExpression.hxx>
@@ -22,7 +13,7 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args,
         "The build_name command should not be called; see CMP0036.")) {
     return true;
   }
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmBuildNameCommand.h b/Source/cmBuildNameCommand.h
index 43c24b0..7c09d73 100644
--- a/Source/cmBuildNameCommand.h
+++ b/Source/cmBuildNameCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmBuildNameCommand_h
 #define cmBuildNameCommand_h
 
@@ -18,11 +9,11 @@ class cmBuildNameCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmBuildNameCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmBuildNameCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "build_name"; }
-  virtual bool IsScriptable() const { return true; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmBuildNameCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "build_name"; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 };
 
 #endif
diff --git a/Source/cmCLocaleEnvironmentScope.cxx b/Source/cmCLocaleEnvironmentScope.cxx
index ee9acde..28e8f2e 100644
--- a/Source/cmCLocaleEnvironmentScope.cxx
+++ b/Source/cmCLocaleEnvironmentScope.cxx
@@ -1,20 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCLocaleEnvironmentScope.h"
 
 #include "cmSystemTools.h"
 
 #include <sstream>
+#include <utility>
 
 cmCLocaleEnvironmentScope::cmCLocaleEnvironmentScope()
 {
@@ -31,8 +22,9 @@ cmCLocaleEnvironmentScope::cmCLocaleEnvironmentScope()
 
 std::string cmCLocaleEnvironmentScope::GetEnv(std::string const& key)
 {
-  const char* value = cmSystemTools::GetEnv(key);
-  return value ? value : std::string();
+  std::string value;
+  cmSystemTools::GetEnv(key, value);
+  return value;
 }
 
 void cmCLocaleEnvironmentScope::SetEnv(std::string const& key,
@@ -45,7 +37,7 @@ void cmCLocaleEnvironmentScope::SetEnv(std::string const& key,
   if (value.empty()) {
     cmSystemTools::UnsetEnv(key.c_str());
   } else {
-    std::stringstream tmp;
+    std::ostringstream tmp;
     tmp << key << "=" << value;
     cmSystemTools::PutEnv(tmp.str());
   }
@@ -55,7 +47,7 @@ cmCLocaleEnvironmentScope::~cmCLocaleEnvironmentScope()
 {
   for (backup_map_t::const_iterator i = this->EnvironmentBackup.begin();
        i != this->EnvironmentBackup.end(); ++i) {
-    std::stringstream tmp;
+    std::ostringstream tmp;
     tmp << i->first << "=" << i->second;
     cmSystemTools::PutEnv(tmp.str());
   }
diff --git a/Source/cmCLocaleEnvironmentScope.h b/Source/cmCLocaleEnvironmentScope.h
index b011741..32cc8df 100644
--- a/Source/cmCLocaleEnvironmentScope.h
+++ b/Source/cmCLocaleEnvironmentScope.h
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCLocaleEnvironmentScope_h
 #define cmCLocaleEnvironmentScope_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
 
 class cmCLocaleEnvironmentScope
 {
diff --git a/Source/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx
index fbec6fd..018010e 100644
--- a/Source/cmCMakeHostSystemInformationCommand.cxx
+++ b/Source/cmCMakeHostSystemInformationCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakeHostSystemInformationCommand.h"
 
 // cmCMakeHostSystemInformation
@@ -42,9 +33,9 @@ bool cmCMakeHostSystemInformationCommand::InitialPass(
       result_list += ";";
     }
     std::string value;
-    if (!this->GetValue(info, key, value))
+    if (!this->GetValue(info, key, value)) {
       return false;
-
+    }
     result_list += value;
   }
 
@@ -84,7 +75,7 @@ bool cmCMakeHostSystemInformationCommand::GetValue(
 std::string cmCMakeHostSystemInformationCommand::ValueToString(
   size_t value) const
 {
-  std::stringstream tmp;
+  std::ostringstream tmp;
   tmp << value;
   return tmp.str();
 }
diff --git a/Source/cmCMakeHostSystemInformationCommand.h b/Source/cmCMakeHostSystemInformationCommand.h
index 6981ea9..4ab6aa1 100644
--- a/Source/cmCMakeHostSystemInformationCommand.h
+++ b/Source/cmCMakeHostSystemInformationCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCMakeHostSystemInformationCommand_h
 #define cmCMakeHostSystemInformationCommand_h
 
@@ -28,7 +19,7 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     return new cmCMakeHostSystemInformationCommand;
   }
@@ -37,18 +28,18 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
   * This determines if the command is invoked when in script mode.
   */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
   * The name of the command as specified in CMakeList.txt.
   */
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return "cmake_host_system_information";
   }
diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx
index 1376845..80b5108 100644
--- a/Source/cmCMakeMinimumRequired.cxx
+++ b/Source/cmCMakeMinimumRequired.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakeMinimumRequired.h"
 
 #include "cmVersion.h"
diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h
index fc73e87..425aeed 100644
--- a/Source/cmCMakeMinimumRequired.h
+++ b/Source/cmCMakeMinimumRequired.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCMakeMinimumRequired_h
 #define cmCMakeMinimumRequired_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmCMakeMinimumRequired; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmCMakeMinimumRequired; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "cmake_minimum_required"; }
+  std::string GetName() const CM_OVERRIDE { return "cmake_minimum_required"; }
 
   cmTypeMacro(cmCMakeMinimumRequired, cmCommand);
 
diff --git a/Source/cmCMakePolicyCommand.cxx b/Source/cmCMakePolicyCommand.cxx
index 07e0885..eea76f2 100644
--- a/Source/cmCMakePolicyCommand.cxx
+++ b/Source/cmCMakePolicyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakePolicyCommand.h"
 
 #include "cmVersion.h"
@@ -17,30 +8,34 @@
 bool cmCMakePolicyCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("requires at least one argument.");
     return false;
   }
 
   if (args[0] == "SET") {
     return this->HandleSetMode(args);
-  } else if (args[0] == "GET") {
+  }
+  if (args[0] == "GET") {
     return this->HandleGetMode(args);
-  } else if (args[0] == "PUSH") {
+  }
+  if (args[0] == "PUSH") {
     if (args.size() > 1) {
       this->SetError("PUSH may not be given additional arguments.");
       return false;
     }
     this->Makefile->PushPolicy();
     return true;
-  } else if (args[0] == "POP") {
+  }
+  if (args[0] == "POP") {
     if (args.size() > 1) {
       this->SetError("POP may not be given additional arguments.");
       return false;
     }
     this->Makefile->PopPolicy();
     return true;
-  } else if (args[0] == "VERSION") {
+  }
+  if (args[0] == "VERSION") {
     return this->HandleVersionMode(args);
   }
 
@@ -148,7 +143,8 @@ bool cmCMakePolicyCommand::HandleVersionMode(
   if (args.size() <= 1) {
     this->SetError("VERSION not given an argument");
     return false;
-  } else if (args.size() >= 3) {
+  }
+  if (args.size() >= 3) {
     this->SetError("VERSION given too many arguments");
     return false;
   }
diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h
index dbb91d5..d5c5cb5 100644
--- a/Source/cmCMakePolicyCommand.h
+++ b/Source/cmCMakePolicyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCMakePolicyCommand_h
 #define cmCMakePolicyCommand_h
 
@@ -26,24 +17,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmCMakePolicyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmCMakePolicyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
     * This determines if the command is invoked when in script mode.
     */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
     * The name of the command as specified in CMakeList.txt.
     */
-  virtual std::string GetName() const { return "cmake_policy"; }
+  std::string GetName() const CM_OVERRIDE { return "cmake_policy"; }
 
   cmTypeMacro(cmCMakePolicyCommand, cmCommand);
 
diff --git a/Source/cmCPackPropertiesGenerator.cxx b/Source/cmCPackPropertiesGenerator.cxx
index af01c7d..ae6b0a1 100644
--- a/Source/cmCPackPropertiesGenerator.cxx
+++ b/Source/cmCPackPropertiesGenerator.cxx
@@ -1,8 +1,13 @@
 #include "cmCPackPropertiesGenerator.h"
 
-#include "cmLocalGenerator.h"
+#include "cmGeneratorExpression.h"
+#include "cmInstalledFile.h"
 #include "cmOutputConverter.h"
 
+#include <map>
+#include <ostream>
+#include <utility>
+
 cmCPackPropertiesGenerator::cmCPackPropertiesGenerator(
   cmLocalGenerator* lg, cmInstalledFile const& installedFile,
   std::vector<std::string> const& configurations)
diff --git a/Source/cmCPackPropertiesGenerator.h b/Source/cmCPackPropertiesGenerator.h
index 4372b87..37c6039 100644
--- a/Source/cmCPackPropertiesGenerator.h
+++ b/Source/cmCPackPropertiesGenerator.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCPackPropertiesGenerator_h
 #define cmCPackPropertiesGenerator_h
 
-#include "cmInstalledFile.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmScriptGenerator.h"
 
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+class cmInstalledFile;
 class cmLocalGenerator;
 
 /** \class cmCPackPropertiesGenerator
@@ -29,9 +26,8 @@ public:
                              std::vector<std::string> const& configurations);
 
 protected:
-  virtual void GenerateScriptForConfig(std::ostream& os,
-                                       const std::string& config,
-                                       Indent const& indent);
+  void GenerateScriptForConfig(std::ostream& os, const std::string& config,
+                               Indent const& indent) CM_OVERRIDE;
 
   cmLocalGenerator* LG;
   cmInstalledFile const& InstalledFile;
diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx
index a78300c..3a08aea 100644
--- a/Source/cmCPluginAPI.cxx
+++ b/Source/cmCPluginAPI.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
    this file contains the implementation of the C API to CMake. Generally
    these routines just manipulate arguments and then call the associated
@@ -218,8 +209,8 @@ void CCONV cmAddUtilityCommand(void* arg, const char* utilityName,
   }
 
   // Pass the call to the makefile instance.
-  mf->AddUtilityCommand(utilityName, (all ? false : true), 0, depends2,
-                        commandLines);
+  mf->AddUtilityCommand(utilityName, (all ? false : true), CM_NULLPTR,
+                        depends2, commandLines);
 }
 void CCONV cmAddCustomCommand(void* arg, const char* source,
                               const char* command, int numArgs,
@@ -257,7 +248,7 @@ void CCONV cmAddCustomCommand(void* arg, const char* source,
   }
 
   // Pass the call to the makefile instance.
-  const char* no_comment = 0;
+  const char* no_comment = CM_NULLPTR;
   mf->AddCustomCommandOldStyle(target, outputs2, depends2, source,
                                commandLines, no_comment);
 }
@@ -291,8 +282,8 @@ void CCONV cmAddCustomCommandToOutput(void* arg, const char* output,
   }
 
   // Pass the call to the makefile instance.
-  const char* no_comment = 0;
-  const char* no_working_dir = 0;
+  const char* no_comment = CM_NULLPTR;
+  const char* no_working_dir = CM_NULLPTR;
   mf->AddCustomCommandToOutput(output, depends2, main_dependency, commandLines,
                                no_comment, no_working_dir);
 }
@@ -333,8 +324,8 @@ void CCONV cmAddCustomCommandToTarget(void* arg, const char* target,
   // Pass the call to the makefile instance.
   std::vector<std::string> no_byproducts;
   std::vector<std::string> no_depends;
-  const char* no_comment = 0;
-  const char* no_working_dir = 0;
+  const char* no_comment = CM_NULLPTR;
+  const char* no_working_dir = CM_NULLPTR;
   mf->AddCustomCommandToTarget(target, no_byproducts, no_depends, commandLines,
                                cctype, no_comment, no_working_dir);
 }
@@ -414,7 +405,7 @@ void CCONV cmExpandSourceListArguments(void* arg, int numArgs,
     result.push_back(args[i]);
   }
   int resargc = static_cast<int>(result.size());
-  char** resargv = 0;
+  char** resargv = CM_NULLPTR;
   if (resargc) {
     resargv = (char**)malloc(resargc * sizeof(char*));
   }
@@ -453,7 +444,7 @@ int CCONV cmGetTotalArgumentSize(int argc, char** argv)
 struct cmCPluginAPISourceFile
 {
   cmCPluginAPISourceFile()
-    : RealSourceFile(0)
+    : RealSourceFile(CM_NULLPTR)
   {
   }
   cmSourceFile* RealSourceFile;
@@ -524,9 +515,8 @@ void CCONV* cmGetSource(void* arg, const char* name)
       i = cmCPluginAPISourceFiles.insert(entry).first;
     }
     return (void*)i->second;
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 void* CCONV cmAddSource(void* arg, void* arg2)
@@ -534,7 +524,7 @@ void* CCONV cmAddSource(void* arg, void* arg2)
   cmMakefile* mf = static_cast<cmMakefile*>(arg);
   cmCPluginAPISourceFile* osf = static_cast<cmCPluginAPISourceFile*>(arg2);
   if (osf->FullPath.empty()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Create the real cmSourceFile instance and copy over saved information.
@@ -574,12 +564,11 @@ const char* CCONV cmSourceFileGetProperty(void* arg, const char* prop)
   cmCPluginAPISourceFile* sf = static_cast<cmCPluginAPISourceFile*>(arg);
   if (cmSourceFile* rsf = sf->RealSourceFile) {
     return rsf->GetProperty(prop);
-  } else {
-    if (!strcmp(prop, "LOCATION")) {
-      return sf->FullPath.c_str();
-    }
-    return sf->Properties.GetPropertyValue(prop);
   }
+  if (!strcmp(prop, "LOCATION")) {
+    return sf->FullPath.c_str();
+  }
+  return sf->Properties.GetPropertyValue(prop);
 }
 
 int CCONV cmSourceFileGetPropertyAsBool(void* arg, const char* prop)
@@ -587,9 +576,8 @@ int CCONV cmSourceFileGetPropertyAsBool(void* arg, const char* prop)
   cmCPluginAPISourceFile* sf = static_cast<cmCPluginAPISourceFile*>(arg);
   if (cmSourceFile* rsf = sf->RealSourceFile) {
     return rsf->GetPropertyAsBool(prop) ? 1 : 0;
-  } else {
-    return cmSystemTools::IsOn(cmSourceFileGetProperty(arg, prop)) ? 1 : 0;
   }
+  return cmSystemTools::IsOn(cmSourceFileGetProperty(arg, prop)) ? 1 : 0;
 }
 
 void CCONV cmSourceFileSetProperty(void* arg, const char* prop,
diff --git a/Source/cmCPluginAPI.h b/Source/cmCPluginAPI.h
index 4d9a9a7..88b81c6 100644
--- a/Source/cmCPluginAPI.h
+++ b/Source/cmCPluginAPI.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /* This header file defines the API that loadable commands can use. In many
    of these commands C++ instances of cmMakefile of cmSourceFile are passed
    in as arguments or returned. In these cases they are passed as a void *
diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx
index bc36c5a..1824d94 100644
--- a/Source/cmCTest.cxx
+++ b/Source/cmCTest.cxx
@@ -1,60 +1,53 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include "cmCurl.h" // include before anything that includes windows.h
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTest.h"
 
 #include "cmAlgorithms.h"
-#include "cmCTestCommand.h"
-#include "cmCTestStartCommand.h"
-#include "cmDynamicLoader.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmState.h"
-#include "cmVersionMacros.h"
-#include "cmXMLWriter.h"
-#include "cmake.h"
-#include <cmsys/Base64.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/SystemInformation.hxx>
-
 #include "cmCTestBuildAndTestHandler.h"
 #include "cmCTestBuildHandler.h"
 #include "cmCTestConfigureHandler.h"
 #include "cmCTestCoverageHandler.h"
+#include "cmCTestGenericHandler.h"
 #include "cmCTestMemCheckHandler.h"
 #include "cmCTestScriptHandler.h"
+#include "cmCTestStartCommand.h"
 #include "cmCTestSubmitHandler.h"
 #include "cmCTestTestHandler.h"
 #include "cmCTestUpdateHandler.h"
 #include "cmCTestUploadHandler.h"
-
+#include "cmCurl.h"
+#include "cmDynamicLoader.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmVersion.h"
+#include "cmVersionConfig.h"
+#include "cmXMLWriter.h"
+#include "cmake.h"
 
+#include <cm_auto_ptr.hxx>
+#include <cm_curl.h>
+#include <cm_zlib.h>
+#include <cmsys/Base64.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
 #include <cmsys/Process.h>
-#include <cmsys/RegularExpression.hxx>
-
+#include <cmsys/String.hxx>
+#include <cmsys/SystemInformation.hxx>
 #include <ctype.h>
-#include <float.h>
-#include <math.h>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stdio.h>
 #include <stdlib.h>
-
-#include <cmsys/auto_ptr.hxx>
-
-#include <cm_zlib.h>
-#include <cmsys/Base64.h>
+#include <string.h>
+#include <string>
+#include <time.h>
+#include <utility>
+#include <vector>
 
 #if defined(__BEOS__) || defined(__HAIKU__)
 #include <be/kernel/OS.h> /* disable_debugger() API. */
@@ -70,7 +63,7 @@
 struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
 {
   struct tm* lctime;
-  time_t tctime = time(0);
+  time_t tctime = time(CM_NULLPTR);
   lctime = gmtime(&tctime);
   char buf[1024];
   // add todays year day and month to the time in str because
@@ -88,7 +81,7 @@ struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
   // As such, this time may be in the past or in the future.
   time_t ntime = curl_getdate(buf, &tctime);
   cmCTestLog(this, DEBUG, "   Get curl time: " << ntime << std::endl);
-  tctime = time(0);
+  tctime = time(CM_NULLPTR);
   cmCTestLog(this, DEBUG, "   Get the current time: " << tctime << std::endl);
 
   const int dayLength = 24 * 60 * 60;
@@ -134,7 +127,7 @@ std::string cmCTest::CleanString(const std::string& str)
 
 std::string cmCTest::CurrentTime()
 {
-  time_t currenttime = time(0);
+  time_t currenttime = time(CM_NULLPTR);
   struct tm* t = localtime(&currenttime);
   // return ::CleanString(ctime(&currenttime));
   char current_time[1024];
@@ -244,7 +237,7 @@ std::string cmCTest::DecodeURL(const std::string& in)
   for (const char* c = in.c_str(); *c; ++c) {
     if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
       char buf[3] = { *(c + 1), *(c + 2), 0 };
-      out.append(1, char(strtoul(buf, 0, 16)));
+      out.append(1, char(strtoul(buf, CM_NULLPTR, 16)));
       c += 2;
     } else {
       out.append(1, *c);
@@ -288,7 +281,7 @@ cmCTest::cmCTest()
   this->ScheduleType = "";
   this->StopTime = "";
   this->NextDayStopTime = false;
-  this->OutputLogFile = 0;
+  this->OutputLogFile = CM_NULLPTR;
   this->OutputLogFileLastTag = -1;
   this->SuppressUpdatingCTestConfiguration = false;
   this->DartVersion = 1;
@@ -298,9 +291,10 @@ cmCTest::cmCTest()
   this->ComputedCompressMemCheckOutput = false;
   this->RepeatTests = 1; // default to run each test once
   this->RepeatUntilFail = false;
-  if (const char* outOnFail =
-        cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE")) {
-    this->OutputTestOutputOnTestFailure = !cmSystemTools::IsOff(outOnFail);
+  std::string outOnFail;
+  if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", outOnFail)) {
+    this->OutputTestOutputOnTestFailure =
+      !cmSystemTools::IsOff(outOnFail.c_str());
   }
   this->InitStreams();
 
@@ -347,7 +341,7 @@ cmCTest::cmCTest()
 cmCTest::~cmCTest()
 {
   cmDeleteAll(this->TestingHandlers);
-  this->SetOutputLogFileName(0);
+  this->SetOutputLogFileName(CM_NULLPTR);
 }
 
 void cmCTest::SetParallelLevel(int level)
@@ -365,11 +359,8 @@ bool cmCTest::ShouldCompressTestOutput()
   if (!this->ComputedCompressTestOutput) {
     std::string cdashVersion = this->GetCDashVersion();
     // version >= 1.6?
-    bool cdashSupportsGzip =
-      cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER,
-                                    cdashVersion.c_str(), "1.6") ||
-      cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL,
-                                    cdashVersion.c_str(), "1.6");
+    bool cdashSupportsGzip = cmSystemTools::VersionCompare(
+      cmSystemTools::OP_GREATER_EQUAL, cdashVersion.c_str(), "1.6");
     this->CompressTestOutput &= cdashSupportsGzip;
     this->ComputedCompressTestOutput = true;
   }
@@ -474,7 +465,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
   cm.SetHomeOutputDirectory("");
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator gg(&cm);
-  cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
   if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(),
                                              mf.get())) {
     cmCTestOptionalLog(
@@ -515,7 +506,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
     std::string tag;
 
     if (createNewTag) {
-      time_t tctime = time(0);
+      time_t tctime = time(CM_NULLPTR);
       if (this->TomorrowTag) {
         tctime += (24 * 60 * 60);
       }
@@ -540,7 +531,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
         }
         tfin.close();
       }
-      if (tag.empty() || (0 != command) || this->Parts[PartStart]) {
+      if (tag.empty() || (CM_NULLPTR != command) || this->Parts[PartStart]) {
         cmCTestOptionalLog(
           this, DEBUG,
           "TestModel: " << this->GetTestModelString() << std::endl, quiet);
@@ -562,7 +553,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
           ofs << this->GetTestModelString() << std::endl;
         }
         ofs.close();
-        if (0 == command) {
+        if (CM_NULLPTR == command) {
           cmCTestOptionalLog(this, OUTPUT, "Create new tag: "
                                << tag << " - " << this->GetTestModelString()
                                << std::endl,
@@ -783,13 +774,12 @@ bool cmCTest::SetTest(const char* ttype, bool report)
   if (p != PartCount) {
     this->Parts[p].Enable();
     return true;
-  } else {
-    if (report) {
-      cmCTestLog(this, ERROR_MESSAGE, "Don't know about test \""
-                   << ttype << "\" yet..." << std::endl);
-    }
-    return false;
   }
+  if (report) {
+    cmCTestLog(this, ERROR_MESSAGE, "Don't know about test \""
+                 << ttype << "\" yet..." << std::endl);
+  }
+  return false;
 }
 
 void cmCTest::Finalize()
@@ -860,7 +850,7 @@ cmCTestGenericHandler* cmCTest::GetInitializedHandler(const char* handler)
   cmCTest::t_TestingHandlers::iterator it =
     this->TestingHandlers.find(handler);
   if (it == this->TestingHandlers.end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   it->second->Initialize();
   return it->second;
@@ -871,7 +861,7 @@ cmCTestGenericHandler* cmCTest::GetHandler(const char* handler)
   cmCTest::t_TestingHandlers::iterator it =
     this->TestingHandlers.find(handler);
   if (it == this->TestingHandlers.end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return it->second;
 }
@@ -886,7 +876,7 @@ int cmCTest::ExecuteHandler(const char* shandler)
   return handler->ProcessHandler();
 }
 
-int cmCTest::ProcessTests()
+int cmCTest::ProcessSteps()
 {
   int res = 0;
   bool notest = true;
@@ -1020,7 +1010,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
   // First generate the command and arguments
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
 
-  if (args.size() < 1) {
+  if (args.empty()) {
     return false;
   }
 
@@ -1029,7 +1019,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
        a != args.end(); ++a) {
     argv.push_back(a->c_str());
   }
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   output = "";
   cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
@@ -1057,7 +1047,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
   cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "   Each . represents "
                << tick_len << " bytes of output" << std::endl
                << "    " << std::flush);
-  while (cmsysProcess_WaitForData(cp, &data, &length, 0)) {
+  while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
     for (int cc = 0; cc < length; ++cc) {
       if (data[cc] == 0) {
         data[cc] = '\n';
@@ -1082,7 +1072,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
   cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Size of output: "
                << int(double(output.size()) / 1024.0) << "K" << std::endl);
 
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 
   int result = cmsysProcess_GetState(cp);
 
@@ -1165,7 +1155,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
     }
     std::string oldpath = cmSystemTools::GetCurrentWorkingDirectory();
 
-    cmsys::auto_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
+    CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv;
     if (modifyEnv) {
       saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment);
       cmSystemTools::AppendEnv(*environment);
@@ -1193,7 +1183,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
     *output = "";
   }
 
-  cmsys::auto_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
+  CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv;
   if (modifyEnv) {
     saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment);
     cmSystemTools::AppendEnv(*environment);
@@ -1211,7 +1201,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
 
   char* data;
   int length;
-  while (cmsysProcess_WaitForData(cp, &data, &length, 0)) {
+  while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
     if (output) {
       tempOutput.insert(tempOutput.end(), data, data + length);
     }
@@ -1221,7 +1211,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
     }
   }
 
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   if (output && tempOutput.begin() != tempOutput.end()) {
     output->append(&*tempOutput.begin(), tempOutput.size());
   }
@@ -1245,16 +1235,16 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
     if (output) {
       *output += outerr;
     }
-    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr.c_str() << std::endl
-                                                            << std::flush);
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr << std::endl
+                                                    << std::flush);
   } else if (result == cmsysProcess_State_Error) {
     std::string outerr = "\n*** ERROR executing: ";
     outerr += cmsysProcess_GetErrorString(cp);
     if (output) {
       *output += outerr;
     }
-    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr.c_str() << std::endl
-                                                            << std::flush);
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr << std::endl
+                                                    << std::flush);
   }
   cmsysProcess_Delete(cp);
 
@@ -1507,22 +1497,17 @@ std::string cmCTest::Base64EncodeFile(std::string const& file)
                         | std::ios::binary
 #endif
                       );
-  unsigned char* file_buffer = new unsigned char[len + 1];
-  ifs.read(reinterpret_cast<char*>(file_buffer), len);
+  std::vector<char> file_buffer(len + 1);
+  ifs.read(&file_buffer[0], len);
   ifs.close();
 
-  unsigned char* encoded_buffer = new unsigned char[(len * 3) / 2 + 5];
+  std::vector<char> encoded_buffer((len * 3) / 2 + 5);
 
-  size_t const rlen = cmsysBase64_Encode(file_buffer, len, encoded_buffer, 1);
+  size_t const rlen = cmsysBase64_Encode(
+    reinterpret_cast<unsigned char*>(&file_buffer[0]), len,
+    reinterpret_cast<unsigned char*>(&encoded_buffer[0]), 1);
 
-  std::string base64 = "";
-  for (size_t i = 0; i < rlen; i++) {
-    base64 += encoded_buffer[i];
-  }
-  delete[] file_buffer;
-  delete[] encoded_buffer;
-
-  return base64;
+  return std::string(&encoded_buffer[0], rlen);
 }
 
 bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
@@ -2018,7 +2003,7 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output)
     // handle the script arguments -S -SR -SP
     this->HandleScriptArguments(i, args, SRArgumentSpecified);
 
-    // handle a request for a dashboard
+    // --dashboard: handle a request for a dashboard
     std::string arg = args[i];
     if (this->CheckArgument(arg, "-D", "--dashboard") && i < args.size() - 1) {
       this->ProduceXML = true;
@@ -2044,54 +2029,18 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output)
       this->AddVariableDefinition(input);
     }
 
-    if (this->CheckArgument(arg, "-T", "--test-action") &&
-        (i < args.size() - 1)) {
-      this->ProduceXML = true;
-      i++;
-      if (!this->SetTest(args[i].c_str(), false)) {
-        executeTests = false;
-        cmCTestLog(this, ERROR_MESSAGE,
-                   "CTest -T called with incorrect option: " << args[i]
-                                                             << std::endl);
-        cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
-                     << std::endl
-                     << "  " << ctestExec << " -T all" << std::endl
-                     << "  " << ctestExec << " -T start" << std::endl
-                     << "  " << ctestExec << " -T update" << std::endl
-                     << "  " << ctestExec << " -T configure" << std::endl
-                     << "  " << ctestExec << " -T build" << std::endl
-                     << "  " << ctestExec << " -T test" << std::endl
-                     << "  " << ctestExec << " -T coverage" << std::endl
-                     << "  " << ctestExec << " -T memcheck" << std::endl
-                     << "  " << ctestExec << " -T notes" << std::endl
-                     << "  " << ctestExec << " -T submit" << std::endl);
-      }
+    // --test-action: calls SetTest(<stage>, /*report=*/ false) to enable
+    // the corresponding stage
+    if (!this->HandleTestActionArgument(ctestExec, i, args)) {
+      executeTests = false;
     }
 
-    // what type of test model
-    if (this->CheckArgument(arg, "-M", "--test-model") &&
-        (i < args.size() - 1)) {
-      i++;
-      std::string const& str = args[i];
-      if (cmSystemTools::LowerCase(str) == "nightly") {
-        this->SetTestModel(cmCTest::NIGHTLY);
-      } else if (cmSystemTools::LowerCase(str) == "continuous") {
-        this->SetTestModel(cmCTest::CONTINUOUS);
-      } else if (cmSystemTools::LowerCase(str) == "experimental") {
-        this->SetTestModel(cmCTest::EXPERIMENTAL);
-      } else {
-        executeTests = false;
-        cmCTestLog(this, ERROR_MESSAGE,
-                   "CTest -M called with incorrect option: " << str
-                                                             << std::endl);
-        cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
-                     << std::endl
-                     << "  " << ctestExec << " -M Continuous" << std::endl
-                     << "  " << ctestExec << " -M Experimental" << std::endl
-                     << "  " << ctestExec << " -M Nightly" << std::endl);
-      }
+    // --test-model: what type of test model
+    if (!this->HandleTestModelArgument(ctestExec, i, args)) {
+      executeTests = false;
     }
 
+    // --extra-submit
     if (this->CheckArgument(arg, "--extra-submit") && i < args.size() - 1) {
       this->ProduceXML = true;
       this->SetTest("Submit");
@@ -2106,6 +2055,7 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output)
       cmakeAndTest = true;
     }
 
+    // --schedule-random
     if (this->CheckArgument(arg, "--schedule-random")) {
       this->ScheduleType = "Random";
     }
@@ -2124,80 +2074,151 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output)
     }
   } // the close of the for argument loop
 
+  // handle CTEST_PARALLEL_LEVEL environment variable
   if (!this->ParallelLevelSetInCli) {
-    if (const char* parallel = cmSystemTools::GetEnv("CTEST_PARALLEL_LEVEL")) {
-      int plevel = atoi(parallel);
+    std::string parallel;
+    if (cmSystemTools::GetEnv("CTEST_PARALLEL_LEVEL", parallel)) {
+      int plevel = atoi(parallel.c_str());
       this->SetParallelLevel(plevel);
     }
   }
 
-  // now what sould cmake do? if --build-and-test was specified then
+  // now what should cmake do? if --build-and-test was specified then
   // we run the build and test handler and return
   if (cmakeAndTest) {
-    this->Verbose = true;
-    cmCTestBuildAndTestHandler* handler =
-      static_cast<cmCTestBuildAndTestHandler*>(this->GetHandler("buildtest"));
-    int retv = handler->ProcessHandler();
-    *output = handler->GetOutput();
-#ifdef CMAKE_BUILD_WITH_CMAKE
-    cmDynamicLoader::FlushCache();
-#endif
-    if (retv != 0) {
-      cmCTestLog(this, DEBUG,
-                 "build and test failing returning: " << retv << std::endl);
-    }
-    return retv;
+    return this->RunCMakeAndTest(output);
   }
 
   if (executeTests) {
-    int res;
-    // call process directory
-    if (this->RunConfigurationScript) {
-      if (this->ExtraVerbose) {
-        cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
-      }
-      cmCTest::t_TestingHandlers::iterator it;
-      for (it = this->TestingHandlers.begin();
-           it != this->TestingHandlers.end(); ++it) {
-        it->second->SetVerbose(this->ExtraVerbose);
-        it->second->SetSubmitIndex(this->SubmitIndex);
-      }
-      this->GetHandler("script")->SetVerbose(this->Verbose);
-      res = this->GetHandler("script")->ProcessHandler();
-      if (res != 0) {
-        cmCTestLog(this, DEBUG,
-                   "running script failing returning: " << res << std::endl);
-      }
+    return this->ExecuteTests();
+  }
+
+  return 1;
+}
 
+bool cmCTest::HandleTestActionArgument(const char* ctestExec, size_t& i,
+                                       const std::vector<std::string>& args)
+{
+  bool success = true;
+  std::string arg = args[i];
+  if (this->CheckArgument(arg, "-T", "--test-action") &&
+      (i < args.size() - 1)) {
+    this->ProduceXML = true;
+    i++;
+    if (!this->SetTest(args[i].c_str(), false)) {
+      success = false;
+      cmCTestLog(this, ERROR_MESSAGE, "CTest -T called with incorrect option: "
+                   << args[i] << std::endl);
+      cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
+                   << std::endl
+                   << "  " << ctestExec << " -T all" << std::endl
+                   << "  " << ctestExec << " -T start" << std::endl
+                   << "  " << ctestExec << " -T update" << std::endl
+                   << "  " << ctestExec << " -T configure" << std::endl
+                   << "  " << ctestExec << " -T build" << std::endl
+                   << "  " << ctestExec << " -T test" << std::endl
+                   << "  " << ctestExec << " -T coverage" << std::endl
+                   << "  " << ctestExec << " -T memcheck" << std::endl
+                   << "  " << ctestExec << " -T notes" << std::endl
+                   << "  " << ctestExec << " -T submit" << std::endl);
+    }
+  }
+  return success;
+}
+
+bool cmCTest::HandleTestModelArgument(const char* ctestExec, size_t& i,
+                                      const std::vector<std::string>& args)
+{
+  bool success = true;
+  std::string arg = args[i];
+  if (this->CheckArgument(arg, "-M", "--test-model") &&
+      (i < args.size() - 1)) {
+    i++;
+    std::string const& str = args[i];
+    if (cmSystemTools::LowerCase(str) == "nightly") {
+      this->SetTestModel(cmCTest::NIGHTLY);
+    } else if (cmSystemTools::LowerCase(str) == "continuous") {
+      this->SetTestModel(cmCTest::CONTINUOUS);
+    } else if (cmSystemTools::LowerCase(str) == "experimental") {
+      this->SetTestModel(cmCTest::EXPERIMENTAL);
     } else {
-      // What is this?  -V seems to be the same as -VV,
-      // and Verbose is always on in this case
-      this->ExtraVerbose = this->Verbose;
-      this->Verbose = true;
-      cmCTest::t_TestingHandlers::iterator it;
-      for (it = this->TestingHandlers.begin();
-           it != this->TestingHandlers.end(); ++it) {
-        it->second->SetVerbose(this->Verbose);
-        it->second->SetSubmitIndex(this->SubmitIndex);
-      }
-      std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
-      if (!this->Initialize(cwd.c_str(), 0)) {
-        res = 12;
-        cmCTestLog(this, ERROR_MESSAGE, "Problem initializing the dashboard."
-                     << std::endl);
-      } else {
-        res = this->ProcessTests();
-      }
-      this->Finalize();
+      success = false;
+      cmCTestLog(this, ERROR_MESSAGE, "CTest -M called with incorrect option: "
+                   << str << std::endl);
+      cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
+                   << std::endl
+                   << "  " << ctestExec << " -M Continuous" << std::endl
+                   << "  " << ctestExec << " -M Experimental" << std::endl
+                   << "  " << ctestExec << " -M Nightly" << std::endl);
     }
+  }
+  return success;
+}
+
+int cmCTest::ExecuteTests()
+{
+  int res;
+  // call process directory
+  if (this->RunConfigurationScript) {
+    if (this->ExtraVerbose) {
+      cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
+    }
+    cmCTest::t_TestingHandlers::iterator it;
+    for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
+         ++it) {
+      it->second->SetVerbose(this->ExtraVerbose);
+      it->second->SetSubmitIndex(this->SubmitIndex);
+    }
+    this->GetHandler("script")->SetVerbose(this->Verbose);
+    res = this->GetHandler("script")->ProcessHandler();
     if (res != 0) {
       cmCTestLog(this, DEBUG,
-                 "Running a test(s) failed returning : " << res << std::endl);
+                 "running script failing returning: " << res << std::endl);
     }
-    return res;
+
+  } else {
+    // What is this?  -V seems to be the same as -VV,
+    // and Verbose is always on in this case
+    this->ExtraVerbose = this->Verbose;
+    this->Verbose = true;
+    cmCTest::t_TestingHandlers::iterator it;
+    for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
+         ++it) {
+      it->second->SetVerbose(this->Verbose);
+      it->second->SetSubmitIndex(this->SubmitIndex);
+    }
+    std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
+    if (!this->Initialize(cwd.c_str(), CM_NULLPTR)) {
+      res = 12;
+      cmCTestLog(this, ERROR_MESSAGE, "Problem initializing the dashboard."
+                   << std::endl);
+    } else {
+      res = this->ProcessSteps();
+    }
+    this->Finalize();
+  }
+  if (res != 0) {
+    cmCTestLog(this, DEBUG,
+               "Running a test(s) failed returning : " << res << std::endl);
   }
+  return res;
+}
 
-  return 1;
+int cmCTest::RunCMakeAndTest(std::string* output)
+{
+  this->Verbose = true;
+  cmCTestBuildAndTestHandler* handler =
+    static_cast<cmCTestBuildAndTestHandler*>(this->GetHandler("buildtest"));
+  int retv = handler->ProcessHandler();
+  *output = handler->GetOutput();
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  cmDynamicLoader::FlushCache();
+#endif
+  if (retv != 0) {
+    cmCTestLog(this, DEBUG, "build and test failing returning: " << retv
+                                                                 << std::endl);
+  }
+  return retv;
 }
 
 void cmCTest::SetNotesFiles(const char* notes)
@@ -2325,7 +2346,7 @@ std::string cmCTest::GetShortPathToFile(const char* cfname)
   bool inBld = bldRelpath.find("..") == bldRelpath.npos;
   // TODO: Handle files with .. in their name
 
-  std::string* res = 0;
+  std::string* res = CM_NULLPTR;
 
   if (inSrc && inBld) {
     // If both have relative path with no dots, pick the shorter one
@@ -2375,7 +2396,7 @@ void cmCTest::EmptyCTestConfiguration()
 void cmCTest::DetermineNextDayStop()
 {
   struct tm* lctime;
-  time_t current_time = time(0);
+  time_t current_time = time(CM_NULLPTR);
   lctime = gmtime(&current_time);
   int gm_hour = lctime->tm_hour;
   time_t gm_time = mktime(lctime);
@@ -2459,7 +2480,7 @@ bool cmCTest::GetProduceXML()
 const char* cmCTest::GetSpecificTrack()
 {
   if (this->SpecificTrack.empty()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return this->SpecificTrack.c_str();
 }
@@ -2525,7 +2546,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
 {
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
 
-  if (args.size() < 1) {
+  if (args.empty()) {
     return false;
   }
 
@@ -2534,7 +2555,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
        a != args.end(); ++a) {
     argv.push_back(a->c_str());
   }
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   *stdOut = "";
   *stdErr = "";
@@ -2555,7 +2576,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
   int res;
   bool done = false;
   while (!done) {
-    res = cmsysProcess_WaitForData(cp, &data, &length, 0);
+    res = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR);
     switch (res) {
       case cmsysProcess_Pipe_STDOUT:
         tempOutput.insert(tempOutput.end(), data, data + length);
@@ -2572,7 +2593,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
     }
   }
 
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   if (!tempOutput.empty()) {
     stdOut->append(&*tempOutput.begin(), tempOutput.size());
   }
@@ -2614,7 +2635,7 @@ void cmCTest::SetOutputLogFileName(const char* name)
 {
   if (this->OutputLogFile) {
     delete this->OutputLogFile;
-    this->OutputLogFile = 0;
+    this->OutputLogFile = CM_NULLPTR;
   }
   if (name) {
     this->OutputLogFile = new cmGeneratedFileStream(name);
@@ -2628,7 +2649,7 @@ static const char* cmCTestStringLogType[] = { "DEBUG",
                                               "HANDLER_VERBOSE_OUTPUT",
                                               "WARNING",
                                               "ERROR_MESSAGE",
-                                              0 };
+                                              CM_NULLPTR };
 
 #ifdef cerr
 #undef cerr
@@ -2760,48 +2781,42 @@ bool cmCTest::CompressString(std::string& str)
   int ret;
   z_stream strm;
 
-  unsigned char* in =
-    reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
-  // zlib makes the guarantee that this is the maximum output size
-  int outSize =
-    static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
-  unsigned char* out = new unsigned char[outSize];
-
   strm.zalloc = Z_NULL;
   strm.zfree = Z_NULL;
   strm.opaque = Z_NULL;
   ret = deflateInit(&strm, -1); // default compression level
   if (ret != Z_OK) {
-    delete[] out;
     return false;
   }
 
+  unsigned char* in =
+    reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
+  // zlib makes the guarantee that this is the maximum output size
+  int outSize =
+    static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
+  std::vector<unsigned char> out(outSize);
+
   strm.avail_in = static_cast<uInt>(str.size());
   strm.next_in = in;
   strm.avail_out = outSize;
-  strm.next_out = out;
+  strm.next_out = &out[0];
   ret = deflate(&strm, Z_FINISH);
 
   if (ret == Z_STREAM_ERROR || ret != Z_STREAM_END) {
     cmCTestLog(this, ERROR_MESSAGE, "Error during gzip compression."
                  << std::endl);
-    delete[] out;
     return false;
   }
 
   (void)deflateEnd(&strm);
 
   // Now base64 encode the resulting binary string
-  unsigned char* base64EncodedBuffer = new unsigned char[(outSize * 3) / 2];
+  std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
 
   size_t rlen =
-    cmsysBase64_Encode(out, strm.total_out, base64EncodedBuffer, 1);
-
-  str = "";
-  str.append(reinterpret_cast<char*>(base64EncodedBuffer), rlen);
+    cmsysBase64_Encode(&out[0], strm.total_out, &base64EncodedBuffer[0], 1);
 
-  delete[] base64EncodedBuffer;
-  delete[] out;
+  str.assign(reinterpret_cast<char*>(&base64EncodedBuffer[0]), rlen);
 
   return true;
 }
diff --git a/Source/cmCTest.h b/Source/cmCTest.h
index 65ecaa4..8d3f8fb 100644
--- a/Source/cmCTest.h
+++ b/Source/cmCTest.h
@@ -1,30 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCTest_h
 #define cmCTest_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include "cmListFileCache.h"
+#include <cmsys/String.hxx>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string>
 #include <time.h>
+#include <vector>
 
-class cmake;
-class cmMakefile;
 class cmCTestGenericHandler;
-class cmGeneratedFileStream;
-class cmCTestCommand;
-class cmCTestScriptHandler;
 class cmCTestStartCommand;
+class cmGeneratedFileStream;
+class cmMakefile;
 class cmXMLWriter;
 
 #define cmCTestLog(ctSelf, logType, msg)                                      \
@@ -43,16 +35,13 @@ class cmXMLWriter;
                   cmCTestLog_msg.str().c_str(), suppress);                    \
   } while (0)
 
-#ifdef cerr
-#undef cerr
-#endif
-#define cerr no_cerr_use_cmCTestLog
-
-#ifdef cout
-#undef cout
-#endif
-#define cout no_cout_use_cmCTestLog
-
+/** \class cmCTest
+ * \brief Represents a ctest invocation.
+ *
+ * This class represents a ctest invocation. It is the top level class when
+ * running ctest.
+ *
+ */
 class cmCTest
 {
   friend class cmCTestRunTest;
@@ -119,8 +108,8 @@ public:
   typedef std::vector<cmsys::String> VectorOfStrings;
   typedef std::set<std::string> SetOfStrings;
 
-  ///! Process Command line arguments
-  int Run(std::vector<std::string>&, std::string* output = 0);
+  /** Process Command line arguments */
+  int Run(std::vector<std::string>&, std::string* output = CM_NULLPTR);
 
   /**
    * Initialize and finalize testing
@@ -129,23 +118,30 @@ public:
   void Finalize();
 
   /**
-   * Process the tests. This is the main routine. The execution of the
-   * tests should look like this:
+   * Process the dashboard client steps.
    *
+   * Steps are enabled using SetTest()
+   *
+   * The execution of the steps (or #Part) should look like this:
+   *
+   * /code
    * ctest foo;
    * foo.Initialize();
    * // Set some things on foo
-   * foo.ProcessTests();
+   * foo.ProcessSteps();
    * foo.Finalize();
+   * /endcode
+   *
+   * \sa Initialize(), Finalize(), Part, PartInfo, SetTest()
    */
-  int ProcessTests();
+  int ProcessSteps();
 
-  /*
+  /**
    * A utility function that returns the nightly time
    */
   struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag);
 
-  /*
+  /**
    * Is the tomorrow tag set?
    */
   bool GetTomorrowTag() { return this->TomorrowTag; }
@@ -155,14 +151,14 @@ public:
    */
   int TestDirectory(bool memcheck);
 
-  ///! what is the configuraiton type, e.g. Debug, Release etc.
+  /** what is the configuraiton type, e.g. Debug, Release etc. */
   std::string const& GetConfigType();
   double GetTimeOut() { return this->TimeOut; }
   void SetTimeOut(double t) { this->TimeOut = t; }
 
   double GetGlobalTimeout() { return this->GlobalTimeout; }
 
-  // how many test to run at the same time
+  /** how many test to run at the same time */
   int GetParallelLevel() { return this->ParallelLevel; }
   void SetParallelLevel(int);
 
@@ -200,19 +196,19 @@ public:
   cmCTest();
   ~cmCTest();
 
-  //! Set the notes files to be created.
+  /** Set the notes files to be created. */
   void SetNotesFiles(const char* notes);
 
   void PopulateCustomVector(cmMakefile* mf, const std::string& definition,
                             std::vector<std::string>& vec);
   void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val);
 
-  ///! Get the current time as string
+  /** Get the current time as string */
   std::string CurrentTime();
 
-  //! tar/gzip and then base 64 encode a file
+  /** tar/gzip and then base 64 encode a file */
   std::string Base64GzipEncodeFile(std::string const& file);
-  //! base64 encode a file
+  /** base64 encode a file */
   std::string Base64EncodeFile(std::string const& file);
 
   /**
@@ -222,11 +218,13 @@ public:
    */
   double GetRemainingTimeAllowed();
 
-  ///! Open file in the output directory and set the stream
+  /**
+   * Open file in the output directory and set the stream
+   */
   bool OpenOutputFile(const std::string& path, const std::string& name,
                       cmGeneratedFileStream& stream, bool compress = false);
 
-  ///! Should we only show what we would do?
+  /** Should we only show what we would do? */
   bool GetShowOnly();
 
   bool ShouldUseHTTP10() { return this->UseHTTP10; }
@@ -242,11 +240,11 @@ public:
   std::string GetStopTime() { return this->StopTime; }
   void SetStopTime(std::string const& time);
 
-  // Used for parallel ctest job scheduling
+  /** Used for parallel ctest job scheduling */
   std::string GetScheduleType() { return this->ScheduleType; }
   void SetScheduleType(std::string type) { this->ScheduleType = type; }
 
-  ///! The max output width
+  /** The max output width */
   int GetMaxTestNameWidth() const;
   void SetMaxTestNameWidth(int w) { this->MaxTestNameWidth = w; }
 
@@ -271,34 +269,40 @@ public:
    * escaped for this to with spaces.
    */
   bool RunCommand(const char* command, std::string* stdOut,
-                  std::string* stdErr, int* retVal = 0, const char* dir = 0,
-                  double timeout = 0.0);
+                  std::string* stdErr, int* retVal = CM_NULLPTR,
+                  const char* dir = CM_NULLPTR, double timeout = 0.0);
 
-  //! Clean/make safe for xml the given value such that it may be used as
-  // one of the key fields by CDash when computing the buildid.
+  /**
+   * Clean/make safe for xml the given value such that it may be used as
+   * one of the key fields by CDash when computing the buildid.
+   */
   static std::string SafeBuildIdField(const std::string& value);
 
-  //! Start CTest XML output file
+  /** Start CTest XML output file */
   void StartXML(cmXMLWriter& xml, bool append);
 
-  //! End CTest XML output file
+  /** End CTest XML output file */
   void EndXML(cmXMLWriter& xml);
 
-  //! Run command specialized for make and configure. Returns process status
-  // and retVal is return value or exception.
+  /**
+   * Run command specialized for make and configure. Returns process status
+   * and retVal is return value or exception.
+   */
   int RunMakeCommand(const char* command, std::string& output, int* retVal,
                      const char* dir, int timeout, std::ostream& ofs);
 
-  /*
-   * return the current tag
-   */
+  /** Return the current tag */
   std::string GetCurrentTag();
 
-  //! Get the path to the build tree
+  /** Get the path to the build tree */
   std::string GetBinaryDir();
 
-  //! Get the short path to the file. This means if the file is in binary or
-  // source directory, it will become /.../relative/path/to/file
+  /**
+   * Get the short path to the file.
+   *
+   * This means if the file is in binary or
+   * source directory, it will become /.../relative/path/to/file
+   */
   std::string GetShortPathToFile(const char* fname);
 
   enum
@@ -308,7 +312,7 @@ public:
     CONTINUOUS
   };
 
-  // provide some more detailed info on the return code for ctest
+  /** provide some more detailed info on the return code for ctest */
   enum
   {
     UPDATE_ERRORS = 0x01,
@@ -320,14 +324,16 @@ public:
     SUBMIT_ERRORS = 0x40
   };
 
-  ///! Are we producing XML
+  /** Are we producing XML */
   bool GetProduceXML();
   void SetProduceXML(bool v);
 
-  //! Run command specialized for tests. Returns process status and retVal is
-  // return value or exception. If environment is non-null, it is used to set
-  // environment variables prior to running the test. After running the test,
-  // environment variables are restored to their previous values.
+  /**
+   * Run command specialized for tests. Returns process status and retVal is
+   * return value or exception. If environment is non-null, it is used to set
+   * environment variables prior to running the test. After running the test,
+   * environment variables are restored to their previous values.
+   */
   int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
               std::ostream* logfile, double testTimeOut,
               std::vector<std::string>* environment);
@@ -338,13 +344,13 @@ public:
    */
   int ExecuteHandler(const char* handler);
 
-  /*
+  /**
    * Get the handler object
    */
   cmCTestGenericHandler* GetHandler(const char* handler);
   cmCTestGenericHandler* GetInitializedHandler(const char* handler);
 
-  /*
+  /**
    * Set the CTest variable from CMake variable
    */
   bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf,
@@ -352,37 +358,42 @@ public:
                                               const std::string& cmake_var,
                                               bool suppress = false);
 
-  //! Make string safe to be send as an URL
+  /** Make string safe to be send as an URL */
   static std::string MakeURLSafe(const std::string&);
 
   /** Decode a URL to the original string.  */
   static std::string DecodeURL(const std::string&);
 
-  //! Should ctect configuration be updated. When using new style ctest
-  // script, this should be true.
+  /**
+   * Should ctect configuration be updated. When using new style ctest
+   * script, this should be true.
+   */
   void SetSuppressUpdatingCTestConfiguration(bool val)
   {
     this->SuppressUpdatingCTestConfiguration = val;
   }
 
-  //! Add overwrite to ctest configuration.
-  // The format is key=value
+  /**
+   * Add overwrite to ctest configuration.
+   *
+   * The format is key=value
+   */
   void AddCTestConfigurationOverwrite(const std::string& encstr);
 
-  //! Create XML file that contains all the notes specified
+  /** Create XML file that contains all the notes specified */
   int GenerateNotesFile(const VectorOfStrings& files);
 
-  //! Submit extra files to the server
+  /** Submit extra files to the server */
   bool SubmitExtraFiles(const char* files);
   bool SubmitExtraFiles(const VectorOfStrings& files);
 
-  //! Set the output log file name
+  /** Set the output log file name */
   void SetOutputLogFileName(const char* name);
 
-  //! Set the visual studio or Xcode config type
+  /** Set the visual studio or Xcode config type */
   void SetConfigType(const char* ct);
 
-  //! Various log types
+  /** Various log types */
   enum
   {
     DEBUG = 0,
@@ -395,15 +406,15 @@ public:
     OTHER
   };
 
-  //! Add log to the output
+  /** Add log to the output */
   void Log(int logType, const char* file, int line, const char* msg,
            bool suppress = false);
 
-  //! Get the version of dart server
+  /** Get the version of dart server */
   int GetDartVersion() { return this->DartVersion; }
   int GetDropSiteCDash() { return this->DropSiteCDash; }
 
-  //! Add file to be submitted
+  /** Add file to be submitted */
   void AddSubmitFile(Part part, const char* name);
   std::vector<std::string> const& GetSubmitFiles(Part part)
   {
@@ -411,7 +422,9 @@ public:
   }
   void ClearSubmitFiles(Part part) { this->Parts[part].SubmitFiles.clear(); }
 
-  //! Read the custom configuration files and apply them to the current ctest
+  /**
+   * Read the custom configuration files and apply them to the current ctest
+   */
   int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf);
 
   std::vector<std::string>& GetInitialCommandLineArguments()
@@ -419,7 +432,7 @@ public:
     return this->InitialCommandLineArguments;
   }
 
-  //! Set the track to submit to
+  /** Set the track to submit to */
   void SetSpecificTrack(const char* track);
   const char* GetSpecificTrack();
 
@@ -447,10 +460,13 @@ public:
   {
     return this->Definitions;
   }
-  // return the number of times a test should be run
+
+  /** Return the number of times a test should be run */
   int GetTestRepeat() { return this->RepeatTests; }
-  // return true if test should run until fail
+
+  /** Return true if test should run until fail */
   bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
+
 private:
   int RepeatTests;
   bool RepeatUntilFail;
@@ -485,7 +501,7 @@ private:
 
   bool ShowOnly;
 
-  //! Map of configuration properties
+  /** Map of configuration properties */
   typedef std::map<std::string, std::string> CTestConfigurationMap;
 
   std::string CTestConfigFile;
@@ -549,36 +565,47 @@ private:
    */
   int Initialize(const char* binary_dir, cmCTestStartCommand* command);
 
-  //! parse the option after -D and convert it into the appropriate steps
+  /** parse the option after -D and convert it into the appropriate steps */
   bool AddTestsForDashboardType(std::string& targ);
 
-  //! read as "emit an error message for an unknown -D value"
+  /** read as "emit an error message for an unknown -D value" */
   void ErrorMessageUnknownDashDValue(std::string& val);
 
-  //! add a variable definition from a command line -D value
+  /** add a variable definition from a command line -D value */
   bool AddVariableDefinition(const std::string& arg);
 
-  //! parse and process most common command line arguments
+  /** parse and process most common command line arguments */
   bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args,
                                   std::string& errormsg);
 
-  //! hande the -S -SP and -SR arguments
+  /** hande the -S -SP and -SR arguments */
   void HandleScriptArguments(size_t& i, std::vector<std::string>& args,
                              bool& SRArgumentSpecified);
 
-  //! Reread the configuration file
+  /** Reread the configuration file */
   bool UpdateCTestConfiguration();
 
-  //! Create note from files.
+  /** Create note from files. */
   int GenerateCTestNotesOutput(cmXMLWriter& xml, const VectorOfStrings& files);
 
-  //! Check if the argument is the one specified
+  /** Check if the argument is the one specified */
   bool CheckArgument(const std::string& arg, const char* varg1,
-                     const char* varg2 = 0);
+                     const char* varg2 = CM_NULLPTR);
 
-  //! Output errors from a test
+  /** Output errors from a test */
   void OutputTestErrors(std::vector<char> const& process_output);
 
+  /** Handle the --test-action command line argument */
+  bool HandleTestActionArgument(const char* ctestExec, size_t& i,
+                                const std::vector<std::string>& args);
+
+  /** Handle the --test-model command line argument */
+  bool HandleTestModelArgument(const char* ctestExec, size_t& i,
+                               const std::vector<std::string>& args);
+
+  int RunCMakeAndTest(std::string* output);
+  int ExecuteTests();
+
   bool SuppressUpdatingCTestConfiguration;
 
   bool Debug;
diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx
index d143193..4b03499 100644
--- a/Source/cmCacheManager.cxx
+++ b/Source/cmCacheManager.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCacheManager.h"
 
 #include "cmGeneratedFileStream.h"
@@ -16,10 +7,12 @@
 #include "cmVersion.h"
 #include "cmake.h"
 
-#include <cmsys/Directory.hxx>
+#include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
 
 cmCacheManager::cmCacheManager()
 {
@@ -71,8 +64,9 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal,
     while (*realbuffer != '0' &&
            (*realbuffer == ' ' || *realbuffer == '\t' || *realbuffer == '\r' ||
             *realbuffer == '\n')) {
-      if (*realbuffer == '\n')
+      if (*realbuffer == '\n') {
         lineno++;
+      }
       realbuffer++;
     }
     // skip blank lines and comment lines
@@ -178,7 +172,7 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal,
 }
 
 const char* cmCacheManager::PersistentProperties[] = { "ADVANCED", "MODIFIED",
-                                                       "STRINGS", 0 };
+                                                       "STRINGS", CM_NULLPTR };
 
 bool cmCacheManager::ReadPropertyEntry(std::string const& entryKey,
                                        CacheEntry& e)
@@ -446,7 +440,7 @@ cmCacheManager::CacheEntry* cmCacheManager::GetCacheEntry(
   if (i != this->Cache.end()) {
     return &i->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmCacheManager::CacheIterator cmCacheManager::GetCacheIterator(const char* key)
@@ -461,7 +455,7 @@ const char* cmCacheManager::GetInitializedCacheValue(
   if (i != this->Cache.end() && i->second.Initialized) {
     return i->second.Value.c_str();
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmCacheManager::PrintCache(std::ostream& out) const
@@ -539,6 +533,11 @@ void cmCacheManager::CacheIterator::Next()
   }
 }
 
+std::vector<std::string> cmCacheManager::CacheIterator::GetPropertyList() const
+{
+  return this->GetEntry().GetPropertyList();
+}
+
 void cmCacheManager::CacheIterator::SetValue(const char* value)
 {
   if (this->IsAtEnd()) {
@@ -558,12 +557,18 @@ bool cmCacheManager::CacheIterator::GetValueAsBool() const
   return cmSystemTools::IsOn(this->GetEntry().Value.c_str());
 }
 
+std::vector<std::string> cmCacheManager::CacheEntry::GetPropertyList() const
+{
+  return this->Properties.GetPropertyList();
+}
+
 const char* cmCacheManager::CacheEntry::GetProperty(
   const std::string& prop) const
 {
   if (prop == "TYPE") {
     return cmState::CacheEntryTypeToString(this->Type);
-  } else if (prop == "VALUE") {
+  }
+  if (prop == "VALUE") {
     return this->Value.c_str();
   }
   return this->Properties.GetPropertyValue(prop);
@@ -605,7 +610,7 @@ const char* cmCacheManager::CacheIterator::GetProperty(
   if (!this->IsAtEnd()) {
     return this->GetEntry().GetProperty(prop);
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmCacheManager::CacheIterator::SetProperty(const std::string& p,
@@ -642,5 +647,5 @@ void cmCacheManager::CacheIterator::SetProperty(const std::string& p, bool v)
 bool cmCacheManager::CacheIterator::PropertyExists(
   const std::string& prop) const
 {
-  return this->GetProperty(prop) ? true : false;
+  return this->GetProperty(prop) != CM_NULLPTR;
 }
diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h
index e9b80cb..16a2e78 100644
--- a/Source/cmCacheManager.h
+++ b/Source/cmCacheManager.h
@@ -1,23 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCacheManager_h
 #define cmCacheManager_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmPropertyMap.h"
 #include "cmState.h"
 
-class cmMarkAsAdvancedCommand;
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+class cmake;
 
 /** \class cmCacheManager
  * \brief Control class for cmake's cache
@@ -38,6 +36,7 @@ private:
     std::string Value;
     cmState::CacheEntryType Type;
     cmPropertyMap Properties;
+    std::vector<std::string> GetPropertyList() const;
     const char* GetProperty(const std::string&) const;
     void SetProperty(const std::string& property, const char* value);
     void AppendProperty(const std::string& property, const char* value,
@@ -60,6 +59,7 @@ public:
     bool IsAtEnd() const;
     void Next();
     std::string GetName() const { return this->Position->first; }
+    std::vector<std::string> GetPropertyList() const;
     const char* GetProperty(const std::string&) const;
     bool GetPropertyAsBool(const std::string&) const;
     bool PropertyExists(const std::string&) const;
@@ -111,7 +111,7 @@ public:
   void PrintCache(std::ostream&) const;
 
   ///! Get the iterator for an entry with a given key.
-  cmCacheManager::CacheIterator GetCacheIterator(const char* key = 0);
+  cmCacheManager::CacheIterator GetCacheIterator(const char* key = CM_NULLPTR);
 
   ///! Remove an entry from the cache
   void RemoveCacheEntry(const std::string& key);
@@ -126,7 +126,7 @@ public:
   {
     cmCacheManager::CacheIterator it = this->GetCacheIterator(key.c_str());
     if (it.IsAtEnd()) {
-      return 0;
+      return CM_NULLPTR;
     }
     return it.GetValue();
   }
@@ -169,7 +169,8 @@ public:
   void RemoveCacheEntryProperty(std::string const& key,
                                 std::string const& propName)
   {
-    this->GetCacheIterator(key.c_str()).SetProperty(propName, (void*)0);
+    this->GetCacheIterator(key.c_str())
+      .SetProperty(propName, (void*)CM_NULLPTR);
   }
 
   void AppendCacheEntryProperty(std::string const& key,
diff --git a/Source/cmCallVisualStudioMacro.cxx b/Source/cmCallVisualStudioMacro.cxx
index e608d6b..a21a7d2 100644
--- a/Source/cmCallVisualStudioMacro.cxx
+++ b/Source/cmCallVisualStudioMacro.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCallVisualStudioMacro.h"
 
 #include "cmSystemTools.h"
@@ -105,8 +96,8 @@ HRESULT InstanceCallMacro(IDispatch* vsIDE, const std::string& macro,
       std::ostringstream oss;
       oss << std::endl;
       oss << "Invoke(ExecuteCommand)" << std::endl;
-      oss << "  Macro: " << macro.c_str() << std::endl;
-      oss << "  Args: " << args.c_str() << std::endl;
+      oss << "  Macro: " << macro << std::endl;
+      oss << "  Args: " << args << std::endl;
 
       if (DISP_E_EXCEPTION == hr) {
         oss << "DISP_E_EXCEPTION EXCEPINFO:" << excep.wCode << std::endl;
diff --git a/Source/cmCallVisualStudioMacro.h b/Source/cmCallVisualStudioMacro.h
index e516fe2..7ff4513 100644
--- a/Source/cmCallVisualStudioMacro.h
+++ b/Source/cmCallVisualStudioMacro.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCallVisualStudioMacro_h
 #define cmCallVisualStudioMacro_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmCallVisualStudioMacro
diff --git a/Source/cmCommand.h b/Source/cmCommand.h
index 0157293..d8e337d 100644
--- a/Source/cmCommand.h
+++ b/Source/cmCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommand_h
 #define cmCommand_h
 
@@ -38,14 +29,14 @@ public:
    */
   cmCommand()
   {
-    this->Makefile = 0;
+    this->Makefile = CM_NULLPTR;
     this->Enabled = true;
   }
 
   /**
    * Need virtual destructor to destroy real command type.
    */
-  virtual ~cmCommand() {}
+  ~cmCommand() CM_OVERRIDE {}
 
   /**
    * Specify the makefile.
diff --git a/Source/cmCommandArgumentLexer.cxx b/Source/cmCommandArgumentLexer.cxx
index e23ef8a..fe460ba 100644
--- a/Source/cmCommandArgumentLexer.cxx
+++ b/Source/cmCommandArgumentLexer.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmStandardIncludes.h"
 
 #line 2 "cmCommandArgumentLexer.cxx"
@@ -462,17 +453,8 @@ static yyconst flex_int16_t yy_chk[53] =
 #define YY_RESTORE_YY_MORE_OFFSET
 #line 1 "cmCommandArgumentLexer.in.l"
 #line 2 "cmCommandArgumentLexer.in.l"
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmCommandArgumentLexer.h b/Source/cmCommandArgumentLexer.h
index 2ea3fa2..7234fe1 100644
--- a/Source/cmCommandArgumentLexer.h
+++ b/Source/cmCommandArgumentLexer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommandArgument_yyHEADER_H
 #define cmCommandArgument_yyHEADER_H 1
 #define cmCommandArgument_yyIN_HEADER 1
diff --git a/Source/cmCommandArgumentLexer.in.l b/Source/cmCommandArgumentLexer.in.l
index 24a0eec..eb9d08c 100644
--- a/Source/cmCommandArgumentLexer.in.l
+++ b/Source/cmCommandArgumentLexer.in.l
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmCommandArgumentParser.cxx b/Source/cmCommandArgumentParser.cxx
index 9f8a4de..e384f21 100644
--- a/Source/cmCommandArgumentParser.cxx
+++ b/Source/cmCommandArgumentParser.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /* A Bison parser, made by GNU Bison 2.3.  */
 
 /* Skeleton implementation for Bison's Yacc-like parsers in C
@@ -119,17 +110,8 @@
 /* Copy the first part of user declarations.  */
 #line 1 "cmCommandArgumentParser.y"
 
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmCommandArgumentParser.y b/Source/cmCommandArgumentParser.y
index b1d53f6..b2f4b1b 100644
--- a/Source/cmCommandArgumentParser.y
+++ b/Source/cmCommandArgumentParser.y
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx
index a4f3c7d..2d66344 100644
--- a/Source/cmCommandArgumentParserHelper.cxx
+++ b/Source/cmCommandArgumentParserHelper.cxx
@@ -1,22 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommandArgumentParserHelper.h"
 
+#include <cm_kwiml.h>
+
+#include "cmCommandArgumentLexer.h"
 #include "cmMakefile.h"
-#include "cmOutputConverter.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmake.h"
 
-#include "cmCommandArgumentLexer.h"
+#include <cmConfigure.h>
+#include <iostream>
+#include <sstream>
+#include <string.h>
 
 int cmCommandArgument_yyparse(yyscan_t yyscanner);
 //
@@ -25,7 +22,7 @@ cmCommandArgumentParserHelper::cmCommandArgumentParserHelper()
   this->WarnUninitialized = false;
   this->CheckSystemVars = false;
   this->FileLine = -1;
-  this->FileName = 0;
+  this->FileName = CM_NULLPTR;
   this->RemoveEmpty = true;
   this->EmptyVariable[0] = 0;
   strcpy(this->DCURLYVariable, "${");
@@ -71,13 +68,12 @@ char* cmCommandArgumentParserHelper::ExpandSpecialVariable(const char* key,
     return this->EmptyVariable;
   }
   if (strcmp(key, "ENV") == 0) {
-    char* ptr = getenv(var);
-    if (ptr) {
+    std::string str;
+    if (cmSystemTools::GetEnv(var, str)) {
       if (this->EscapeQuotes) {
-        return this->AddString(cmSystemTools::EscapeQuotes(ptr));
-      } else {
-        return ptr;
+        return this->AddString(cmSystemTools::EscapeQuotes(str));
       }
+      return this->AddString(str);
     }
     return this->EmptyVariable;
   }
@@ -86,9 +82,8 @@ char* cmCommandArgumentParserHelper::ExpandSpecialVariable(const char* key,
           this->Makefile->GetState()->GetInitializedCacheValue(var)) {
       if (this->EscapeQuotes) {
         return this->AddString(cmSystemTools::EscapeQuotes(c));
-      } else {
-        return this->AddString(c);
       }
+      return this->AddString(c);
     }
     return this->EmptyVariable;
   }
@@ -96,13 +91,13 @@ char* cmCommandArgumentParserHelper::ExpandSpecialVariable(const char* key,
   e << "Syntax $" << key << "{} is not supported.  "
     << "Only ${}, $ENV{}, and $CACHE{} are allowed.";
   this->SetError(e.str());
-  return 0;
+  return CM_NULLPTR;
 }
 
 char* cmCommandArgumentParserHelper::ExpandVariable(const char* var)
 {
   if (!var) {
-    return 0;
+    return CM_NULLPTR;
   }
   if (this->FileLine >= 0 && strcmp(var, "CMAKE_CURRENT_LIST_LINE") == 0) {
     std::ostringstream ostr;
@@ -125,7 +120,7 @@ char* cmCommandArgumentParserHelper::ExpandVariable(const char* var)
         this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
       }
     }
-    return 0;
+    return CM_NULLPTR;
   }
   if (this->EscapeQuotes && value) {
     return this->AddString(cmSystemTools::EscapeQuotes(value));
@@ -162,7 +157,8 @@ char* cmCommandArgumentParserHelper::CombineUnions(char* in1, char* in2)
 {
   if (!in1) {
     return in2;
-  } else if (!in2) {
+  }
+  if (!in2) {
     return in1;
   }
   size_t len = strlen(in1) + strlen(in2) + 1;
@@ -176,7 +172,7 @@ char* cmCommandArgumentParserHelper::CombineUnions(char* in1, char* in2)
 void cmCommandArgumentParserHelper::AllocateParserType(
   cmCommandArgumentParserHelper::ParserType* pt, const char* str, int len)
 {
-  pt->str = 0;
+  pt->str = CM_NULLPTR;
   if (len == 0) {
     len = static_cast<int>(strlen(str));
   }
@@ -282,10 +278,9 @@ int cmCommandArgumentParserHelper::LexInput(char* buf, int maxlen)
       this->CurrentLine++;
     }
     return (1);
-  } else {
-    buf[0] = '\n';
-    return (0);
   }
+  buf[0] = '\n';
+  return (0);
 }
 
 void cmCommandArgumentParserHelper::Error(const char* str)
diff --git a/Source/cmCommandArgumentParserHelper.h b/Source/cmCommandArgumentParserHelper.h
index 97b706c..95bf0ad 100644
--- a/Source/cmCommandArgumentParserHelper.h
+++ b/Source/cmCommandArgumentParserHelper.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommandArgumentParserHelper_h
 #define cmCommandArgumentParserHelper_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 #define YYSTYPE cmCommandArgumentParserHelper::ParserType
 #define YYSTYPE_IS_DECLARED
diff --git a/Source/cmCommandArgumentParserTokens.h b/Source/cmCommandArgumentParserTokens.h
index 7fb58e2..d162b82 100644
--- a/Source/cmCommandArgumentParserTokens.h
+++ b/Source/cmCommandArgumentParserTokens.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /* A Bison parser, made by GNU Bison 2.3.  */
 
 /* Skeleton interface for Bison's Yacc-like parsers in C
diff --git a/Source/cmCommandArgumentsHelper.cxx b/Source/cmCommandArgumentsHelper.cxx
index c336bc5..babddbe 100644
--- a/Source/cmCommandArgumentsHelper.cxx
+++ b/Source/cmCommandArgumentsHelper.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommandArgumentsHelper.h"
 
 cmCommandArgument::cmCommandArgument(cmCommandArgumentsHelper* args,
@@ -21,11 +11,11 @@ cmCommandArgument::cmCommandArgument(cmCommandArgumentsHelper* args,
   , ArgumentsBeforeEmpty(true)
   , CurrentIndex(0)
 {
-  if (args != 0) {
+  if (args != CM_NULLPTR) {
     args->AddArgument(this);
   }
 
-  if (this->Group != 0) {
+  if (this->Group != CM_NULLPTR) {
     this->Group->ContainedArguments.push_back(this);
   }
 }
@@ -45,7 +35,7 @@ void cmCommandArgument::Follows(const cmCommandArgument* arg)
 
 void cmCommandArgument::FollowsGroup(const cmCommandArgumentGroup* group)
 {
-  if (group != 0) {
+  if (group != CM_NULLPTR) {
     this->ArgumentsBeforeEmpty = false;
     this->ArgumentsBefore.insert(group->ContainedArguments.begin(),
                                  group->ContainedArguments.end());
@@ -57,19 +47,12 @@ bool cmCommandArgument::MayFollow(const cmCommandArgument* current) const
   if (this->ArgumentsBeforeEmpty) {
     return true;
   }
-
-  std::set<const cmCommandArgument*>::const_iterator argIt =
-    this->ArgumentsBefore.find(current);
-  if (argIt != this->ArgumentsBefore.end()) {
-    return true;
-  }
-
-  return false;
+  return this->ArgumentsBefore.find(current) != this->ArgumentsBefore.end();
 }
 
 bool cmCommandArgument::KeyMatches(const std::string& key) const
 {
-  if ((this->Key == 0) || (this->Key[0] == '\0')) {
+  if ((this->Key == CM_NULLPTR) || (this->Key[0] == '\0')) {
     return true;
   }
   return (key == this->Key);
@@ -77,7 +60,7 @@ bool cmCommandArgument::KeyMatches(const std::string& key) const
 
 void cmCommandArgument::ApplyOwnGroup()
 {
-  if (this->Group != 0) {
+  if (this->Group != CM_NULLPTR) {
     for (std::vector<cmCommandArgument*>::const_iterator it =
            this->Group->ContainedArguments.begin();
          it != this->Group->ContainedArguments.end(); ++it) {
@@ -105,9 +88,9 @@ cmCAStringVector::cmCAStringVector(cmCommandArgumentsHelper* args,
                                    const char* key,
                                    cmCommandArgumentGroup* group)
   : cmCommandArgument(args, key, group)
-  , Ignore(0)
+  , Ignore(CM_NULLPTR)
 {
-  if ((key == 0) || (*key == 0)) {
+  if ((key == CM_NULLPTR) || (*key == 0)) {
     this->DataStart = 0;
   } else {
     this->DataStart = 1;
@@ -117,7 +100,7 @@ cmCAStringVector::cmCAStringVector(cmCommandArgumentsHelper* args,
 bool cmCAStringVector::DoConsume(const std::string& arg, unsigned int index)
 {
   if (index >= this->DataStart) {
-    if ((this->Ignore == 0) || (arg != this->Ignore)) {
+    if ((this->Ignore == CM_NULLPTR) || (arg != this->Ignore)) {
       this->Vector.push_back(arg);
     }
   }
@@ -134,7 +117,7 @@ cmCAString::cmCAString(cmCommandArgumentsHelper* args, const char* key,
                        cmCommandArgumentGroup* group)
   : cmCommandArgument(args, key, group)
 {
-  if ((key == 0) || (*key == 0)) {
+  if ((key == CM_NULLPTR) || (*key == 0)) {
     this->DataStart = 0;
   } else {
     this->DataStart = 1;
@@ -216,7 +199,7 @@ void cmCommandArgumentGroup::FollowsGroup(const cmCommandArgumentGroup* group)
 void cmCommandArgumentsHelper::Parse(const std::vector<std::string>* args,
                                      std::vector<std::string>* unconsumedArgs)
 {
-  if (args == 0) {
+  if (args == CM_NULLPTR) {
     return;
   }
 
@@ -227,8 +210,8 @@ void cmCommandArgumentsHelper::Parse(const std::vector<std::string>* args,
     (*argIt)->Reset();
   }
 
-  cmCommandArgument* activeArgument = 0;
-  const cmCommandArgument* previousArgument = 0;
+  cmCommandArgument* activeArgument = CM_NULLPTR;
+  const cmCommandArgument* previousArgument = CM_NULLPTR;
   for (std::vector<std::string>::const_iterator it = args->begin();
        it != args->end(); ++it) {
     for (std::vector<cmCommandArgument*>::iterator argIt =
@@ -246,10 +229,10 @@ void cmCommandArgumentsHelper::Parse(const std::vector<std::string>* args,
       bool argDone = activeArgument->Consume(*it);
       previousArgument = activeArgument;
       if (argDone) {
-        activeArgument = 0;
+        activeArgument = CM_NULLPTR;
       }
     } else {
-      if (unconsumedArgs != 0) {
+      if (unconsumedArgs != CM_NULLPTR) {
         unconsumedArgs->push_back(*it);
       }
     }
diff --git a/Source/cmCommandArgumentsHelper.h b/Source/cmCommandArgumentsHelper.h
index c2a6f92..50af2e2 100644
--- a/Source/cmCommandArgumentsHelper.h
+++ b/Source/cmCommandArgumentsHelper.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommandArgumentsHelper_h
 #define cmCommandArgumentsHelper_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmCommandArgumentsHelper;
@@ -43,7 +36,7 @@ class cmCommandArgument
 {
 public:
   cmCommandArgument(cmCommandArgumentsHelper* args, const char* key,
-                    cmCommandArgumentGroup* group = 0);
+                    cmCommandArgumentGroup* group = CM_NULLPTR);
   virtual ~cmCommandArgument() {}
 
   /// this argument may follow after arg. 0 means it comes first.
@@ -95,7 +88,7 @@ class cmCAStringVector : public cmCommandArgument
 {
 public:
   cmCAStringVector(cmCommandArgumentsHelper* args, const char* key,
-                   cmCommandArgumentGroup* group = 0);
+                   cmCommandArgumentGroup* group = CM_NULLPTR);
 
   /// Return the vector of strings
   const std::vector<std::string>& GetVector() const { return this->Vector; }
@@ -108,8 +101,8 @@ private:
   unsigned int DataStart;
   const char* Ignore;
   cmCAStringVector();
-  virtual bool DoConsume(const std::string& arg, unsigned int index);
-  virtual void DoReset();
+  bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
+  void DoReset() CM_OVERRIDE;
 };
 
 /** cmCAString is to be used for arguments which consist of one value,
@@ -118,7 +111,7 @@ class cmCAString : public cmCommandArgument
 {
 public:
   cmCAString(cmCommandArgumentsHelper* args, const char* key,
-             cmCommandArgumentGroup* group = 0);
+             cmCommandArgumentGroup* group = CM_NULLPTR);
 
   /// Return the string
   const std::string& GetString() const { return this->String; }
@@ -126,8 +119,8 @@ public:
 private:
   std::string String;
   unsigned int DataStart;
-  virtual bool DoConsume(const std::string& arg, unsigned int index);
-  virtual void DoReset();
+  bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
+  void DoReset() CM_OVERRIDE;
   cmCAString();
 };
 
@@ -137,14 +130,14 @@ class cmCAEnabler : public cmCommandArgument
 {
 public:
   cmCAEnabler(cmCommandArgumentsHelper* args, const char* key,
-              cmCommandArgumentGroup* group = 0);
+              cmCommandArgumentGroup* group = CM_NULLPTR);
 
   /// Has it been enabled ?
   bool IsEnabled() const { return this->Enabled; }
 private:
   bool Enabled;
-  virtual bool DoConsume(const std::string& arg, unsigned int index);
-  virtual void DoReset();
+  bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
+  void DoReset() CM_OVERRIDE;
   cmCAEnabler();
 };
 
@@ -154,14 +147,14 @@ class cmCADisabler : public cmCommandArgument
 {
 public:
   cmCADisabler(cmCommandArgumentsHelper* args, const char* key,
-               cmCommandArgumentGroup* group = 0);
+               cmCommandArgumentGroup* group = CM_NULLPTR);
 
   /// Is it still enabled ?
   bool IsEnabled() const { return this->Enabled; }
 private:
   bool Enabled;
-  virtual bool DoConsume(const std::string& arg, unsigned int index);
-  virtual void DoReset();
+  bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
+  void DoReset() CM_OVERRIDE;
   cmCADisabler();
 };
 
diff --git a/Source/cmCommands.cxx.in b/Source/cmCommands.cxx.in
index e23bbd1..9eddf30 100644
--- a/Source/cmCommands.cxx.in
+++ b/Source/cmCommands.cxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommands.h"
 
 @COMMAND_INCLUDES@
diff --git a/Source/cmCommands.h b/Source/cmCommands.h
index d0f1ab7..c2a59b8 100644
--- a/Source/cmCommands.h
+++ b/Source/cmCommands.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommands_h
 #define cmCommands_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <vector>
 
diff --git a/Source/cmCommandsForBootstrap.cxx b/Source/cmCommandsForBootstrap.cxx
index 5f397a1..1b3bf51 100644
--- a/Source/cmCommandsForBootstrap.cxx
+++ b/Source/cmCommandsForBootstrap.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommands.h"
 
 void GetPredefinedCommands(std::vector<cmCommand*>&)
diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx
index c630971..6887a31 100644
--- a/Source/cmCommonTargetGenerator.cxx
+++ b/Source/cmCommonTargetGenerator.cxx
@@ -1,35 +1,31 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommonTargetGenerator.h"
 
+#include <algorithm>
+#include <cmConfigure.h>
+#include <set>
+#include <sstream>
+#include <utility>
+
+#include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalCommonGenerator.h"
 #include "cmLocalCommonGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmSystemTools.h"
+#include "cmState.h"
 
-cmCommonTargetGenerator::cmCommonTargetGenerator(
-  cmOutputConverter::RelativeRoot wd, cmGeneratorTarget* gt)
-  : WorkingDirectory(wd)
-  , GeneratorTarget(gt)
+cmCommonTargetGenerator::cmCommonTargetGenerator(cmGeneratorTarget* gt)
+  : GeneratorTarget(gt)
   , Makefile(gt->Makefile)
   , LocalGenerator(static_cast<cmLocalCommonGenerator*>(gt->LocalGenerator))
   , GlobalGenerator(static_cast<cmGlobalCommonGenerator*>(
       gt->LocalGenerator->GetGlobalGenerator()))
   , ConfigName(LocalGenerator->GetConfigName())
   , ModuleDefinitionFile(GeneratorTarget->GetModuleDefinitionFile(ConfigName))
-  , FortranModuleDirectoryComputed(false)
 {
 }
 
@@ -42,13 +38,6 @@ std::string const& cmCommonTargetGenerator::GetConfigName() const
   return this->ConfigName;
 }
 
-std::string cmCommonTargetGenerator::Convert(
-  std::string const& source, cmOutputConverter::RelativeRoot relative,
-  cmOutputConverter::OutputFormat output)
-{
-  return this->LocalGenerator->Convert(source, relative, output);
-}
-
 const char* cmCommonTargetGenerator::GetFeature(const std::string& feature)
 {
   return this->GeneratorTarget->GetFeature(feature, this->ConfigName);
@@ -91,99 +80,17 @@ void cmCommonTargetGenerator::AddModuleDefinitionFlag(std::string& flags)
   this->LocalGenerator->AppendFlags(flags, flag);
 }
 
-std::string cmCommonTargetGenerator::ComputeFortranModuleDirectory() const
-{
-  std::string mod_dir;
-  const char* target_mod_dir =
-    this->GeneratorTarget->GetProperty("Fortran_MODULE_DIRECTORY");
-  const char* moddir_flag =
-    this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
-  if (target_mod_dir && moddir_flag) {
-    // Compute the full path to the module directory.
-    if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
-      // Already a full path.
-      mod_dir = target_mod_dir;
-    } else {
-      // Interpret relative to the current output directory.
-      mod_dir = this->LocalGenerator->GetCurrentBinaryDirectory();
-      mod_dir += "/";
-      mod_dir += target_mod_dir;
-    }
-
-    // Make sure the module output directory exists.
-    cmSystemTools::MakeDirectory(mod_dir);
-  }
-  return mod_dir;
-}
-
-std::string cmCommonTargetGenerator::GetFortranModuleDirectory()
-{
-  // Compute the module directory.
-  if (!this->FortranModuleDirectoryComputed) {
-    this->FortranModuleDirectoryComputed = true;
-    this->FortranModuleDirectory = this->ComputeFortranModuleDirectory();
-  }
-
-  // Return the computed directory.
-  return this->FortranModuleDirectory;
-}
-
-void cmCommonTargetGenerator::AddFortranFlags(std::string& flags)
-{
-  // Enable module output if necessary.
-  if (const char* modout_flag =
-        this->Makefile->GetDefinition("CMAKE_Fortran_MODOUT_FLAG")) {
-    this->LocalGenerator->AppendFlags(flags, modout_flag);
-  }
-
-  // Add a module output directory flag if necessary.
-  std::string mod_dir = this->GetFortranModuleDirectory();
-  if (!mod_dir.empty()) {
-    mod_dir =
-      this->Convert(mod_dir, this->WorkingDirectory, cmOutputConverter::SHELL);
-  } else {
-    mod_dir =
-      this->Makefile->GetSafeDefinition("CMAKE_Fortran_MODDIR_DEFAULT");
-  }
-  if (!mod_dir.empty()) {
-    const char* moddir_flag =
-      this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG");
-    std::string modflag = moddir_flag;
-    modflag += mod_dir;
-    this->LocalGenerator->AppendFlags(flags, modflag);
-  }
-
-  // If there is a separate module path flag then duplicate the
-  // include path with it.  This compiler does not search the include
-  // path for modules.
-  if (const char* modpath_flag =
-        this->Makefile->GetDefinition("CMAKE_Fortran_MODPATH_FLAG")) {
-    std::vector<std::string> includes;
-    const std::string& config =
-      this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-    this->LocalGenerator->GetIncludeDirectories(
-      includes, this->GeneratorTarget, "C", config);
-    for (std::vector<std::string>::const_iterator idi = includes.begin();
-         idi != includes.end(); ++idi) {
-      std::string flg = modpath_flag;
-      flg +=
-        this->Convert(*idi, cmOutputConverter::NONE, cmOutputConverter::SHELL);
-      this->LocalGenerator->AppendFlags(flags, flg);
-    }
-  }
-}
-
 void cmCommonTargetGenerator::AppendFortranFormatFlags(
   std::string& flags, cmSourceFile const& source)
 {
   const char* srcfmt = source.GetProperty("Fortran_FORMAT");
   cmOutputConverter::FortranFormat format =
-    this->LocalGenerator->GetFortranFormat(srcfmt);
+    cmOutputConverter::GetFortranFormat(srcfmt);
   if (format == cmOutputConverter::FortranFormatNone) {
     const char* tgtfmt = this->GeneratorTarget->GetProperty("Fortran_FORMAT");
-    format = this->LocalGenerator->GetFortranFormat(tgtfmt);
+    format = cmOutputConverter::GetFortranFormat(tgtfmt);
   }
-  const char* var = 0;
+  const char* var = CM_NULLPTR;
   switch (format) {
     case cmOutputConverter::FortranFormatFixed:
       var = "CMAKE_Fortran_FORMAT_FIXED_FLAG";
@@ -200,91 +107,14 @@ void cmCommonTargetGenerator::AppendFortranFormatFlags(
   }
 }
 
-std::string cmCommonTargetGenerator::GetFrameworkFlags(std::string const& l)
-{
-  if (!this->Makefile->IsOn("APPLE")) {
-    return std::string();
-  }
-
-  std::string fwSearchFlagVar = "CMAKE_" + l + "_FRAMEWORK_SEARCH_FLAG";
-  const char* fwSearchFlag = this->Makefile->GetDefinition(fwSearchFlagVar);
-  if (!(fwSearchFlag && *fwSearchFlag)) {
-    return std::string();
-  }
-
-  std::set<std::string> emitted;
-#ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
-  emitted.insert("/System/Library/Frameworks");
-#endif
-  std::vector<std::string> includes;
-
-  const std::string& config =
-    this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-  this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
-                                              "C", config);
-  // check all include directories for frameworks as this
-  // will already have added a -F for the framework
-  for (std::vector<std::string>::iterator i = includes.begin();
-       i != includes.end(); ++i) {
-    if (this->GlobalGenerator->NameResolvesToFramework(*i)) {
-      std::string frameworkDir = *i;
-      frameworkDir += "/../";
-      frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
-      emitted.insert(frameworkDir);
-    }
-  }
-
-  std::string flags;
-  const char* cfg = this->LocalGenerator->GetConfigName().c_str();
-  if (cmComputeLinkInformation* cli =
-        this->GeneratorTarget->GetLinkInformation(cfg)) {
-    std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
-    for (std::vector<std::string>::const_iterator i = frameworks.begin();
-         i != frameworks.end(); ++i) {
-      if (emitted.insert(*i).second) {
-        flags += fwSearchFlag;
-        flags += this->LocalGenerator->ConvertToOutputFormat(
-          *i, cmOutputConverter::SHELL);
-        flags += " ";
-      }
-    }
-  }
-  return flags;
-}
-
 std::string cmCommonTargetGenerator::GetFlags(const std::string& l)
 {
   ByLanguageMap::iterator i = this->FlagsByLanguage.find(l);
   if (i == this->FlagsByLanguage.end()) {
     std::string flags;
-    const char* lang = l.c_str();
-
-    // Add language feature flags.
-    this->AddFeatureFlags(flags, lang);
-
-    this->LocalGenerator->AddArchitectureFlags(flags, this->GeneratorTarget,
-                                               lang, this->ConfigName);
-
-    // Fortran-specific flags computed for this target.
-    if (l == "Fortran") {
-      this->AddFortranFlags(flags);
-    }
 
-    this->LocalGenerator->AddCMP0018Flags(flags, this->GeneratorTarget, lang,
-                                          this->ConfigName);
-
-    this->LocalGenerator->AddVisibilityPresetFlags(
-      flags, this->GeneratorTarget, lang);
-
-    // Append old-style preprocessor definition flags.
-    this->LocalGenerator->AppendFlags(flags, this->Makefile->GetDefineFlags());
-
-    // Add framework directory flags.
-    this->LocalGenerator->AppendFlags(flags, this->GetFrameworkFlags(l));
-
-    // Add target-specific flags.
-    this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, lang,
-                                            this->ConfigName);
+    this->LocalGenerator->GetTargetCompileFlags(this->GeneratorTarget,
+                                                this->ConfigName, l, flags);
 
     ByLanguageMap::value_type entry(l, flags);
     i = this->FlagsByLanguage.insert(entry).first;
@@ -297,19 +127,11 @@ std::string cmCommonTargetGenerator::GetDefines(const std::string& l)
   ByLanguageMap::iterator i = this->DefinesByLanguage.find(l);
   if (i == this->DefinesByLanguage.end()) {
     std::set<std::string> defines;
-    const char* lang = l.c_str();
-    // Add the export symbol definition for shared library objects.
-    if (const char* exportMacro = this->GeneratorTarget->GetExportMacro()) {
-      this->LocalGenerator->AppendDefines(defines, exportMacro);
-    }
-
-    // Add preprocessor definitions for this target and configuration.
-    this->LocalGenerator->AddCompileDefinitions(
-      defines, this->GeneratorTarget, this->LocalGenerator->GetConfigName(),
-      l);
+    this->LocalGenerator->GetTargetDefines(this->GeneratorTarget,
+                                           this->ConfigName, l, defines);
 
     std::string definesString;
-    this->LocalGenerator->JoinDefines(defines, definesString, lang);
+    this->LocalGenerator->JoinDefines(defines, definesString, l);
 
     ByLanguageMap::value_type entry(l, definesString);
     i = this->DefinesByLanguage.insert(entry).first;
@@ -366,8 +188,10 @@ std::string cmCommonTargetGenerator::GetManifests()
   std::vector<std::string> manifests;
   for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin();
        mi != manifest_srcs.end(); ++mi) {
-    manifests.push_back(this->Convert(
-      (*mi)->GetFullPath(), this->WorkingDirectory, cmOutputConverter::SHELL));
+    manifests.push_back(this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetWorkingDirectory(), (*mi)->GetFullPath()),
+      cmOutputConverter::SHELL));
   }
 
   return cmJoin(manifests, " ");
diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h
index c9645e7..707b81e 100644
--- a/Source/cmCommonTargetGenerator.h
+++ b/Source/cmCommonTargetGenerator.h
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommonTargetGenerator_h
 #define cmCommonTargetGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmLocalGenerator.h"
+#include "cmOutputConverter.h"
+
+#include <map>
+#include <string>
+#include <vector>
 
 class cmGeneratorTarget;
 class cmGlobalCommonGenerator;
@@ -28,8 +23,7 @@ class cmSourceFile;
 class cmCommonTargetGenerator
 {
 public:
-  cmCommonTargetGenerator(cmOutputConverter::RelativeRoot wd,
-                          cmGeneratorTarget* gt);
+  cmCommonTargetGenerator(cmGeneratorTarget* gt);
   virtual ~cmCommonTargetGenerator();
 
   std::string const& GetConfigName() const;
@@ -45,7 +39,6 @@ protected:
   // Helper to add flag for windows .def file.
   void AddModuleDefinitionFlag(std::string& flags);
 
-  cmOutputConverter::RelativeRoot WorkingDirectory;
   cmGeneratorTarget* GeneratorTarget;
   cmMakefile* Makefile;
   cmLocalCommonGenerator* LocalGenerator;
@@ -55,25 +48,9 @@ protected:
   // The windows module definition source file (.def), if any.
   cmSourceFile const* ModuleDefinitionFile;
 
-  // Target-wide Fortran module output directory.
-  bool FortranModuleDirectoryComputed;
-  std::string FortranModuleDirectory;
-  std::string GetFortranModuleDirectory();
-  virtual std::string ComputeFortranModuleDirectory() const;
-
-  // Compute target-specific Fortran language flags.
-  void AddFortranFlags(std::string& flags);
-
-  std::string Convert(
-    std::string const& source, cmOutputConverter::RelativeRoot relative,
-    cmOutputConverter::OutputFormat output = cmOutputConverter::UNCHANGED);
-
   void AppendFortranFormatFlags(std::string& flags,
                                 cmSourceFile const& source);
 
-  // Return the a string with -F flags on apple
-  std::string GetFrameworkFlags(std::string const& l);
-
   virtual void AddIncludeFlags(std::string& flags,
                                std::string const& lang) = 0;
 
diff --git a/Source/cmComputeComponentGraph.cxx b/Source/cmComputeComponentGraph.cxx
index 4f21c3a..a02d885 100644
--- a/Source/cmComputeComponentGraph.cxx
+++ b/Source/cmComputeComponentGraph.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmComputeComponentGraph.h"
 
 #include <algorithm>
diff --git a/Source/cmComputeComponentGraph.h b/Source/cmComputeComponentGraph.h
index fb95f9a..608dedc 100644
--- a/Source/cmComputeComponentGraph.h
+++ b/Source/cmComputeComponentGraph.h
@@ -1,22 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmComputeComponentGraph_h
 #define cmComputeComponentGraph_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmGraphAdjacencyList.h"
 
 #include <stack>
+#include <vector>
 
 /** \class cmComputeComponentGraph
  * \brief Analyze a graph to determine strongly connected components.
diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx
index 2129394..93f3289 100644
--- a/Source/cmComputeLinkDepends.cxx
+++ b/Source/cmComputeLinkDepends.cxx
@@ -1,25 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmComputeLinkDepends.h"
 
 #include "cmAlgorithms.h"
 #include "cmComputeComponentGraph.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmake.h"
 
+#include <algorithm>
 #include <assert.h>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+#include <utility>
 
 /*
 
@@ -194,7 +194,7 @@ cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target,
   this->OldLinkDirMode = false;
 
   // No computation has been done.
-  this->CCG = 0;
+  this->CCG = CM_NULLPTR;
 }
 
 cmComputeLinkDepends::~cmComputeLinkDepends()
@@ -286,7 +286,7 @@ std::map<std::string, int>::iterator cmComputeLinkDepends::AllocateLinkEntry(
   std::map<std::string, int>::iterator lei =
     this->LinkEntryIndex.insert(index_entry).first;
   this->EntryList.push_back(LinkEntry());
-  this->InferredDependSets.push_back(0);
+  this->InferredDependSets.push_back(CM_NULLPTR);
   this->EntryConstraintGraph.push_back(EdgeList());
   return lei;
 }
@@ -314,7 +314,7 @@ int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item)
   // If the item has dependencies queue it to follow them.
   if (entry.Target) {
     // Target dependencies are always known.  Follow them.
-    BFSEntry qe = { index, 0 };
+    BFSEntry qe = { index, CM_NULLPTR };
     this->BFSQueue.push(qe);
   } else {
     // Look for an old-style <item>_LIB_DEPENDS variable.
diff --git a/Source/cmComputeLinkDepends.h b/Source/cmComputeLinkDepends.h
index 6aa40c3..6a4e8e0 100644
--- a/Source/cmComputeLinkDepends.h
+++ b/Source/cmComputeLinkDepends.h
@@ -1,28 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmComputeLinkDepends_h
 #define cmComputeLinkDepends_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmGraphAdjacencyList.h"
 #include "cmLinkItem.h"
+#include "cmTargetLinkLibraryType.h"
 
+#include <map>
 #include <queue>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmComputeComponentGraph;
+class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmMakefile;
-class cmGeneratorTarget;
 class cmake;
 
 /** \class cmComputeLinkDepends
@@ -44,7 +40,7 @@ public:
     bool IsFlag;
     LinkEntry()
       : Item()
-      , Target(0)
+      , Target(CM_NULLPTR)
       , IsSharedDep(false)
       , IsFlag(false)
     {
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index e1a7bee..dc8236d 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -1,29 +1,26 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmComputeLinkInformation.h"
 
-#include "cmComputeLinkDepends.h"
-#include "cmOrderDirectories.h"
-
 #include "cmAlgorithms.h"
+#include "cmComputeLinkDepends.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOrderDirectories.h"
 #include "cmOutputConverter.h"
+#include "cmPolicies.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmake.h"
 
+#include <algorithm>
 #include <ctype.h>
+#include <sstream>
+#include <string.h>
+#include <utility>
 
 //#define CM_COMPUTE_LINK_INFO_DEBUG
 
@@ -262,7 +259,7 @@ cmComputeLinkInformation::cmComputeLinkInformation(
     this->GlobalGenerator, target, "linker search path");
   this->OrderRuntimeSearchPath = new cmOrderDirectories(
     this->GlobalGenerator, target, "runtime search path");
-  this->OrderDependentRPath = 0;
+  this->OrderDependentRPath = CM_NULLPTR;
 
   // Get the language used for linking this target.
   this->LinkLanguage = this->Target->GetLinkerLanguage(config);
@@ -274,8 +271,7 @@ cmComputeLinkInformation::cmComputeLinkInformation(
 
   // Check whether we should use an import library for linking a target.
   this->UseImportLibrary =
-    this->Makefile->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX") ? true
-                                                                 : false;
+    this->Makefile->IsDefinitionSet("CMAKE_IMPORT_LIBRARY_SUFFIX");
 
   // Check whether we should skip dependencies on shared library files.
   this->LinkDependsNoShared =
@@ -284,7 +280,7 @@ cmComputeLinkInformation::cmComputeLinkInformation(
   // On platforms without import libraries there may be a special flag
   // to use when creating a plugin (module) that obtains symbols from
   // the program that will load it.
-  this->LoaderFlag = 0;
+  this->LoaderFlag = CM_NULLPTR;
   if (!this->UseImportLibrary &&
       this->Target->GetType() == cmState::MODULE_LIBRARY) {
     std::string loader_flag_var = "CMAKE_SHARED_MODULE_LOADER_";
@@ -562,7 +558,7 @@ void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang)
     for (std::vector<std::string>::const_iterator i = libsVec.begin();
          i != libsVec.end(); ++i) {
       if (this->ImplicitLinkLibs.find(*i) == this->ImplicitLinkLibs.end()) {
-        this->AddItem(*i, 0);
+        this->AddItem(*i, CM_NULLPTR);
       }
     }
   }
@@ -694,7 +690,7 @@ void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
 
   // Check if we need to include the dependent shared library in other
   // path ordering.
-  cmOrderDirectories* order = 0;
+  cmOrderDirectories* order = CM_NULLPTR;
   if (this->SharedDependencyMode == SharedDepModeLibDir &&
       !this->LinkWithRuntimePath /* AddLibraryRuntimeInfo adds it */) {
     // Add the item to the linker search path.
@@ -706,7 +702,7 @@ void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
   if (order) {
     if (tgt) {
       std::string soName = tgt->GetSOName(this->Config);
-      const char* soname = soName.empty() ? 0 : soName.c_str();
+      const char* soname = soName.empty() ? CM_NULLPTR : soName.c_str();
       order->AddRuntimeLibrary(lib, soname);
     } else {
       order->AddRuntimeLibrary(lib);
@@ -725,9 +721,9 @@ void cmComputeLinkInformation::ComputeLinkTypeInfo()
   this->LinkTypeEnabled = false;
 
   // Lookup link type selection flags.
-  const char* static_link_type_flag = 0;
-  const char* shared_link_type_flag = 0;
-  const char* target_type_str = 0;
+  const char* static_link_type_flag = CM_NULLPTR;
+  const char* shared_link_type_flag = CM_NULLPTR;
+  const char* target_type_str = CM_NULLPTR;
   switch (this->Target->GetType()) {
     case cmState::EXECUTABLE:
       target_type_str = "EXE";
@@ -1607,7 +1603,7 @@ void cmComputeLinkInformation::AddLibraryRuntimeInfo(
   // Try to get the soname of the library.  Only files with this name
   // could possibly conflict.
   std::string soName = target->GetSOName(this->Config);
-  const char* soname = soName.empty() ? 0 : soName.c_str();
+  const char* soname = soName.empty() ? CM_NULLPTR : soName.c_str();
 
   // Include this library in the runtime path ordering.
   this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath, soname);
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index c0ddc53..1d29c26 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -1,26 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmComputeLinkInformation_h
 #define cmComputeLinkInformation_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/RegularExpression.hxx>
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
 
-class cmake;
+class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmMakefile;
-class cmGeneratorTarget;
 class cmOrderDirectories;
+class cmake;
 
 /** \class cmComputeLinkInformation
  * \brief Compute link information for a target in one configuration.
@@ -38,7 +33,7 @@ public:
     Item()
       : Value()
       , IsPath(true)
-      , Target(0)
+      , Target(CM_NULLPTR)
     {
     }
     Item(Item const& item)
@@ -47,7 +42,8 @@ public:
       , Target(item.Target)
     {
     }
-    Item(std::string const& v, bool p, cmGeneratorTarget const* target = 0)
+    Item(std::string const& v, bool p,
+         cmGeneratorTarget const* target = CM_NULLPTR)
       : Value(v)
       , IsPath(p)
       , Target(target)
diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx
index 570405a..735bc32 100644
--- a/Source/cmComputeTargetDepends.cxx
+++ b/Source/cmComputeTargetDepends.cxx
@@ -1,29 +1,27 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmComputeTargetDepends.h"
 
 #include "cmComputeComponentGraph.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmPolicies.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
+#include "cmTargetDepend.h"
 #include "cmake.h"
 
-#include <algorithm>
-
 #include <assert.h>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
+class cmListFileBacktrace;
 
 /*
 
@@ -291,7 +289,7 @@ void cmComputeTargetDepends::AddInterfaceDepends(
   // within the project.
   if (dependee && dependee->GetType() == cmState::EXECUTABLE &&
       !dependee->IsExecutableWithExports()) {
-    dependee = 0;
+    dependee = CM_NULLPTR;
   }
 
   if (dependee) {
@@ -355,7 +353,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
   // within the project.
   if (linking && dependee && dependee->GetType() == cmState::EXECUTABLE &&
       !dependee->IsExecutableWithExports()) {
-    dependee = 0;
+    dependee = CM_NULLPTR;
   }
 
   if (dependee) {
diff --git a/Source/cmComputeTargetDepends.h b/Source/cmComputeTargetDepends.h
index 9e51d4d..2b6591f 100644
--- a/Source/cmComputeTargetDepends.h
+++ b/Source/cmComputeTargetDepends.h
@@ -1,27 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmComputeTargetDepends_h
 #define cmComputeTargetDepends_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmGraphAdjacencyList.h"
 
-#include <stack>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmComputeComponentGraph;
+class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmLinkItem;
-class cmGeneratorTarget;
 class cmTargetDependSet;
 
 /** \class cmComputeTargetDepends
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
index 7006b62..420a777 100644
--- a/Source/cmConditionEvaluator.cxx
+++ b/Source/cmConditionEvaluator.cxx
@@ -1,19 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmConditionEvaluator.h"
 
 #include "cmAlgorithms.h"
 #include "cmOutputConverter.h"
+#include "cmSystemTools.h"
 
 static std::string const keyAND = "AND";
 static std::string const keyCOMMAND = "COMMAND";
@@ -21,12 +12,14 @@ static std::string const keyDEFINED = "DEFINED";
 static std::string const keyEQUAL = "EQUAL";
 static std::string const keyEXISTS = "EXISTS";
 static std::string const keyGREATER = "GREATER";
+static std::string const keyGREATER_EQUAL = "GREATER_EQUAL";
 static std::string const keyIN_LIST = "IN_LIST";
 static std::string const keyIS_ABSOLUTE = "IS_ABSOLUTE";
 static std::string const keyIS_DIRECTORY = "IS_DIRECTORY";
 static std::string const keyIS_NEWER_THAN = "IS_NEWER_THAN";
 static std::string const keyIS_SYMLINK = "IS_SYMLINK";
 static std::string const keyLESS = "LESS";
+static std::string const keyLESS_EQUAL = "LESS_EQUAL";
 static std::string const keyMATCHES = "MATCHES";
 static std::string const keyNOT = "NOT";
 static std::string const keyOR = "OR";
@@ -35,12 +28,16 @@ static std::string const keyParenR = ")";
 static std::string const keyPOLICY = "POLICY";
 static std::string const keySTREQUAL = "STREQUAL";
 static std::string const keySTRGREATER = "STRGREATER";
+static std::string const keySTRGREATER_EQUAL = "STRGREATER_EQUAL";
 static std::string const keySTRLESS = "STRLESS";
+static std::string const keySTRLESS_EQUAL = "STRLESS_EQUAL";
 static std::string const keyTARGET = "TARGET";
 static std::string const keyTEST = "TEST";
 static std::string const keyVERSION_EQUAL = "VERSION_EQUAL";
 static std::string const keyVERSION_GREATER = "VERSION_GREATER";
+static std::string const keyVERSION_GREATER_EQUAL = "VERSION_GREATER_EQUAL";
 static std::string const keyVERSION_LESS = "VERSION_LESS";
+static std::string const keyVERSION_LESS_EQUAL = "VERSION_LESS_EQUAL";
 
 cmConditionEvaluator::cmConditionEvaluator(cmMakefile& makefile,
                                            const cmListFileContext& context,
@@ -78,7 +75,7 @@ bool cmConditionEvaluator::IsTrue(
   errorString = "";
 
   // handle empty invocation
-  if (args.size() < 1) {
+  if (args.empty()) {
     return false;
   }
 
@@ -130,7 +127,7 @@ const char* cmConditionEvaluator::GetDefinitionIfUnquoted(
   if ((this->Policy54Status != cmPolicies::WARN &&
        this->Policy54Status != cmPolicies::OLD) &&
       argument.WasQuoted()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   const char* def = this->Makefile.GetDefinition(argument.GetValue());
@@ -242,20 +239,19 @@ bool cmConditionEvaluator::GetBooleanValueOld(
     // Old IsTrue behavior for single argument.
     if (arg == "0") {
       return false;
-    } else if (arg == "1") {
+    }
+    if (arg == "1") {
       return true;
-    } else {
-      const char* def = this->GetDefinitionIfUnquoted(arg);
-      return !cmSystemTools::IsOff(def);
     }
-  } else {
-    // Old GetVariableOrNumber behavior.
     const char* def = this->GetDefinitionIfUnquoted(arg);
-    if (!def && atoi(arg.c_str())) {
-      def = arg.c_str();
-    }
     return !cmSystemTools::IsOff(def);
   }
+  // Old GetVariableOrNumber behavior.
+  const char* def = this->GetDefinitionIfUnquoted(arg);
+  if (!def && atoi(arg.c_str())) {
+    def = arg.c_str();
+  }
+  return !cmSystemTools::IsOff(def);
 }
 
 //=========================================================================
@@ -267,7 +263,8 @@ bool cmConditionEvaluator::GetBooleanValueWithAutoDereference(
   // Use the policy if it is set.
   if (this->Policy12Status == cmPolicies::NEW) {
     return GetBooleanValue(newArg);
-  } else if (this->Policy12Status == cmPolicies::OLD) {
+  }
+  if (this->Policy12Status == cmPolicies::OLD) {
     return GetBooleanValueOld(newArg, oneArg);
   }
 
@@ -486,7 +483,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
         if (argP1len > 4 && argP1->GetValue().substr(0, 4) == "ENV{" &&
             argP1->GetValue().operator[](argP1len - 1) == '}') {
           std::string env = argP1->GetValue().substr(4, argP1len - 5);
-          bdef = cmSystemTools::GetEnv(env.c_str()) ? true : false;
+          bdef = cmSystemTools::HasEnv(env.c_str());
         } else {
           bdef = this->Makefile.IsDefinitionSet(argP1->GetValue());
         }
@@ -559,7 +556,9 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
 
       if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
           (this->IsKeyword(keyLESS, *argP1) ||
+           this->IsKeyword(keyLESS_EQUAL, *argP1) ||
            this->IsKeyword(keyGREATER, *argP1) ||
+           this->IsKeyword(keyGREATER_EQUAL, *argP1) ||
            this->IsKeyword(keyEQUAL, *argP1))) {
         def = this->GetVariableOrString(*arg);
         def2 = this->GetVariableOrString(*argP2);
@@ -570,8 +569,12 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
           result = false;
         } else if (*(argP1) == keyLESS) {
           result = (lhs < rhs);
+        } else if (*(argP1) == keyLESS_EQUAL) {
+          result = (lhs <= rhs);
         } else if (*(argP1) == keyGREATER) {
           result = (lhs > rhs);
+        } else if (*(argP1) == keyGREATER_EQUAL) {
+          result = (lhs >= rhs);
         } else {
           result = (lhs == rhs);
         }
@@ -580,16 +583,22 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
 
       if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
           (this->IsKeyword(keySTRLESS, *argP1) ||
-           this->IsKeyword(keySTREQUAL, *argP1) ||
-           this->IsKeyword(keySTRGREATER, *argP1))) {
+           this->IsKeyword(keySTRLESS_EQUAL, *argP1) ||
+           this->IsKeyword(keySTRGREATER, *argP1) ||
+           this->IsKeyword(keySTRGREATER_EQUAL, *argP1) ||
+           this->IsKeyword(keySTREQUAL, *argP1))) {
         def = this->GetVariableOrString(*arg);
         def2 = this->GetVariableOrString(*argP2);
         int val = strcmp(def, def2);
         bool result;
         if (*(argP1) == keySTRLESS) {
           result = (val < 0);
+        } else if (*(argP1) == keySTRLESS_EQUAL) {
+          result = (val <= 0);
         } else if (*(argP1) == keySTRGREATER) {
           result = (val > 0);
+        } else if (*(argP1) == keySTRGREATER_EQUAL) {
+          result = (val >= 0);
         } else // strequal
         {
           result = (val == 0);
@@ -599,15 +608,23 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
 
       if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
           (this->IsKeyword(keyVERSION_LESS, *argP1) ||
+           this->IsKeyword(keyVERSION_LESS_EQUAL, *argP1) ||
            this->IsKeyword(keyVERSION_GREATER, *argP1) ||
+           this->IsKeyword(keyVERSION_GREATER_EQUAL, *argP1) ||
            this->IsKeyword(keyVERSION_EQUAL, *argP1))) {
         def = this->GetVariableOrString(*arg);
         def2 = this->GetVariableOrString(*argP2);
-        cmSystemTools::CompareOp op = cmSystemTools::OP_EQUAL;
+        cmSystemTools::CompareOp op;
         if (*argP1 == keyVERSION_LESS) {
           op = cmSystemTools::OP_LESS;
+        } else if (*argP1 == keyVERSION_LESS_EQUAL) {
+          op = cmSystemTools::OP_LESS_EQUAL;
         } else if (*argP1 == keyVERSION_GREATER) {
           op = cmSystemTools::OP_GREATER;
+        } else if (*argP1 == keyVERSION_GREATER_EQUAL) {
+          op = cmSystemTools::OP_GREATER_EQUAL;
+        } else { // version_equal
+          op = cmSystemTools::OP_EQUAL;
         }
         bool result = cmSystemTools::VersionCompare(op, def, def2);
         this->HandleBinaryOp(result, reducible, arg, newArgs, argP1, argP2);
diff --git a/Source/cmConditionEvaluator.h b/Source/cmConditionEvaluator.h
index 3f8c984..306bee4 100644
--- a/Source/cmConditionEvaluator.h
+++ b/Source/cmConditionEvaluator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmConditionEvaluator_h
 #define cmConditionEvaluator_h
 
diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in
index 62128a7..057c6c0 100644
--- a/Source/cmConfigure.cmake.h.in
+++ b/Source/cmConfigure.cmake.h.in
@@ -1,18 +1,46 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmConfigure_h
+#define cmConfigure_h
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
+#include <cmsys/Configure.hxx> // IWYU pragma: keep
+
+#ifdef _MSC_VER
+#pragma warning(disable : 4786)
+#pragma warning(disable : 4503)
+#endif
+
+#ifdef __ICL
+#pragma warning(disable : 985)
+#pragma warning(disable : 1572) /* floating-point equality test */
+#endif
 
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
 #cmakedefine HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE
 #cmakedefine HAVE_UNSETENV
 #cmakedefine CMAKE_USE_ELF_PARSER
 #cmakedefine CMAKE_USE_MACH_PARSER
+#cmakedefine CMAKE_USE_LIBUV
 #cmakedefine CMAKE_ENCODING_UTF8
-#cmakedefine CMake_HAVE_CXX11_UNORDERED_MAP
+#cmakedefine CMake_HAVE_CXX_AUTO_PTR
+#cmakedefine CMake_HAVE_CXX_MAKE_UNIQUE
+#cmakedefine CMake_HAVE_CXX_NULLPTR
+#cmakedefine CMake_HAVE_CXX_OVERRIDE
+#cmakedefine CMake_HAVE_CXX_UNIQUE_PTR
+#cmakedefine CMake_HAVE_CXX_UNORDERED_MAP
+#cmakedefine CMake_HAVE_CXX_UNORDERED_SET
+#define CMAKE_BIN_DIR "/@CMAKE_BIN_DIR@"
 #define CMAKE_DATA_DIR "/@CMAKE_DATA_DIR@"
+
+#ifdef CMake_HAVE_CXX_NULLPTR
+#define CM_NULLPTR nullptr
+#else
+#define CM_NULLPTR 0
+#endif
+
+#ifdef CMake_HAVE_CXX_OVERRIDE
+#define CM_OVERRIDE override
+#else
+#define CM_OVERRIDE
+#endif
+
+#endif
diff --git a/Source/cmConfigureFileCommand.cxx b/Source/cmConfigureFileCommand.cxx
index 899a674..6a451f5 100644
--- a/Source/cmConfigureFileCommand.cxx
+++ b/Source/cmConfigureFileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmConfigureFileCommand.h"
 
 #include <cmsys/RegularExpression.hxx>
diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h
index 79f00bc..f9a0f2a 100644
--- a/Source/cmConfigureFileCommand.h
+++ b/Source/cmConfigureFileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmConfigureFileCommand_h
 #define cmConfigureFileCommand_h
 
@@ -19,24 +10,24 @@ class cmConfigureFileCommand : public cmCommand
 public:
   cmTypeMacro(cmConfigureFileCommand, cmCommand);
 
-  virtual cmCommand* Clone() { return new cmConfigureFileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmConfigureFileCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "configure_file"; }
+  std::string GetName() const CM_OVERRIDE { return "configure_file"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
 private:
   int ConfigureFile();
diff --git a/Source/cmContinueCommand.cxx b/Source/cmContinueCommand.cxx
index c8c1b7d..ce36463 100644
--- a/Source/cmContinueCommand.cxx
+++ b/Source/cmContinueCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmContinueCommand.h"
 
 // cmContinueCommand
diff --git a/Source/cmContinueCommand.h b/Source/cmContinueCommand.h
index 63ae59d..a36d5f3 100644
--- a/Source/cmContinueCommand.h
+++ b/Source/cmContinueCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmContinueCommand_h
 #define cmContinueCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmContinueCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmContinueCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "continue"; }
+  std::string GetName() const CM_OVERRIDE { return "continue"; }
 
   cmTypeMacro(cmContinueCommand, cmCommand);
 };
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index 75d0e9e..a409d40 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCoreTryCompile.h"
 
 #include "cmAlgorithms.h"
@@ -77,7 +68,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
   }
 
   const char* sourceDirectory = argv[2].c_str();
-  const char* projectName = 0;
+  const char* projectName = CM_NULLPTR;
   std::string targetName;
   std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
   std::vector<std::string> compileDefs;
@@ -334,6 +325,43 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
                     " ${COMPILE_DEFINITIONS}\")\n",
               li->c_str(), li->c_str());
     }
+    switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
+      case cmPolicies::WARN:
+        if (this->Makefile->PolicyOptionalWarningEnabled(
+              "CMAKE_POLICY_WARNING_CMP0066")) {
+          std::ostringstream w;
+          /* clang-format off */
+          w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
+            "For compatibility with older versions of CMake, try_compile "
+            "is not honoring caller config-specific compiler flags "
+            "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
+            ;
+          /* clang-format on */
+          this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+        }
+      case cmPolicies::OLD:
+        // OLD behavior is to do nothing.
+        break;
+      case cmPolicies::REQUIRED_IF_USED:
+      case cmPolicies::REQUIRED_ALWAYS:
+        this->Makefile->IssueMessage(
+          cmake::FATAL_ERROR,
+          cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
+      case cmPolicies::NEW: {
+        // NEW behavior is to pass config-specific compiler flags.
+        static std::string const cfgDefault = "DEBUG";
+        std::string const cfg =
+          !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
+        for (std::set<std::string>::iterator li = testLangs.begin();
+             li != testLangs.end(); ++li) {
+          std::string const langFlagsCfg = "CMAKE_" + *li + "_FLAGS_" + cfg;
+          const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
+          fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
+                  cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "")
+                    .c_str());
+        }
+      } break;
+    }
     switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
       case cmPolicies::WARN:
         if (this->Makefile->PolicyOptionalWarningEnabled(
@@ -528,9 +556,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
         if (copyFileError.empty()) {
           this->Makefile->IssueMessage(cmake::FATAL_ERROR, emsg.str());
           return -1;
-        } else {
-          copyFileErrorMessage = emsg.str();
         }
+        copyFileErrorMessage = emsg.str();
       }
     }
 
diff --git a/Source/cmCoreTryCompile.h b/Source/cmCoreTryCompile.h
index 6a3b049..e173a16 100644
--- a/Source/cmCoreTryCompile.h
+++ b/Source/cmCoreTryCompile.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCoreTryCompile_h
 #define cmCoreTryCompile_h
 
diff --git a/Source/cmCreateTestSourceList.cxx b/Source/cmCreateTestSourceList.cxx
index d8c629c..ec62c5b 100644
--- a/Source/cmCreateTestSourceList.cxx
+++ b/Source/cmCreateTestSourceList.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCreateTestSourceList.h"
 
 #include "cmSourceFile.h"
diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h
index cfaca2e..ffd06f0 100644
--- a/Source/cmCreateTestSourceList.h
+++ b/Source/cmCreateTestSourceList.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCreateTestSourceList_h
 #define cmCreateTestSourceList_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmCreateTestSourceList; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmCreateTestSourceList; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "create_test_sourcelist"; }
+  std::string GetName() const CM_OVERRIDE { return "create_test_sourcelist"; }
 
   cmTypeMacro(cmCreateTestSourceList, cmCommand);
 };
diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx
index 85049ca..9b3f84a 100644
--- a/Source/cmCryptoHash.cxx
+++ b/Source/cmCryptoHash.cxx
@@ -1,40 +1,71 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCryptoHash.h"
 
 #include "cm_sha2.h"
+
 #include <cmsys/FStream.hxx>
 #include <cmsys/MD5.h>
+#include <string.h>
 
-cmsys::auto_ptr<cmCryptoHash> cmCryptoHash::New(const char* algo)
+CM_AUTO_PTR<cmCryptoHash> cmCryptoHash::New(const char* algo)
 {
   if (strcmp(algo, "MD5") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashMD5);
-  } else if (strcmp(algo, "SHA1") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA1);
-  } else if (strcmp(algo, "SHA224") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA224);
-  } else if (strcmp(algo, "SHA256") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA256);
-  } else if (strcmp(algo, "SHA384") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA384);
-  } else if (strcmp(algo, "SHA512") == 0) {
-    return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA512);
-  } else {
-    return cmsys::auto_ptr<cmCryptoHash>(0);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashMD5);
+  }
+  if (strcmp(algo, "SHA1") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA1);
+  }
+  if (strcmp(algo, "SHA224") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA224);
   }
+  if (strcmp(algo, "SHA256") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA256);
+  }
+  if (strcmp(algo, "SHA384") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA384);
+  }
+  if (strcmp(algo, "SHA512") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA512);
+  }
+  return CM_AUTO_PTR<cmCryptoHash>(CM_NULLPTR);
 }
 
-std::string cmCryptoHash::HashString(const std::string& input)
+bool cmCryptoHash::IntFromHexDigit(char input, char& output)
+{
+  if (input >= '0' && input <= '9') {
+    output = char(input - '0');
+    return true;
+  }
+  if (input >= 'a' && input <= 'f') {
+    output = char(input - 'a' + 0xA);
+    return true;
+  }
+  if (input >= 'A' && input <= 'F') {
+    output = char(input - 'A' + 0xA);
+    return true;
+  }
+  return false;
+}
+
+std::string cmCryptoHash::ByteHashToString(
+  const std::vector<unsigned char>& hash)
+{
+  // Map from 4-bit index to hexadecimal representation.
+  static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
+                                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+
+  std::string res;
+  for (std::vector<unsigned char>::const_iterator vit = hash.begin();
+       vit != hash.end(); ++vit) {
+    res.push_back(hex[(*vit) >> 4]);
+    res.push_back(hex[(*vit) & 0xF]);
+  }
+  return res;
+}
+
+std::vector<unsigned char> cmCryptoHash::ByteHashString(
+  const std::string& input)
 {
   this->Initialize();
   this->Append(reinterpret_cast<unsigned char const*>(input.c_str()),
@@ -42,35 +73,48 @@ std::string cmCryptoHash::HashString(const std::string& input)
   return this->Finalize();
 }
 
-std::string cmCryptoHash::HashFile(const std::string& file)
+std::vector<unsigned char> cmCryptoHash::ByteHashFile(const std::string& file)
 {
   cmsys::ifstream fin(file.c_str(), std::ios::in | std::ios::binary);
-  if (!fin) {
-    return "";
+  if (fin) {
+    this->Initialize();
+    {
+      // Should be efficient enough on most system:
+      cm_sha2_uint64_t buffer[512];
+      char* buffer_c = reinterpret_cast<char*>(buffer);
+      unsigned char const* buffer_uc =
+        reinterpret_cast<unsigned char const*>(buffer);
+      // This copy loop is very sensitive on certain platforms with
+      // slightly broken stream libraries (like HPUX).  Normally, it is
+      // incorrect to not check the error condition on the fin.read()
+      // before using the data, but the fin.gcount() will be zero if an
+      // error occurred.  Therefore, the loop should be safe everywhere.
+      while (fin) {
+        fin.read(buffer_c, sizeof(buffer));
+        if (int gcount = static_cast<int>(fin.gcount())) {
+          this->Append(buffer_uc, gcount);
+        }
+      }
+    }
+    if (fin.eof()) {
+      // Success
+      return this->Finalize();
+    }
+    // Finalize anyway
+    this->Finalize();
   }
+  // Return without success
+  return std::vector<unsigned char>();
+}
 
-  this->Initialize();
+std::string cmCryptoHash::HashString(const std::string& input)
+{
+  return ByteHashToString(this->ByteHashString(input));
+}
 
-  // Should be efficient enough on most system:
-  cm_sha2_uint64_t buffer[512];
-  char* buffer_c = reinterpret_cast<char*>(buffer);
-  unsigned char const* buffer_uc =
-    reinterpret_cast<unsigned char const*>(buffer);
-  // This copy loop is very sensitive on certain platforms with
-  // slightly broken stream libraries (like HPUX).  Normally, it is
-  // incorrect to not check the error condition on the fin.read()
-  // before using the data, but the fin.gcount() will be zero if an
-  // error occurred.  Therefore, the loop should be safe everywhere.
-  while (fin) {
-    fin.read(buffer_c, sizeof(buffer));
-    if (int gcount = static_cast<int>(fin.gcount())) {
-      this->Append(buffer_uc, gcount);
-    }
-  }
-  if (fin.eof()) {
-    return this->Finalize();
-  }
-  return "";
+std::string cmCryptoHash::HashFile(const std::string& file)
+{
+  return ByteHashToString(this->ByteHashFile(file));
 }
 
 cmCryptoHashMD5::cmCryptoHashMD5()
@@ -93,11 +137,11 @@ void cmCryptoHashMD5::Append(unsigned char const* buf, int sz)
   cmsysMD5_Append(this->MD5, buf, sz);
 }
 
-std::string cmCryptoHashMD5::Finalize()
+std::vector<unsigned char> cmCryptoHashMD5::Finalize()
 {
-  char md5out[32];
-  cmsysMD5_FinalizeHex(this->MD5, md5out);
-  return std::string(md5out, 32);
+  std::vector<unsigned char> hash(16, 0);
+  cmsysMD5_Finalize(this->MD5, &hash[0]);
+  return hash;
 }
 
 #define cmCryptoHash_SHA_CLASS_IMPL(SHA)                                      \
@@ -111,11 +155,11 @@ std::string cmCryptoHashMD5::Finalize()
   {                                                                           \
     SHA##_Update(this->SHA, buf, sz);                                         \
   }                                                                           \
-  std::string cmCryptoHash##SHA::Finalize()                                   \
+  std::vector<unsigned char> cmCryptoHash##SHA::Finalize()                    \
   {                                                                           \
-    char out[SHA##_DIGEST_STRING_LENGTH];                                     \
-    SHA##_End(this->SHA, out);                                                \
-    return std::string(out, SHA##_DIGEST_STRING_LENGTH - 1);                  \
+    std::vector<unsigned char> hash(SHA##_DIGEST_LENGTH, 0);                  \
+    SHA##_Final(&hash[0], this->SHA);                                         \
+    return hash;                                                              \
   }
 
 cmCryptoHash_SHA_CLASS_IMPL(SHA1) cmCryptoHash_SHA_CLASS_IMPL(SHA224)
diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h
index a0c5eab..5c2d3ca 100644
--- a/Source/cmCryptoHash.h
+++ b/Source/cmCryptoHash.h
@@ -1,33 +1,62 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCryptoHash_h
 #define cmCryptoHash_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
+#include <string>
+#include <vector>
 
+/**
+ * @brief Abstract base class for cryptographic hash generators
+ */
 class cmCryptoHash
 {
 public:
   virtual ~cmCryptoHash() {}
-  static cmsys::auto_ptr<cmCryptoHash> New(const char* algo);
+
+  /// @brief Returns a new hash generator of the requested type
+  /// @arg algo Hash type name. Supported hash types are
+  ///      MD5, SHA1, SHA224, SHA256, SHA384, SHA512
+  /// @return A valid auto pointer if algo is supported or
+  ///         an invalid/NULL pointer otherwise
+  static CM_AUTO_PTR<cmCryptoHash> New(const char* algo);
+
+  /// @brief Converts a hex character to its binary value (4 bits)
+  /// @arg input Hex character [0-9a-fA-F].
+  /// @arg output Binary value of the input character (4 bits)
+  /// @return True if input was a valid hex character
+  static bool IntFromHexDigit(char input, char& output);
+
+  /// @brief Converts a byte hash to a sequence of hex character pairs
+  static std::string ByteHashToString(const std::vector<unsigned char>& hash);
+
+  /// @brief Calculates a binary hash from string input data
+  /// @return Binary hash vector
+  std::vector<unsigned char> ByteHashString(const std::string& input);
+
+  /// @brief Calculates a binary hash from file content
+  /// @see ByteHashString()
+  /// @return Non empty binary hash vector if the file was read successfully.
+  ///         An empty vector otherwise.
+  std::vector<unsigned char> ByteHashFile(const std::string& file);
+
+  /// @brief Calculates a hash string from string input data
+  /// @return Sequence of hex characters pairs for each byte of the binary hash
   std::string HashString(const std::string& input);
+
+  /// @brief Calculates a hash string from file content
+  /// @see HashString()
+  /// @return Non empty hash string if the file was read successfully.
+  ///         An empty string otherwise.
   std::string HashFile(const std::string& file);
 
 protected:
   virtual void Initialize() = 0;
   virtual void Append(unsigned char const*, int) = 0;
-  virtual std::string Finalize() = 0;
+  virtual std::vector<unsigned char> Finalize() = 0;
 };
 
 class cmCryptoHashMD5 : public cmCryptoHash
@@ -36,12 +65,12 @@ class cmCryptoHashMD5 : public cmCryptoHash
 
 public:
   cmCryptoHashMD5();
-  ~cmCryptoHashMD5();
+  ~cmCryptoHashMD5() CM_OVERRIDE;
 
 protected:
-  virtual void Initialize();
-  virtual void Append(unsigned char const* buf, int sz);
-  virtual std::string Finalize();
+  void Initialize() CM_OVERRIDE;
+  void Append(unsigned char const* buf, int sz) CM_OVERRIDE;
+  std::vector<unsigned char> Finalize() CM_OVERRIDE;
 };
 
 #define cmCryptoHash_SHA_CLASS_DECL(SHA)                                      \
@@ -56,7 +85,7 @@ protected:
   protected:                                                                  \
     virtual void Initialize();                                                \
     virtual void Append(unsigned char const* buf, int sz);                    \
-    virtual std::string Finalize();                                           \
+    virtual std::vector<unsigned char> Finalize();                            \
   }
 
 cmCryptoHash_SHA_CLASS_DECL(SHA1);
diff --git a/Source/cmCurl.cxx b/Source/cmCurl.cxx
index 5bc4f91..341b8c0 100644
--- a/Source/cmCurl.cxx
+++ b/Source/cmCurl.cxx
@@ -1,17 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCurl.h"
 
+#include "cmThirdParty.h"
+
+#if !defined(CMAKE_USE_SYSTEM_CURL) && !defined(_WIN32) &&                    \
+  !defined(__APPLE__) && !defined(CURL_CA_BUNDLE) && !defined(CURL_CA_PATH)
+#define CMAKE_FIND_CAFILE
 #include "cmSystemTools.h"
+#endif
 
 // curl versions before 7.21.5 did not provide this error code
 #if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM < 0x071505
@@ -19,9 +16,9 @@
 #endif
 
 #define check_curl_result(result, errstr)                                     \
-  if (result != CURLE_OK && result != CURLE_NOT_BUILT_IN) {                   \
+  if ((result) != CURLE_OK && (result) != CURLE_NOT_BUILT_IN) {               \
     e += e.empty() ? "" : "\n";                                               \
-    e += errstr;                                                              \
+    e += (errstr);                                                            \
     e += ::curl_easy_strerror(result);                                        \
   }
 
@@ -32,8 +29,7 @@ std::string cmCurlSetCAInfo(::CURL* curl, const char* cafile)
     ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_CAINFO, cafile);
     check_curl_result(res, "Unable to set TLS/SSL Verify CAINFO: ");
   }
-#if !defined(CMAKE_USE_SYSTEM_CURL) && !defined(_WIN32) &&                    \
-  !defined(__APPLE__) && !defined(CURL_CA_BUNDLE) && !defined(CURL_CA_PATH)
+#ifdef CMAKE_FIND_CAFILE
 #define CMAKE_CAFILE_FEDORA "/etc/pki/tls/certs/ca-bundle.crt"
   else if (cmSystemTools::FileExists(CMAKE_CAFILE_FEDORA, true)) {
     ::CURLcode res =
diff --git a/Source/cmCurl.h b/Source/cmCurl.h
index eac7f13..60ab9fe 100644
--- a/Source/cmCurl.h
+++ b/Source/cmCurl.h
@@ -1,21 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCurl_h
 #define cmCurl_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include "cm_curl.h"
+#include <cm_curl.h>
+#include <string>
 
-std::string cmCurlSetCAInfo(::CURL* curl, const char* cafile = 0);
+std::string cmCurlSetCAInfo(::CURL* curl, const char* cafile = CM_NULLPTR);
 
 #endif
diff --git a/Source/cmCustomCommand.cxx b/Source/cmCustomCommand.cxx
index 7c00c80..6645b8e 100644
--- a/Source/cmCustomCommand.cxx
+++ b/Source/cmCustomCommand.cxx
@@ -1,19 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCustomCommand.h"
 
 #include "cmMakefile.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cmConfigure.h>
 
 cmCustomCommand::cmCustomCommand()
   : Backtrace()
@@ -38,7 +29,7 @@ cmCustomCommand::cmCustomCommand(cmMakefile const* mf,
   , Backtrace()
   , Comment(comment ? comment : "")
   , WorkingDirectory(workingDirectory ? workingDirectory : "")
-  , HaveComment(comment ? true : false)
+  , HaveComment(comment != CM_NULLPTR)
   , EscapeAllowMakeVars(false)
   , EscapeOldStyle(true)
 {
@@ -69,7 +60,7 @@ const cmCustomCommandLines& cmCustomCommand::GetCommandLines() const
 
 const char* cmCustomCommand::GetComment() const
 {
-  const char* no_comment = 0;
+  const char* no_comment = CM_NULLPTR;
   return this->HaveComment ? this->Comment.c_str() : no_comment;
 }
 
@@ -135,3 +126,13 @@ void cmCustomCommand::SetUsesTerminal(bool b)
 {
   this->UsesTerminal = b;
 }
+
+const std::string& cmCustomCommand::GetDepfile() const
+{
+  return this->Depfile;
+}
+
+void cmCustomCommand::SetDepfile(const std::string& depfile)
+{
+  this->Depfile = depfile;
+}
diff --git a/Source/cmCustomCommand.h b/Source/cmCustomCommand.h
index c2b9738..66f8fa9 100644
--- a/Source/cmCustomCommand.h
+++ b/Source/cmCustomCommand.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCustomCommand_h
 #define cmCustomCommand_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
+#include "cmCustomCommandLines.h"
 #include "cmListFileCache.h"
+
+#include <string>
+#include <utility>
+#include <vector>
+
 class cmMakefile;
 
 /** \class cmCustomCommand
@@ -88,6 +85,10 @@ public:
   bool GetUsesTerminal() const;
   void SetUsesTerminal(bool b);
 
+  /** Set/Get the depfile (used by the Ninja generator) */
+  const std::string& GetDepfile() const;
+  void SetDepfile(const std::string& depfile);
+
 private:
   std::vector<std::string> Outputs;
   std::vector<std::string> Byproducts;
@@ -97,6 +98,7 @@ private:
   ImplicitDependsList ImplicitDepends;
   std::string Comment;
   std::string WorkingDirectory;
+  std::string Depfile;
   bool HaveComment;
   bool EscapeAllowMakeVars;
   bool EscapeOldStyle;
diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx
index 99bb601..0fd4ffb 100644
--- a/Source/cmCustomCommandGenerator.cxx
+++ b/Source/cmCustomCommandGenerator.cxx
@@ -1,21 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCustomCommandGenerator.h"
 
 #include "cmCustomCommand.h"
+#include "cmCustomCommandLines.h"
 #include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+
+#include <cmConfigure.h>
 
 cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc,
                                                    const std::string& config,
@@ -45,7 +43,7 @@ bool cmCustomCommandGenerator::UseCrossCompilingEmulator(unsigned int c) const
   std::string const& argv0 = this->CC.GetCommandLines()[c][0];
   cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
   if (target && target->GetType() == cmState::EXECUTABLE) {
-    return target->GetProperty("CROSSCOMPILING_EMULATOR") != 0;
+    return target->GetProperty("CROSSCOMPILING_EMULATOR") != CM_NULLPTR;
   }
   return false;
 }
@@ -66,7 +64,7 @@ std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
     }
   }
 
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = this->GE->Parse(argv0);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(argv0);
   std::string exe = cge->Evaluate(this->LG, this->Config);
 
   return exe;
@@ -145,7 +143,7 @@ std::vector<std::string> const& cmCustomCommandGenerator::GetDepends() const
     std::vector<std::string> depends = this->CC.GetDepends();
     for (std::vector<std::string>::const_iterator i = depends.begin();
          i != depends.end(); ++i) {
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = this->GE->Parse(*i);
+      CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*i);
       std::vector<std::string> result;
       cmSystemTools::ExpandListArgument(cge->Evaluate(this->LG, this->Config),
                                         result);
diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h
index a361153..23cc596 100644
--- a/Source/cmCustomCommandGenerator.h
+++ b/Source/cmCustomCommandGenerator.h
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCustomCommandGenerator_h
 #define cmCustomCommandGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 class cmCustomCommand;
-class cmLocalGenerator;
 class cmGeneratorExpression;
+class cmLocalGenerator;
 
 class cmCustomCommandGenerator
 {
diff --git a/Source/cmCustomCommandLines.h b/Source/cmCustomCommandLines.h
new file mode 100644
index 0000000..87ed4e8
--- /dev/null
+++ b/Source/cmCustomCommandLines.h
@@ -0,0 +1,29 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmCustomCommandLines_h
+#define cmCustomCommandLines_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+/** Data structure to represent a single command line.  */
+class cmCustomCommandLine : public std::vector<std::string>
+{
+public:
+  typedef std::vector<std::string> Superclass;
+  typedef Superclass::iterator iterator;
+  typedef Superclass::const_iterator const_iterator;
+};
+
+/** Data structure to represent a list of command lines.  */
+class cmCustomCommandLines : public std::vector<cmCustomCommandLine>
+{
+public:
+  typedef std::vector<cmCustomCommandLine> Superclass;
+  typedef Superclass::iterator iterator;
+  typedef Superclass::const_iterator const_iterator;
+};
+
+#endif
diff --git a/Source/cmDefinePropertyCommand.cxx b/Source/cmDefinePropertyCommand.cxx
index 484a970..8800363 100644
--- a/Source/cmDefinePropertyCommand.cxx
+++ b/Source/cmDefinePropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDefinePropertyCommand.h"
 
 #include "cmState.h"
@@ -17,7 +8,7 @@
 bool cmDefinePropertyCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmDefinePropertyCommand.h b/Source/cmDefinePropertyCommand.h
index 4248bbe..f494123 100644
--- a/Source/cmDefinePropertyCommand.h
+++ b/Source/cmDefinePropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDefinesPropertyCommand_h
 #define cmDefinesPropertyCommand_h
 
@@ -17,19 +8,19 @@
 class cmDefinePropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmDefinePropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmDefinePropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "define_property"; }
+  std::string GetName() const CM_OVERRIDE { return "define_property"; }
 
   cmTypeMacro(cmDefinePropertyCommand, cmCommand);
 
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index 28b6677..0b459f9 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDefinitions.h"
 
 #include <assert.h>
+#include <set>
+#include <utility>
 
 cmDefinitions::Def cmDefinitions::NoDef;
 
@@ -41,7 +34,7 @@ const char* cmDefinitions::Get(const std::string& key, StackIter begin,
                                StackIter end)
 {
   Def const& def = cmDefinitions::GetInternal(key, begin, end, false);
-  return def.Exists ? def.c_str() : 0;
+  return def.Exists ? def.c_str() : CM_NULLPTR;
 }
 
 void cmDefinitions::Raise(const std::string& key, StackIter begin,
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index 7be0098..569b3a2 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -1,31 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDefinitions_h
 #define cmDefinitions_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include "cmLinkedTree.h"
 
+#include <string>
+#include <vector>
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 #include <unordered_map>
 #else
 #include "cmsys/hash_map.hxx"
 #endif
+#else
+#include <map>
 #endif
 
-#include <list>
-
 /** \class cmDefinitions
  * \brief Store a scope of variable definitions for CMake language.
  *
@@ -92,7 +86,7 @@ private:
   static Def NoDef;
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
   typedef std::unordered_map<std::string, Def> MapType;
 #else
   typedef cmsys::hash_map<std::string, Def> MapType;
diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx
index 5df3cc1..c189419 100644
--- a/Source/cmDepends.cxx
+++ b/Source/cmDepends.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDepends.h"
 
 #include "cmFileTimeComparison.h"
@@ -16,14 +7,17 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSystemTools.h"
+
 #include <cmsys/FStream.hxx>
+#include <sstream>
 #include <string.h>
+#include <utility>
 
 cmDepends::cmDepends(cmLocalGenerator* lg, const char* targetDir)
   : CompileDirectory()
   , LocalGenerator(lg)
   , Verbose(false)
-  , FileComparison(0)
+  , FileComparison(CM_NULLPTR)
   , TargetDirectory(targetDir)
   , MaxPath(16384)
   , Dependee(new char[MaxPath])
@@ -72,7 +66,7 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends)
   return this->Finalize(makeDepends, internalDepends);
 }
 
-bool cmDepends::Finalize(std::ostream&, std::ostream&)
+bool cmDepends::Finalize(std::ostream& /*unused*/, std::ostream& /*unused*/)
 {
   return true;
 }
@@ -123,9 +117,10 @@ void cmDepends::Clear(const char* file)
                 << std::endl;
 }
 
-bool cmDepends::WriteDependencies(const std::set<std::string>&,
-                                  const std::string&, std::ostream&,
-                                  std::ostream&)
+bool cmDepends::WriteDependencies(const std::set<std::string>& /*unused*/,
+                                  const std::string& /*unused*/,
+                                  std::ostream& /*unused*/,
+                                  std::ostream& /*unused*/)
 {
   // This should be implemented by the subclass.
   return false;
@@ -140,7 +135,7 @@ bool cmDepends::CheckDependencies(
   // regenerated.
   bool okay = true;
   bool dependerExists = false;
-  DependencyVector* currentDependencies = 0;
+  DependencyVector* currentDependencies = CM_NULLPTR;
 
   while (internalDepends.getline(this->Dependee, this->MaxPath)) {
     if (this->Dependee[0] == 0 || this->Dependee[0] == '#' ||
@@ -182,7 +177,7 @@ bool cmDepends::CheckDependencies(
     bool regenerate = false;
     const char* dependee = this->Dependee + 1;
     const char* depender = this->Depender;
-    if (currentDependencies != 0) {
+    if (currentDependencies != CM_NULLPTR) {
       currentDependencies->push_back(dependee);
     }
 
@@ -242,9 +237,9 @@ bool cmDepends::CheckDependencies(
 
       // Remove the information of this depender from the map, it needs
       // to be rescanned
-      if (currentDependencies != 0) {
+      if (currentDependencies != CM_NULLPTR) {
         validDeps.erase(this->Depender);
-        currentDependencies = 0;
+        currentDependencies = CM_NULLPTR;
       }
 
       // Remove the depender to be sure it is rebuilt.
@@ -261,7 +256,7 @@ bool cmDepends::CheckDependencies(
 void cmDepends::SetIncludePathFromLanguage(const std::string& lang)
 {
   // Look for the new per "TARGET_" variant first:
-  const char* includePath = 0;
+  const char* includePath = CM_NULLPTR;
   std::string includePathVar = "CMAKE_";
   includePathVar += lang;
   includePathVar += "_TARGET_INCLUDE_PATH";
diff --git a/Source/cmDepends.h b/Source/cmDepends.h
index a62f8c2..f677f80 100644
--- a/Source/cmDepends.h
+++ b/Source/cmDepends.h
@@ -1,18 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDepends_h
 #define cmDepends_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmFileTimeComparison;
 class cmLocalGenerator;
@@ -29,7 +27,7 @@ class cmDepends
 public:
   /** Instances need to know the build directory name and the relative
       path from the build directory to the target file.  */
-  cmDepends(cmLocalGenerator* lg = 0, const char* targetDir = "");
+  cmDepends(cmLocalGenerator* lg = CM_NULLPTR, const char* targetDir = "");
 
   /** at what level will the compile be done from */
   void SetCompileDirectory(const char* dir) { this->CompileDirectory = dir; }
diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx
index 78bb1b2..84ab072 100644
--- a/Source/cmDependsC.cxx
+++ b/Source/cmDependsC.cxx
@@ -1,24 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsC.h"
 
 #include "cmAlgorithms.h"
 #include "cmFileTimeComparison.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSystemTools.h"
-#include <cmsys/FStream.hxx>
 
-#include <ctype.h> // isspace
+#include <cmsys/FStream.hxx>
+#include <utility>
 
 #define INCLUDE_REGEX_LINE                                                    \
   "^[ \t]*#[ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
@@ -29,7 +21,7 @@
 #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
 
 cmDependsC::cmDependsC()
-  : ValidDeps(0)
+  : ValidDeps(CM_NULLPTR)
 {
 }
 
@@ -105,7 +97,7 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
   std::set<std::string> dependencies;
   bool haveDeps = false;
 
-  if (this->ValidDeps != 0) {
+  if (this->ValidDeps != CM_NULLPTR) {
     std::map<std::string, DependencyVector>::const_iterator tmpIt =
       this->ValidDeps->find(obj);
     if (tmpIt != this->ValidDeps->end()) {
@@ -158,7 +150,7 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
           this->HeaderLocationCache.find(current.FileName);
         if (headerLocationIt != this->HeaderLocationCache.end()) {
           fullName = headerLocationIt->second;
-        } else
+        } else {
           for (std::vector<std::string>::const_iterator i =
                  this->IncludePath.begin();
                i != this->IncludePath.end(); ++i) {
@@ -175,6 +167,7 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
               break;
             }
           }
+        }
       }
 
       // Complain if the file cannot be found and matches the complain
@@ -237,19 +230,18 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
   // written by the original local generator for this directory
   // convert the dependencies to paths relative to the home output
   // directory.  We must do the same here.
-  std::string obj_i =
-    this->LocalGenerator->Convert(obj, cmOutputConverter::HOME_OUTPUT);
-  std::string obj_m = this->LocalGenerator->ConvertToOutputFormat(
-    obj_i, cmOutputConverter::MAKERULE);
+  std::string binDir = this->LocalGenerator->GetBinaryDirectory();
+  std::string obj_i = this->LocalGenerator->ConvertToRelativePath(binDir, obj);
+  std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
   internalDepends << obj_i << std::endl;
 
   for (std::set<std::string>::const_iterator i = dependencies.begin();
        i != dependencies.end(); ++i) {
-    makeDepends << obj_m << ": "
-                << this->LocalGenerator->Convert(
-                     *i, cmOutputConverter::HOME_OUTPUT,
-                     cmOutputConverter::MAKERULE)
-                << std::endl;
+    makeDepends
+      << obj_m << ": "
+      << cmSystemTools::ConvertToOutputPath(
+           this->LocalGenerator->ConvertToRelativePath(binDir, *i).c_str())
+      << std::endl;
     internalDepends << " " << *i << std::endl;
   }
   makeDepends << std::endl;
@@ -268,31 +260,31 @@ void cmDependsC::ReadCacheFile()
   }
 
   std::string line;
-  cmIncludeLines* cacheEntry = 0;
+  cmIncludeLines* cacheEntry = CM_NULLPTR;
   bool haveFileName = false;
 
   while (cmSystemTools::GetLineFromStream(fin, line)) {
     if (line.empty()) {
-      cacheEntry = 0;
+      cacheEntry = CM_NULLPTR;
       haveFileName = false;
       continue;
     }
     // the first line after an empty line is the name of the parsed file
-    if (haveFileName == false) {
+    if (!haveFileName) {
       haveFileName = true;
       int newer = 0;
       cmFileTimeComparison comp;
       bool res = comp.FileTimeCompare(this->CacheFileName.c_str(),
                                       line.c_str(), &newer);
 
-      if ((res == true) && (newer == 1)) // cache is newer than the parsed file
+      if (res && newer == 1) // cache is newer than the parsed file
       {
         cacheEntry = new cmIncludeLines;
         this->FileCache[line] = cacheEntry;
       }
       // file doesn't exist, check that the regular expressions
       // haven't changed
-      else if (res == false) {
+      else if (!res) {
         if (line.find(INCLUDE_REGEX_LINE_MARKER) == 0) {
           if (line != this->IncludeRegexLineString) {
             return;
@@ -311,7 +303,7 @@ void cmDependsC::ReadCacheFile()
           }
         }
       }
-    } else if (cacheEntry != 0) {
+    } else if (cacheEntry != CM_NULLPTR) {
       UnscannedEntry entry;
       entry.FileName = line;
       if (cmSystemTools::GetLineFromStream(fin, line)) {
@@ -343,16 +335,16 @@ void cmDependsC::WriteCacheFile() const
          this->FileCache.begin();
        fileIt != this->FileCache.end(); ++fileIt) {
     if (fileIt->second->Used) {
-      cacheOut << fileIt->first.c_str() << std::endl;
+      cacheOut << fileIt->first << std::endl;
 
       for (std::vector<UnscannedEntry>::const_iterator incIt =
              fileIt->second->UnscannedEntries.begin();
            incIt != fileIt->second->UnscannedEntries.end(); ++incIt) {
-        cacheOut << incIt->FileName.c_str() << std::endl;
+        cacheOut << incIt->FileName << std::endl;
         if (incIt->QuotedLocation.empty()) {
           cacheOut << "-" << std::endl;
         } else {
-          cacheOut << incIt->QuotedLocation.c_str() << std::endl;
+          cacheOut << incIt->QuotedLocation << std::endl;
         }
       }
       cacheOut << std::endl;
diff --git a/Source/cmDependsC.h b/Source/cmDependsC.h
index e830aa8..3b5eb62 100644
--- a/Source/cmDependsC.h
+++ b/Source/cmDependsC.h
@@ -1,21 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependsC_h
 #define cmDependsC_h
 
+#include <cmConfigure.h>
+
 #include "cmDepends.h"
 
 #include <cmsys/RegularExpression.hxx>
+#include <iosfwd>
+#include <map>
 #include <queue>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmLocalGenerator;
 
 /** \class cmDependsC
  * \brief Dependency scanner for C and C++ object files.
@@ -31,14 +31,13 @@ public:
              const std::map<std::string, DependencyVector>* validDeps);
 
   /** Virtual destructor to cleanup subclasses properly.  */
-  virtual ~cmDependsC();
+  ~cmDependsC() CM_OVERRIDE;
 
 protected:
   // Implement writing/checking methods required by superclass.
-  virtual bool WriteDependencies(const std::set<std::string>& sources,
-                                 const std::string& obj,
-                                 std::ostream& makeDepends,
-                                 std::ostream& internalDepends);
+  bool WriteDependencies(const std::set<std::string>& sources,
+                         const std::string& obj, std::ostream& makeDepends,
+                         std::ostream& internalDepends) CM_OVERRIDE;
 
   // Method to scan a single file.
   void Scan(std::istream& is, const char* directory,
diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx
index 4608b5a..c1c8880 100644
--- a/Source/cmDependsFortran.cxx
+++ b/Source/cmDependsFortran.cxx
@@ -1,24 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsFortran.h"
 
+#include "cmFortranParser.h" /* Interface to parser object.  */
 #include "cmGeneratedFileStream.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSystemTools.h"
 
-#include "cmFortranParser.h" /* Interface to parser object.  */
 #include <assert.h>
 #include <cmsys/FStream.hxx>
+#include <iostream>
+#include <map>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
 
 // TODO: Test compiler for the case of the mod file.  Some always
 // use lower case and some always use upper case.  I do not know if any
@@ -53,7 +50,7 @@ public:
 };
 
 cmDependsFortran::cmDependsFortran()
-  : Internal(0)
+  : Internal(CM_NULLPTR)
 {
 }
 
@@ -91,8 +88,9 @@ cmDependsFortran::~cmDependsFortran()
 }
 
 bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources,
-                                         const std::string& obj, std::ostream&,
-                                         std::ostream&)
+                                         const std::string& obj,
+                                         std::ostream& /*makeDepends*/,
+                                         std::ostream& /*internalDepends*/)
 {
   // Make sure this is a scanning instance.
   if (sources.empty() || sources.begin()->empty()) {
@@ -123,6 +121,12 @@ bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources,
     if (cmFortran_yyparse(parser.Scanner) != 0) {
       // Failed to parse the file.  Report failure to write dependencies.
       okay = false;
+      /* clang-format off */
+      std::cerr <<
+        "warning: failed to parse dependencies from Fortran source "
+        "'" << src << "': " << parser.Error << std::endl
+        ;
+      /* clang-format on */
     }
   }
   return okay;
@@ -176,6 +180,8 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
     cmGeneratedFileStream fcStream(fcName.c_str());
     fcStream << "# Remove fortran modules provided by this target.\n";
     fcStream << "FILE(REMOVE";
+    std::string currentBinDir =
+      this->LocalGenerator->GetCurrentBinaryDirectory();
     for (std::set<std::string>::const_iterator i = provides.begin();
          i != provides.end(); ++i) {
       std::string mod_upper = mod_dir;
@@ -192,16 +198,16 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
       stamp += ".mod.stamp";
       fcStream << "\n";
       fcStream << "  \""
-               << this->LocalGenerator->Convert(
-                    mod_lower, cmOutputConverter::START_OUTPUT)
+               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
+                                                              mod_lower)
                << "\"\n";
       fcStream << "  \""
-               << this->LocalGenerator->Convert(
-                    mod_upper, cmOutputConverter::START_OUTPUT)
+               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
+                                                              mod_upper)
                << "\"\n";
       fcStream << "  \""
-               << this->LocalGenerator->Convert(
-                    stamp, cmOutputConverter::START_OUTPUT)
+               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
+                                                              stamp)
                << "\"\n";
     }
     fcStream << "  )\n";
@@ -316,19 +322,18 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
   const char* src = info.Source.c_str();
 
   // Write the include dependencies to the output stream.
-  std::string obj_i =
-    this->LocalGenerator->Convert(obj, cmOutputConverter::HOME_OUTPUT);
-  std::string obj_m = this->LocalGenerator->ConvertToOutputFormat(
-    obj_i, cmOutputConverter::MAKERULE);
+  std::string binDir = this->LocalGenerator->GetBinaryDirectory();
+  std::string obj_i = this->LocalGenerator->ConvertToRelativePath(binDir, obj);
+  std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
   internalDepends << obj_i << std::endl;
   internalDepends << " " << src << std::endl;
   for (std::set<std::string>::const_iterator i = info.Includes.begin();
        i != info.Includes.end(); ++i) {
-    makeDepends << obj_m << ": "
-                << this->LocalGenerator->Convert(
-                     *i, cmOutputConverter::HOME_OUTPUT,
-                     cmOutputConverter::MAKERULE)
-                << std::endl;
+    makeDepends
+      << obj_m << ": "
+      << cmSystemTools::ConvertToOutputPath(
+           this->LocalGenerator->ConvertToRelativePath(binDir, *i).c_str())
+      << std::endl;
     internalDepends << " " << *i << std::endl;
   }
   makeDepends << std::endl;
@@ -353,8 +358,8 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
       proxy += "/";
       proxy += *i;
       proxy += ".mod.proxy";
-      proxy = this->LocalGenerator->Convert(
-        proxy, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
+      proxy = cmSystemTools::ConvertToOutputPath(
+        this->LocalGenerator->ConvertToRelativePath(binDir, proxy).c_str());
 
       // since we require some things add them to our list of requirements
       makeDepends << obj_m << ".requires: " << proxy << std::endl;
@@ -369,17 +374,17 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     }
     if (!required->second.empty()) {
       // This module is known.  Depend on its timestamp file.
-      std::string stampFile = this->LocalGenerator->Convert(
-        required->second, cmOutputConverter::HOME_OUTPUT,
-        cmOutputConverter::MAKERULE);
+      std::string stampFile = cmSystemTools::ConvertToOutputPath(
+        this->LocalGenerator->ConvertToRelativePath(binDir, required->second)
+          .c_str());
       makeDepends << obj_m << ": " << stampFile << "\n";
     } else {
       // This module is not known to CMake.  Try to locate it where
       // the compiler will and depend on that.
       std::string module;
       if (this->FindModule(*i, module)) {
-        module = this->LocalGenerator->Convert(
-          module, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
+        module = cmSystemTools::ConvertToOutputPath(
+          this->LocalGenerator->ConvertToRelativePath(binDir, module).c_str());
         makeDepends << obj_m << ": " << module << "\n";
       }
     }
@@ -392,8 +397,8 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     proxy += "/";
     proxy += *i;
     proxy += ".mod.proxy";
-    proxy = this->LocalGenerator->Convert(
-      proxy, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
+    proxy = cmSystemTools::ConvertToOutputPath(
+      this->LocalGenerator->ConvertToRelativePath(binDir, proxy).c_str());
     makeDepends << proxy << ": " << obj_m << ".provides" << std::endl;
   }
 
@@ -414,14 +419,16 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
       std::string modFile = mod_dir;
       modFile += "/";
       modFile += *i;
-      modFile = this->LocalGenerator->Convert(
-        modFile, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::SHELL);
+      modFile = this->LocalGenerator->ConvertToOutputFormat(
+        this->LocalGenerator->ConvertToRelativePath(binDir, modFile),
+        cmOutputConverter::SHELL);
       std::string stampFile = stamp_dir;
       stampFile += "/";
       stampFile += m;
       stampFile += ".mod.stamp";
-      stampFile = this->LocalGenerator->Convert(
-        stampFile, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::SHELL);
+      stampFile = this->LocalGenerator->ConvertToOutputFormat(
+        this->LocalGenerator->ConvertToRelativePath(binDir, stampFile),
+        cmOutputConverter::SHELL);
       makeDepends << "\t$(CMAKE_COMMAND) -E cmake_copy_f90_mod " << modFile
                   << " " << stampFile;
       cmMakefile* mf = this->LocalGenerator->GetMakefile();
@@ -440,8 +447,8 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     // the target finishes building.
     std::string driver = this->TargetDirectory;
     driver += "/build";
-    driver = this->LocalGenerator->Convert(
-      driver, cmOutputConverter::HOME_OUTPUT, cmOutputConverter::MAKERULE);
+    driver = cmSystemTools::ConvertToOutputPath(
+      this->LocalGenerator->ConvertToRelativePath(binDir, driver).c_str());
     makeDepends << driver << ": " << obj_m << ".provides.build\n";
   }
 
@@ -520,7 +527,8 @@ bool cmDependsFortran::CopyModule(const std::vector<std::string>& args)
       }
     }
     return true;
-  } else if (cmSystemTools::FileExists(mod_lower.c_str(), true)) {
+  }
+  if (cmSystemTools::FileExists(mod_lower.c_str(), true)) {
     if (cmDependsFortran::ModulesDiffer(mod_lower.c_str(), stamp.c_str(),
                                         compilerId.c_str())) {
       if (!cmSystemTools::CopyFileAlways(mod_lower, stamp)) {
@@ -633,8 +641,8 @@ bool cmDependsFortran::ModulesDiffer(const char* modFile,
   cmsys::ifstream finModFile(modFile, std::ios::in | std::ios::binary);
   cmsys::ifstream finStampFile(stampFile, std::ios::in | std::ios::binary);
 #else
-  cmsys::ifstream finModFile(modFile, std::ios::in);
-  cmsys::ifstream finStampFile(stampFile, std::ios::in);
+  cmsys::ifstream finModFile(modFile);
+  cmsys::ifstream finStampFile(stampFile);
 #endif
   if (!finModFile || !finStampFile) {
     // At least one of the files does not exist.  The modules differ.
@@ -654,10 +662,9 @@ bool cmDependsFortran::ModulesDiffer(const char* modFile,
     // but also do not include a date so we can fall through to
     // compare them without skipping any prefix.
     unsigned char hdr[2];
-    bool okay =
-      finModFile.read(reinterpret_cast<char*>(hdr), 2) ? true : false;
+    bool okay = !finModFile.read(reinterpret_cast<char*>(hdr), 2).fail();
     finModFile.seekg(0);
-    if (!(okay && hdr[0] == 0x1f && hdr[1] == 0x8b)) {
+    if (!okay || hdr[0] != 0x1f || hdr[1] != 0x8b) {
       const char seq[1] = { '\n' };
       const int seqlen = 1;
 
@@ -699,10 +706,5 @@ bool cmDependsFortran::ModulesDiffer(const char* modFile,
   // Compare the remaining content.  If no compiler id matched above,
   // including the case none was given, this will compare the whole
   // content.
-  if (!cmFortranStreamsDiffer(finModFile, finStampFile)) {
-    return false;
-  }
-
-  // The modules are different.
-  return true;
+  return cmFortranStreamsDiffer(finModFile, finStampFile);
 }
diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h
index 5ff0b6c..8d347f4 100644
--- a/Source/cmDependsFortran.h
+++ b/Source/cmDependsFortran.h
@@ -1,21 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFortran_h
 #define cmFortran_h
 
+#include <cmConfigure.h>
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmDepends.h"
 
 class cmDependsFortranInternals;
 class cmFortranSourceInfo;
+class cmLocalGenerator;
 
 /** \class cmDependsFortran
  * \brief Dependency scanner for Fortran object files.
@@ -34,7 +32,7 @@ public:
   cmDependsFortran(cmLocalGenerator* lg);
 
   /** Virtual destructor to cleanup subclasses properly.  */
-  virtual ~cmDependsFortran();
+  ~cmDependsFortran() CM_OVERRIDE;
 
   /** Callback from build system after a .mod file has been generated
       by a Fortran90 compiler to copy the .mod file to the
@@ -48,8 +46,8 @@ public:
 
 protected:
   // Finalize the dependency information for the target.
-  virtual bool Finalize(std::ostream& makeDepends,
-                        std::ostream& internalDepends);
+  bool Finalize(std::ostream& makeDepends,
+                std::ostream& internalDepends) CM_OVERRIDE;
 
   // Find all the modules required by the target.
   void LocateModules();
@@ -59,10 +57,9 @@ protected:
   bool FindModule(std::string const& name, std::string& module);
 
   // Implement writing/checking methods required by superclass.
-  virtual bool WriteDependencies(const std::set<std::string>& sources,
-                                 const std::string& file,
-                                 std::ostream& makeDepends,
-                                 std::ostream& internalDepends);
+  bool WriteDependencies(const std::set<std::string>& sources,
+                         const std::string& file, std::ostream& makeDepends,
+                         std::ostream& internalDepends) CM_OVERRIDE;
 
   // Actually write the depenencies to the streams.
   bool WriteDependenciesReal(const char* obj, cmFortranSourceInfo const& info,
diff --git a/Source/cmDependsJava.cxx b/Source/cmDependsJava.cxx
index 4f5e2ae..29938ba 100644
--- a/Source/cmDependsJava.cxx
+++ b/Source/cmDependsJava.cxx
@@ -1,17 +1,7 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsJava.h"
 
-#include "cmDependsJavaParserHelper.h"
 #include "cmSystemTools.h"
 
 cmDependsJava::cmDependsJava()
@@ -23,8 +13,9 @@ cmDependsJava::~cmDependsJava()
 }
 
 bool cmDependsJava::WriteDependencies(const std::set<std::string>& sources,
-                                      const std::string&, std::ostream&,
-                                      std::ostream&)
+                                      const std::string& /*obj*/,
+                                      std::ostream& /*makeDepends*/,
+                                      std::ostream& /*internalDepends*/)
 {
   // Make sure this is a scanning instance.
   if (sources.empty() || sources.begin()->empty()) {
@@ -35,8 +26,9 @@ bool cmDependsJava::WriteDependencies(const std::set<std::string>& sources,
   return true;
 }
 
-bool cmDependsJava::CheckDependencies(std::istream&, const char*,
-                                      std::map<std::string, DependencyVector>&)
+bool cmDependsJava::CheckDependencies(
+  std::istream& /*internalDepends*/, const char* /*internalDependsFileName*/,
+  std::map<std::string, DependencyVector>& /*validDeps*/)
 {
   return true;
 }
diff --git a/Source/cmDependsJava.h b/Source/cmDependsJava.h
index 44723fa..1b9cca5 100644
--- a/Source/cmDependsJava.h
+++ b/Source/cmDependsJava.h
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependsJava_h
 #define cmDependsJava_h
 
+#include <cmConfigure.h>
+
 #include "cmDepends.h"
 
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+
 /** \class cmDependsJava
  * \brief Dependency scanner for Java class files.
  */
@@ -25,17 +23,16 @@ public:
   cmDependsJava();
 
   /** Virtual destructor to cleanup subclasses properly.  */
-  virtual ~cmDependsJava();
+  ~cmDependsJava() CM_OVERRIDE;
 
 protected:
   // Implement writing/checking methods required by superclass.
-  virtual bool WriteDependencies(const std::set<std::string>& sources,
-                                 const std::string& file,
-                                 std::ostream& makeDepends,
-                                 std::ostream& internalDepends);
-  virtual bool CheckDependencies(
+  bool WriteDependencies(const std::set<std::string>& sources,
+                         const std::string& file, std::ostream& makeDepends,
+                         std::ostream& internalDepends) CM_OVERRIDE;
+  bool CheckDependencies(
     std::istream& internalDepends, const char* internalDependsFileName,
-    std::map<std::string, DependencyVector>& validDeps);
+    std::map<std::string, DependencyVector>& validDeps) CM_OVERRIDE;
 
 private:
   cmDependsJava(cmDependsJava const&);  // Purposely not implemented.
diff --git a/Source/cmDependsJavaLexer.cxx b/Source/cmDependsJavaLexer.cxx
index f7676d9..aa4c4e0 100644
--- a/Source/cmDependsJavaLexer.cxx
+++ b/Source/cmDependsJavaLexer.cxx
@@ -1,3 +1,5 @@
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 #line 2 "cmDependsJavaLexer.cxx"
 
@@ -641,17 +643,8 @@ static yyconst flex_int16_t yy_chk[479] =
 #define YY_RESTORE_YY_MORE_OFFSET
 #line 1 "cmDependsJavaLexer.in.l"
 #line 2 "cmDependsJavaLexer.in.l"
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmDependsJavaLexer.h b/Source/cmDependsJavaLexer.h
index 61aa66d..e82db26 100644
--- a/Source/cmDependsJavaLexer.h
+++ b/Source/cmDependsJavaLexer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependsJava_yyHEADER_H
 #define cmDependsJava_yyHEADER_H 1
 #define cmDependsJava_yyIN_HEADER 1
diff --git a/Source/cmDependsJavaLexer.in.l b/Source/cmDependsJavaLexer.in.l
index aa2f8a5..fcc5693 100644
--- a/Source/cmDependsJavaLexer.in.l
+++ b/Source/cmDependsJavaLexer.in.l
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmDependsJavaParser.cxx b/Source/cmDependsJavaParser.cxx
index 899f4d2..b99d631 100644
--- a/Source/cmDependsJavaParser.cxx
+++ b/Source/cmDependsJavaParser.cxx
@@ -282,17 +282,8 @@
 /* Copy the first part of user declarations.  */
 #line 1 "cmDependsJavaParser.y"
 
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmDependsJavaParser.y b/Source/cmDependsJavaParser.y
index b66dc6d..91ee7c8 100644
--- a/Source/cmDependsJavaParser.y
+++ b/Source/cmDependsJavaParser.y
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx
index bd3ee4d..b5d68d0 100644
--- a/Source/cmDependsJavaParserHelper.cxx
+++ b/Source/cmDependsJavaParserHelper.cxx
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsJavaParserHelper.h"
 
+#include <cmConfigure.h>
+
 #include "cmDependsJavaLexer.h"
 #include "cmSystemTools.h"
+
 #include <cmsys/FStream.hxx>
+#include <iostream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 int cmDependsJava_yyparse(yyscan_t yyscanner);
 
@@ -35,7 +33,7 @@ cmDependsJavaParserHelper::~cmDependsJavaParserHelper()
 }
 
 void cmDependsJavaParserHelper::CurrentClass::AddFileNamesForPrinting(
-  std::vector<std::string>* files, const char* prefix, const char* sep)
+  std::vector<std::string>* files, const char* prefix, const char* sep) const
 {
   std::string rname = "";
   if (prefix) {
@@ -44,8 +42,8 @@ void cmDependsJavaParserHelper::CurrentClass::AddFileNamesForPrinting(
   }
   rname += this->Name;
   files->push_back(rname);
-  std::vector<CurrentClass>::iterator it;
-  for (it = this->NestedClasses->begin(); it != this->NestedClasses->end();
+  std::vector<CurrentClass>::const_iterator it;
+  for (it = this->NestedClasses.begin(); it != this->NestedClasses.end();
        ++it) {
     it->AddFileNamesForPrinting(files, rname.c_str(), sep);
   }
@@ -59,7 +57,7 @@ void cmDependsJavaParserHelper::DeallocateParserType(char** pt)
   if (!*pt) {
     return;
   }
-  *pt = 0;
+  *pt = CM_NULLPTR;
   this->UnionsAvailable--;
 }
 
@@ -160,13 +158,13 @@ void cmDependsJavaParserHelper::PrepareElement(
   cmDependsJavaParserHelper::ParserType* me)
 {
   // Inititalize self
-  me->str = 0;
+  me->str = CM_NULLPTR;
 }
 
 void cmDependsJavaParserHelper::AllocateParserType(
   cmDependsJavaParserHelper::ParserType* pt, const char* str, int len)
 {
-  pt->str = 0;
+  pt->str = CM_NULLPTR;
   if (len == 0) {
     len = (int)strlen(str);
   }
@@ -191,25 +189,19 @@ void cmDependsJavaParserHelper::StartClass(const char* cls)
 
 void cmDependsJavaParserHelper::EndClass()
 {
-  CurrentClass* parent = 0;
-  CurrentClass* current = 0;
-  if (!this->ClassStack.empty()) {
-    current = &(*(this->ClassStack.end() - 1));
-    if (this->ClassStack.size() > 1) {
-      parent = &(*(this->ClassStack.end() - 2));
-    }
-  }
-  if (current == 0) {
+  if (this->ClassStack.empty()) {
     std::cerr << "Error when parsing. Current class is null" << std::endl;
     abort();
   }
-  if (parent == 0) {
+  if (this->ClassStack.size() <= 1) {
     std::cerr << "Error when parsing. Parent class is null" << std::endl;
     abort();
   }
+  CurrentClass& current = this->ClassStack.back();
+  CurrentClass& parent = this->ClassStack[this->ClassStack.size() - 2];
   this->CurrentDepth--;
-  parent->NestedClasses->push_back(*current);
-  this->ClassStack.erase(this->ClassStack.end() - 1, this->ClassStack.end());
+  parent.NestedClasses.push_back(current);
+  this->ClassStack.pop_back();
 }
 
 void cmDependsJavaParserHelper::PrintClasses()
@@ -228,11 +220,11 @@ void cmDependsJavaParserHelper::PrintClasses()
 std::vector<std::string> cmDependsJavaParserHelper::GetFilesProduced()
 {
   std::vector<std::string> files;
-  CurrentClass* toplevel = &(*(this->ClassStack.begin()));
-  std::vector<CurrentClass>::iterator it;
-  for (it = toplevel->NestedClasses->begin();
-       it != toplevel->NestedClasses->end(); ++it) {
-    it->AddFileNamesForPrinting(&files, 0, "$");
+  CurrentClass const& toplevel = this->ClassStack.front();
+  std::vector<CurrentClass>::const_iterator it;
+  for (it = toplevel.NestedClasses.begin(); it != toplevel.NestedClasses.end();
+       ++it) {
+    it->AddFileNamesForPrinting(&files, CM_NULLPTR, "$");
   }
   return files;
 }
@@ -309,11 +301,10 @@ int cmDependsJavaParserHelper::LexInput(char* buf, int maxlen)
     if (buf[0] == '\n') {
       this->CurrentLine++;
     }
-    return (1);
-  } else {
-    buf[0] = '\n';
-    return (0);
+    return 1;
   }
+  buf[0] = '\n';
+  return 0;
 }
 void cmDependsJavaParserHelper::Error(const char* str)
 {
@@ -333,7 +324,7 @@ void cmDependsJavaParserHelper::Error(const char* str)
 void cmDependsJavaParserHelper::UpdateCombine(const char* str1,
                                               const char* str2)
 {
-  if (this->CurrentCombine == "" && str1 != 0) {
+  if (this->CurrentCombine == "" && str1 != CM_NULLPTR) {
     this->CurrentCombine = str1;
   }
   this->CurrentCombine += ".";
diff --git a/Source/cmDependsJavaParserHelper.h b/Source/cmDependsJavaParserHelper.h
index a13d023..1597ea7 100644
--- a/Source/cmDependsJavaParserHelper.h
+++ b/Source/cmDependsJavaParserHelper.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependsJavaParserHelper_h
 #define cmDependsJavaParserHelper_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 #define YYSTYPE cmDependsJavaParserHelper::ParserType
 #define YYSTYPE_IS_DECLARED
@@ -48,7 +42,7 @@ public:
 
   // For yacc
   void AddClassFound(const char* sclass);
-  void PrepareElement(ParserType* opt);
+  void PrepareElement(ParserType* me);
   void DeallocateParserType(char** pt);
   void CheckEmpty(int line, int cnt, ParserType* pt);
   void StartClass(const char* cls);
@@ -69,20 +63,9 @@ private:
   {
   public:
     std::string Name;
-    std::vector<CurrentClass>* NestedClasses;
-    CurrentClass() { this->NestedClasses = new std::vector<CurrentClass>; }
-    ~CurrentClass() { delete this->NestedClasses; }
-    CurrentClass& operator=(CurrentClass const& c)
-    {
-      this->NestedClasses->clear();
-      this->Name = c.Name;
-      std::copy(c.NestedClasses->begin(), c.NestedClasses->end(),
-                std::back_inserter(*this->NestedClasses));
-      return *this;
-    }
-    CurrentClass(CurrentClass const& c) { (*this) = c; }
+    std::vector<CurrentClass> NestedClasses;
     void AddFileNamesForPrinting(std::vector<std::string>* files,
-                                 const char* prefix, const char* sep);
+                                 const char* prefix, const char* sep) const;
   };
   std::string CurrentPackage;
   std::string::size_type InputBufferPos;
diff --git a/Source/cmDocumentation.cxx b/Source/cmDocumentation.cxx
index 68a8488..cb24adf 100644
--- a/Source/cmDocumentation.cxx
+++ b/Source/cmDocumentation.cxx
@@ -1,28 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDocumentation.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
+#include "cmDocumentationSection.h"
 #include "cmRST.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
 
-#include <cmsys/Directory.hxx>
+#include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
-
 #include <ctype.h>
-
-#include <algorithm>
+#include <string.h>
+#include <utility>
 
 static const char* cmDocumentationStandardOptions[][2] = {
   { "--help,-help,-usage,-h,-H,/?", "Print usage information and exit." },
@@ -49,12 +41,12 @@ static const char* cmDocumentationStandardOptions[][2] = {
   { "--help-variable-list [<f>]",
     "List variables with help available and exit." },
   { "--help-variables [<f>]", "Print cmake-variables manual and exit." },
-  { 0, 0 }
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationGeneratorsHeader[][2] = {
-  { 0, "The following generators are available on this platform:" },
-  { 0, 0 }
+  { CM_NULLPTR, "The following generators are available on this platform:" },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 cmDocumentation::cmDocumentation()
@@ -137,10 +129,10 @@ bool cmDocumentation::PrintRequestedDocumentation(std::ostream& os)
     this->CurrentArgument = i->Argument;
     // If a file name was given, use it.  Otherwise, default to the
     // given stream.
-    cmsys::ofstream* fout = 0;
+    cmsys::ofstream* fout = CM_NULLPTR;
     std::ostream* s = &os;
     if (!i->Filename.empty()) {
-      fout = new cmsys::ofstream(i->Filename.c_str(), std::ios::out);
+      fout = new cmsys::ofstream(i->Filename.c_str());
       if (fout) {
         s = fout;
       } else {
@@ -165,7 +157,7 @@ bool cmDocumentation::PrintRequestedDocumentation(std::ostream& os)
 
 #define GET_OPT_ARGUMENT(target)                                              \
   if ((i + 1 < argc) && !this->IsOption(argv[i + 1])) {                       \
-    target = argv[i + 1];                                                     \
+    (target) = argv[i + 1];                                                   \
     i = i + 1;                                                                \
   };
 
@@ -420,7 +412,7 @@ void cmDocumentation::SetSections(
 
 void cmDocumentation::PrependSection(const char* name, const char* docs[][2])
 {
-  cmDocumentationSection* sec = 0;
+  cmDocumentationSection* sec = CM_NULLPTR;
   if (this->AllSections.find(name) == this->AllSections.end()) {
     sec =
       new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -434,7 +426,7 @@ void cmDocumentation::PrependSection(const char* name, const char* docs[][2])
 void cmDocumentation::PrependSection(const char* name,
                                      std::vector<cmDocumentationEntry>& docs)
 {
-  cmDocumentationSection* sec = 0;
+  cmDocumentationSection* sec = CM_NULLPTR;
   if (this->AllSections.find(name) == this->AllSections.end()) {
     sec =
       new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -447,7 +439,7 @@ void cmDocumentation::PrependSection(const char* name,
 
 void cmDocumentation::AppendSection(const char* name, const char* docs[][2])
 {
-  cmDocumentationSection* sec = 0;
+  cmDocumentationSection* sec = CM_NULLPTR;
   if (this->AllSections.find(name) == this->AllSections.end()) {
     sec =
       new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -461,7 +453,7 @@ void cmDocumentation::AppendSection(const char* name, const char* docs[][2])
 void cmDocumentation::AppendSection(const char* name,
                                     std::vector<cmDocumentationEntry>& docs)
 {
-  cmDocumentationSection* sec = 0;
+  cmDocumentationSection* sec = CM_NULLPTR;
   if (this->AllSections.find(name) == this->AllSections.end()) {
     sec =
       new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -719,9 +711,8 @@ const char* cmDocumentation::GetNameString() const
 {
   if (!this->NameString.empty()) {
     return this->NameString.c_str();
-  } else {
-    return "CMake";
   }
+  return "CMake";
 }
 
 bool cmDocumentation::IsOption(const char* arg) const
diff --git a/Source/cmDocumentation.h b/Source/cmDocumentation.h
index dd99ca8..66afd2c 100644
--- a/Source/cmDocumentation.h
+++ b/Source/cmDocumentation.h
@@ -1,26 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef _cmDocumentation_h
 #define _cmDocumentation_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include "cmDocumentationFormatter.h"
-#include "cmDocumentationSection.h"
-#include "cmake.h"
 
-namespace cmsys {
-class Directory;
-}
+#include <iosfwd>
+#include <map>
+#include <string>
+#include <vector>
+
+class cmDocumentationSection;
+struct cmDocumentationEntry;
 
 /** Class to generate documentation.  */
 class cmDocumentation : public cmDocumentationEnums
@@ -39,7 +32,7 @@ public:
    * help arguments.
    */
   bool CheckOptions(int argc, const char* const* argv,
-                    const char* exitOpt = 0);
+                    const char* exitOpt = CM_NULLPTR);
 
   /**
    * Print help requested on the command line.  Call after
diff --git a/Source/cmDocumentationEntry.h b/Source/cmDocumentationEntry.h
new file mode 100644
index 0000000..1ccb82d
--- /dev/null
+++ b/Source/cmDocumentationEntry.h
@@ -0,0 +1,36 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmDocumentationEntry_h
+#define cmDocumentationEntry_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+
+/** Standard documentation entry for cmDocumentation's formatting.  */
+struct cmDocumentationEntry
+{
+  std::string Name;
+  std::string Brief;
+  cmDocumentationEntry() {}
+  cmDocumentationEntry(const char* doc[2])
+  {
+    if (doc[0]) {
+      this->Name = doc[0];
+    }
+    if (doc[1]) {
+      this->Brief = doc[1];
+    }
+  }
+  cmDocumentationEntry(const char* n, const char* b)
+  {
+    if (n) {
+      this->Name = n;
+    }
+    if (b) {
+      this->Brief = b;
+    }
+  }
+};
+
+#endif
diff --git a/Source/cmDocumentationFormatter.cxx b/Source/cmDocumentationFormatter.cxx
index 4816bb9..21a5209 100644
--- a/Source/cmDocumentationFormatter.cxx
+++ b/Source/cmDocumentationFormatter.cxx
@@ -1,18 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDocumentationFormatter.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmDocumentationSection.h"
 
+#include <ostream>
+#include <string.h>
+#include <string>
+#include <vector>
+
 cmDocumentationFormatter::cmDocumentationFormatter()
   : TextWidth(77)
   , TextIndent("")
diff --git a/Source/cmDocumentationFormatter.h b/Source/cmDocumentationFormatter.h
index 7c4c35b..ffa80f1 100644
--- a/Source/cmDocumentationFormatter.h
+++ b/Source/cmDocumentationFormatter.h
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef _cmDocumentationFormatter_h
 #define _cmDocumentationFormatter_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
 
 /** This is just a helper class to make it build with MSVC 6.0.
 Actually the enums and internal classes could directly go into
diff --git a/Source/cmDocumentationSection.cxx b/Source/cmDocumentationSection.cxx
index c6c87f4..c47f33e 100644
--- a/Source/cmDocumentationSection.cxx
+++ b/Source/cmDocumentationSection.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDocumentationSection.h"
 
 void cmDocumentationSection::Append(const char* data[][2])
diff --git a/Source/cmDocumentationSection.h b/Source/cmDocumentationSection.h
index 161a731..c1eb5c8 100644
--- a/Source/cmDocumentationSection.h
+++ b/Source/cmDocumentationSection.h
@@ -1,18 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef _cmDocumentationSection_h
 #define _cmDocumentationSection_h
 
-#include "cmDocumentationFormatter.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include "cmDocumentationEntry.h"
+
+#include <string>
+#include <vector>
 
 // Low-level interface for custom documents:
 /** Internal class representing a section of the documentation.
diff --git a/Source/cmDynamicLoader.cxx b/Source/cmDynamicLoader.cxx
index 7d0bbdc..a30b642 100644
--- a/Source/cmDynamicLoader.cxx
+++ b/Source/cmDynamicLoader.cxx
@@ -1,22 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmDynamicLoader.h"
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
+#include <cmConfigure.h>
 
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include "cmDynamicLoader.h"
+#include <cmsys/DynamicLoader.hxx>
+#include <map>
+#include <string>
+#include <utility>
 
 class cmDynamicLoaderCache
 {
 public:
   ~cmDynamicLoaderCache();
-  void CacheFile(const char* path, const cmsys::DynamicLoader::LibraryHandle&);
-  bool GetCacheFile(const char* path, cmsys::DynamicLoader::LibraryHandle&);
+  void CacheFile(const char* path,
+                 const cmsys::DynamicLoader::LibraryHandle& /*p*/);
+  bool GetCacheFile(const char* path,
+                    cmsys::DynamicLoader::LibraryHandle& /*p*/);
   bool FlushCache(const char* path);
   void FlushCache();
   static cmDynamicLoaderCache* GetInstance();
@@ -26,7 +26,7 @@ private:
   static cmDynamicLoaderCache* Instance;
 };
 
-cmDynamicLoaderCache* cmDynamicLoaderCache::Instance = 0;
+cmDynamicLoaderCache* cmDynamicLoaderCache::Instance = CM_NULLPTR;
 
 cmDynamicLoaderCache::~cmDynamicLoaderCache()
 {
@@ -75,7 +75,7 @@ void cmDynamicLoaderCache::FlushCache()
     cmsys::DynamicLoader::CloseLibrary(it->second);
   }
   delete cmDynamicLoaderCache::Instance;
-  cmDynamicLoaderCache::Instance = 0;
+  cmDynamicLoaderCache::Instance = CM_NULLPTR;
 }
 
 cmDynamicLoaderCache* cmDynamicLoaderCache::GetInstance()
diff --git a/Source/cmDynamicLoader.h b/Source/cmDynamicLoader.h
index 58d9ae9..d14f81e 100644
--- a/Source/cmDynamicLoader.h
+++ b/Source/cmDynamicLoader.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 // .NAME cmDynamicLoader - class interface to system dynamic libraries
 // .SECTION Description
 // cmDynamicLoader provides a portable interface to loading dynamic
@@ -17,7 +8,7 @@
 #ifndef cmDynamicLoader_h
 #define cmDynamicLoader_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/DynamicLoader.hxx>
 
diff --git a/Source/cmELF.cxx b/Source/cmELF.cxx
index 26f1a44..2d86674 100644
--- a/Source/cmELF.cxx
+++ b/Source/cmELF.cxx
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include "cmStandardIncludes.h" // to get CMAKE_USE_ELF_PARSER first
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmELF.h"
 
+#include <cm_auto_ptr.hxx>
+#include <cm_kwiml.h>
 #include <cmsys/FStream.hxx>
-#include <cmsys/auto_ptr.hxx>
+#include <map>
+#include <sstream>
+#include <stddef.h>
+#include <utility>
+#include <vector>
 
 // Include the ELF format information system header.
 #if defined(__OpenBSD__)
@@ -46,23 +41,26 @@ typedef struct Elf32_Rela Elf32_Rela;
 #if defined(__sun)
 #include <sys/link.h> // For dynamic section information
 #endif
+#ifdef _SCO_DS
+#include <link.h> // For DT_SONAME etc.
+#endif
 
 // Low-level byte swapping implementation.
 template <size_t s>
 struct cmELFByteSwapSize
 {
 };
-void cmELFByteSwap(char*, cmELFByteSwapSize<1> const&)
+void cmELFByteSwap(char* /*unused*/, cmELFByteSwapSize<1> const& /*unused*/)
 {
 }
-void cmELFByteSwap(char* data, cmELFByteSwapSize<2> const&)
+void cmELFByteSwap(char* data, cmELFByteSwapSize<2> const& /*unused*/)
 {
   char one_byte;
   one_byte = data[0];
   data[0] = data[1];
   data[1] = one_byte;
 }
-void cmELFByteSwap(char* data, cmELFByteSwapSize<4> const&)
+void cmELFByteSwap(char* data, cmELFByteSwapSize<4> const& /*unused*/)
 {
   char one_byte;
   one_byte = data[0];
@@ -72,7 +70,7 @@ void cmELFByteSwap(char* data, cmELFByteSwapSize<4> const&)
   data[1] = data[2];
   data[2] = one_byte;
 }
-void cmELFByteSwap(char* data, cmELFByteSwapSize<8> const&)
+void cmELFByteSwap(char* data, cmELFByteSwapSize<8> const& /*unused*/)
 {
   char one_byte;
   one_byte = data[0];
@@ -107,7 +105,7 @@ public:
   };
 
   // Construct and take ownership of the file stream object.
-  cmELFInternal(cmELF* external, cmsys::auto_ptr<cmsys::ifstream>& fin,
+  cmELFInternal(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin,
                 ByteOrderType order)
     : External(external)
     , Stream(*fin.release())
@@ -143,7 +141,7 @@ public:
   {
     this->Stream.seekg(pos);
     this->Stream.read(buf, size);
-    return this->Stream ? true : false;
+    return !this->Stream.fail();
   }
 
   // Lookup the SONAME in the DYNAMIC section.
@@ -214,6 +212,7 @@ struct cmELFTypes32
 };
 
 // Configure the implementation template for 64-bit ELF files.
+#ifndef _SCO_DS
 struct cmELFTypes64
 {
   typedef Elf64_Ehdr ELF_Ehdr;
@@ -223,6 +222,7 @@ struct cmELFTypes64
   typedef KWIML_INT_uint64_t tagtype;
   static const char* GetName() { return "64-bit"; }
 };
+#endif
 
 // Parser implementation template.
 template <class Types>
@@ -237,24 +237,24 @@ public:
   typedef typename Types::tagtype tagtype;
 
   // Construct with a stream and byte swap indicator.
-  cmELFInternalImpl(cmELF* external, cmsys::auto_ptr<cmsys::ifstream>& fin,
+  cmELFInternalImpl(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin,
                     ByteOrderType order);
 
   // Return the number of sections as specified by the ELF header.
-  virtual unsigned int GetNumberOfSections() const
+  unsigned int GetNumberOfSections() const CM_OVERRIDE
   {
     return static_cast<unsigned int>(this->ELFHeader.e_shnum);
   }
 
   // Get the file position and size of a dynamic section entry.
-  virtual unsigned int GetDynamicEntryCount();
-  virtual unsigned long GetDynamicEntryPosition(int j);
+  unsigned int GetDynamicEntryCount() CM_OVERRIDE;
+  unsigned long GetDynamicEntryPosition(int j) CM_OVERRIDE;
 
   // Lookup a string from the dynamic section with the given tag.
-  virtual StringEntry const* GetDynamicSectionString(unsigned int tag);
+  StringEntry const* GetDynamicSectionString(unsigned int tag) CM_OVERRIDE;
 
   // Print information about the ELF file.
-  virtual void PrintInfo(std::ostream& os) const
+  void PrintInfo(std::ostream& os) const CM_OVERRIDE
   {
     os << "ELF " << Types::GetName();
     if (this->ByteOrder == ByteOrderMSB) {
@@ -497,7 +497,7 @@ private:
         this->NeedSwap) {
       ByteSwap(x);
     }
-    return this->Stream ? true : false;
+    return !this->Stream.fail();
   }
   bool Read(ELF_Dyn& x)
   {
@@ -505,7 +505,7 @@ private:
         this->NeedSwap) {
       ByteSwap(x);
     }
-    return this->Stream ? true : false;
+    return !this->Stream.fail();
   }
 
   bool LoadSectionHeader(ELF_Half i)
@@ -537,8 +537,9 @@ private:
 };
 
 template <class Types>
-cmELFInternalImpl<Types>::cmELFInternalImpl(
-  cmELF* external, cmsys::auto_ptr<cmsys::ifstream>& fin, ByteOrderType order)
+cmELFInternalImpl<Types>::cmELFInternalImpl(cmELF* external,
+                                            CM_AUTO_PTR<cmsys::ifstream>& fin,
+                                            ByteOrderType order)
   : cmELFInternal(external, fin, order)
 {
   // Read the main header.
@@ -672,7 +673,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
     if (dssi->second.Position > 0) {
       return &dssi->second;
     }
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Create an entry for this tag.  Assume it is missing until found.
@@ -683,14 +684,14 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
 
   // Try reading the dynamic section.
   if (!this->LoadDynamicSection()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Get the string table referenced by the DYNAMIC section.
   ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
   if (sec.sh_link >= this->SectionHeaders.size()) {
     this->SetErrorMessage("Section DYNAMIC has invalid string table index.");
-    return 0;
+    return CM_NULLPTR;
   }
   ELF_Shdr const& strtab = this->SectionHeaders[sec.sh_link];
 
@@ -705,7 +706,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
       if (dyn.d_un.d_val >= strtab.sh_size) {
         this->SetErrorMessage("Section DYNAMIC references string beyond "
                               "the end of its string section.");
-        return 0;
+        return CM_NULLPTR;
       }
 
       // Seek to the position reported by the entry.
@@ -734,7 +735,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
       if (!this->Stream) {
         this->SetErrorMessage("Dynamic section specifies unreadable RPATH.");
         se.Value = "";
-        return 0;
+        return CM_NULLPTR;
       }
 
       // The value has been read successfully.  Report it.
@@ -745,17 +746,17 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
       return &se;
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 //============================================================================
 // External class implementation.
 
 cmELF::cmELF(const char* fname)
-  : Internal(0)
+  : Internal(CM_NULLPTR)
 {
   // Try to open the file.
-  cmsys::auto_ptr<cmsys::ifstream> fin(new cmsys::ifstream(fname));
+  CM_AUTO_PTR<cmsys::ifstream> fin(new cmsys::ifstream(fname));
 
   // Quit now if the file could not be opened.
   if (!fin.get() || !*fin) {
@@ -799,10 +800,14 @@ cmELF::cmELF(const char* fname)
   if (ident[EI_CLASS] == ELFCLASS32) {
     // 32-bit ELF
     this->Internal = new cmELFInternalImpl<cmELFTypes32>(this, fin, order);
-  } else if (ident[EI_CLASS] == ELFCLASS64) {
+  }
+#ifndef _SCO_DS
+  else if (ident[EI_CLASS] == ELFCLASS64) {
     // 64-bit ELF
     this->Internal = new cmELFInternalImpl<cmELFTypes64>(this, fin, order);
-  } else {
+  }
+#endif
+  else {
     this->ErrorMessage = "ELF file class is not 32-bit or 64-bit.";
     return;
   }
@@ -822,45 +827,40 @@ cmELF::FileType cmELF::GetFileType() const
 {
   if (this->Valid()) {
     return this->Internal->GetFileType();
-  } else {
-    return FileTypeInvalid;
   }
+  return FileTypeInvalid;
 }
 
 unsigned int cmELF::GetNumberOfSections() const
 {
   if (this->Valid()) {
     return this->Internal->GetNumberOfSections();
-  } else {
-    return 0;
   }
+  return 0;
 }
 
 unsigned int cmELF::GetDynamicEntryCount() const
 {
   if (this->Valid()) {
     return this->Internal->GetDynamicEntryCount();
-  } else {
-    return 0;
   }
+  return 0;
 }
 
 unsigned long cmELF::GetDynamicEntryPosition(int index) const
 {
   if (this->Valid()) {
     return this->Internal->GetDynamicEntryPosition(index);
-  } else {
-    return 0;
   }
+  return 0;
 }
 
 bool cmELF::ReadBytes(unsigned long pos, unsigned long size, char* buf) const
 {
   if (this->Valid()) {
     return this->Internal->ReadBytes(pos, size, buf);
-  } else {
-    return false;
   }
+  return false;
 }
 
 bool cmELF::GetSOName(std::string& soname)
@@ -868,9 +868,8 @@ bool cmELF::GetSOName(std::string& soname)
   if (StringEntry const* se = this->GetSOName()) {
     soname = se->Value;
     return true;
-  } else {
-    return false;
   }
+  return false;
 }
 
 cmELF::StringEntry const* cmELF::GetSOName()
@@ -878,9 +877,8 @@ cmELF::StringEntry const* cmELF::GetSOName()
   if (this->Valid() &&
       this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary) {
     return this->Internal->GetSOName();
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 cmELF::StringEntry const* cmELF::GetRPath()
@@ -889,9 +887,8 @@ cmELF::StringEntry const* cmELF::GetRPath()
       (this->Internal->GetFileType() == cmELF::FileTypeExecutable ||
        this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
     return this->Internal->GetRPath();
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 cmELF::StringEntry const* cmELF::GetRunPath()
@@ -900,9 +897,8 @@ cmELF::StringEntry const* cmELF::GetRunPath()
       (this->Internal->GetFileType() == cmELF::FileTypeExecutable ||
        this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
     return this->Internal->GetRunPath();
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 void cmELF::PrintInfo(std::ostream& os) const
diff --git a/Source/cmELF.h b/Source/cmELF.h
index 80832ad..7e7c1d6 100644
--- a/Source/cmELF.h
+++ b/Source/cmELF.h
@@ -1,17 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmELF_h
 #define cmELF_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
 #if !defined(CMAKE_USE_ELF_PARSER)
 #error "This file may be included only if CMAKE_USE_ELF_PARSER is enabled."
 #endif
diff --git a/Source/cmElseCommand.cxx b/Source/cmElseCommand.cxx
index 6db6f8d..16e53f6 100644
--- a/Source/cmElseCommand.cxx
+++ b/Source/cmElseCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmElseCommand.h"
 
 bool cmElseCommand::InitialPass(std::vector<std::string> const&,
diff --git a/Source/cmElseCommand.h b/Source/cmElseCommand.h
index 815825e..33f73ee 100644
--- a/Source/cmElseCommand.h
+++ b/Source/cmElseCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmElseCommand_h
 #define cmElseCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmElseCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmElseCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "else"; }
+  std::string GetName() const CM_OVERRIDE { return "else"; }
 
   cmTypeMacro(cmElseCommand, cmCommand);
 };
diff --git a/Source/cmElseIfCommand.cxx b/Source/cmElseIfCommand.cxx
index dc89e24..cc3624b 100644
--- a/Source/cmElseIfCommand.cxx
+++ b/Source/cmElseIfCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmElseIfCommand.h"
 
 bool cmElseIfCommand::InitialPass(std::vector<std::string> const&,
diff --git a/Source/cmElseIfCommand.h b/Source/cmElseIfCommand.h
index d0ffa5d..a489e30 100644
--- a/Source/cmElseIfCommand.h
+++ b/Source/cmElseIfCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmElseIfCommand_h
 #define cmElseIfCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmElseIfCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmElseIfCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "elseif"; }
+  std::string GetName() const CM_OVERRIDE { return "elseif"; }
 
   cmTypeMacro(cmElseIfCommand, cmCommand);
 };
diff --git a/Source/cmEnableLanguageCommand.cxx b/Source/cmEnableLanguageCommand.cxx
index 0ebe778..49fd6fd 100644
--- a/Source/cmEnableLanguageCommand.cxx
+++ b/Source/cmEnableLanguageCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEnableLanguageCommand.h"
 
 // cmEnableLanguageCommand
@@ -17,7 +8,7 @@ bool cmEnableLanguageCommand::InitialPass(std::vector<std::string> const& args,
 {
   bool optional = false;
   std::vector<std::string> languages;
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmEnableLanguageCommand.h b/Source/cmEnableLanguageCommand.h
index 657e4e5..98b3841 100644
--- a/Source/cmEnableLanguageCommand.h
+++ b/Source/cmEnableLanguageCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEnableLanguageCommand_h
 #define cmEnableLanguageCommand_h
 
@@ -28,19 +19,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEnableLanguageCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEnableLanguageCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "enable_language"; }
+  std::string GetName() const CM_OVERRIDE { return "enable_language"; }
 
   cmTypeMacro(cmEnableLanguageCommand, cmCommand);
 };
diff --git a/Source/cmEnableTestingCommand.cxx b/Source/cmEnableTestingCommand.cxx
index a9c60a8..d66c5b3 100644
--- a/Source/cmEnableTestingCommand.cxx
+++ b/Source/cmEnableTestingCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEnableTestingCommand.h"
 
 // we do this in the final pass so that we now the subdirs have all
diff --git a/Source/cmEnableTestingCommand.h b/Source/cmEnableTestingCommand.h
index a518f18..750ae8c 100644
--- a/Source/cmEnableTestingCommand.h
+++ b/Source/cmEnableTestingCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEnableTestingCommand_h
 #define cmEnableTestingCommand_h
 
@@ -33,19 +24,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEnableTestingCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEnableTestingCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "enable_testing"; }
+  std::string GetName() const CM_OVERRIDE { return "enable_testing"; }
 
   cmTypeMacro(cmEnableTestingCommand, cmCommand);
 };
diff --git a/Source/cmEndForEachCommand.cxx b/Source/cmEndForEachCommand.cxx
index 104b39a..7184bae 100644
--- a/Source/cmEndForEachCommand.cxx
+++ b/Source/cmEndForEachCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEndForEachCommand.h"
 
 bool cmEndForEachCommand::InvokeInitialPass(
diff --git a/Source/cmEndForEachCommand.h b/Source/cmEndForEachCommand.h
index ebc794f..3bcc7cf 100644
--- a/Source/cmEndForEachCommand.h
+++ b/Source/cmEndForEachCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEndForEachCommand_h
 #define cmEndForEachCommand_h
 
@@ -25,20 +16,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEndForEachCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEndForEachCommand; }
 
   /**
    * Override cmCommand::InvokeInitialPass to get arguments before
    * expansion.
    */
-  virtual bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -46,12 +38,12 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "endforeach"; }
+  std::string GetName() const CM_OVERRIDE { return "endforeach"; }
 
   cmTypeMacro(cmEndForEachCommand, cmCommand);
 };
diff --git a/Source/cmEndFunctionCommand.cxx b/Source/cmEndFunctionCommand.cxx
index b4bfa2d..82344c6 100644
--- a/Source/cmEndFunctionCommand.cxx
+++ b/Source/cmEndFunctionCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEndFunctionCommand.h"
 
 bool cmEndFunctionCommand::InvokeInitialPass(
diff --git a/Source/cmEndFunctionCommand.h b/Source/cmEndFunctionCommand.h
index b69dec0..8b4d2f9 100644
--- a/Source/cmEndFunctionCommand.h
+++ b/Source/cmEndFunctionCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEndFunctionCommand_h
 #define cmEndFunctionCommand_h
 
@@ -25,20 +16,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEndFunctionCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEndFunctionCommand; }
 
   /**
    * Override cmCommand::InvokeInitialPass to get arguments before
    * expansion.
    */
-  virtual bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -46,12 +38,12 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "endfunction"; }
+  std::string GetName() const CM_OVERRIDE { return "endfunction"; }
 
   cmTypeMacro(cmEndFunctionCommand, cmCommand);
 };
diff --git a/Source/cmEndIfCommand.cxx b/Source/cmEndIfCommand.cxx
index 1ae3a78..78a0d0f 100644
--- a/Source/cmEndIfCommand.cxx
+++ b/Source/cmEndIfCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEndIfCommand.h"
 
 #include <stdlib.h> // required for atof
diff --git a/Source/cmEndIfCommand.h b/Source/cmEndIfCommand.h
index 457dfd3..b476c72 100644
--- a/Source/cmEndIfCommand.h
+++ b/Source/cmEndIfCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEndIfCommand_h
 #define cmEndIfCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEndIfCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEndIfCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "endif"; }
+  std::string GetName() const CM_OVERRIDE { return "endif"; }
 
   cmTypeMacro(cmEndIfCommand, cmCommand);
 };
diff --git a/Source/cmEndMacroCommand.cxx b/Source/cmEndMacroCommand.cxx
index 435c05f..189d969 100644
--- a/Source/cmEndMacroCommand.cxx
+++ b/Source/cmEndMacroCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEndMacroCommand.h"
 
 bool cmEndMacroCommand::InvokeInitialPass(
diff --git a/Source/cmEndMacroCommand.h b/Source/cmEndMacroCommand.h
index 615e8dc..806750d 100644
--- a/Source/cmEndMacroCommand.h
+++ b/Source/cmEndMacroCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEndMacroCommand_h
 #define cmEndMacroCommand_h
 
@@ -25,20 +16,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEndMacroCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEndMacroCommand; }
 
   /**
    * Override cmCommand::InvokeInitialPass to get arguments before
    * expansion.
    */
-  virtual bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -46,12 +38,12 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "endmacro"; }
+  std::string GetName() const CM_OVERRIDE { return "endmacro"; }
 
   cmTypeMacro(cmEndMacroCommand, cmCommand);
 };
diff --git a/Source/cmEndWhileCommand.cxx b/Source/cmEndWhileCommand.cxx
index 33507de..b635168 100644
--- a/Source/cmEndWhileCommand.cxx
+++ b/Source/cmEndWhileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEndWhileCommand.h"
 
 bool cmEndWhileCommand::InvokeInitialPass(
diff --git a/Source/cmEndWhileCommand.h b/Source/cmEndWhileCommand.h
index 5eda7af..861d2f0 100644
--- a/Source/cmEndWhileCommand.h
+++ b/Source/cmEndWhileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmEndWhileCommand_h
 #define cmEndWhileCommand_h
 
@@ -25,20 +16,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmEndWhileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmEndWhileCommand; }
 
   /**
    * Override cmCommand::InvokeInitialPass to get arguments before
    * expansion.
    */
-  virtual bool InvokeInitialPass(std::vector<cmListFileArgument> const& args,
-                                 cmExecutionStatus& status);
+  bool InvokeInitialPass(std::vector<cmListFileArgument> const& args,
+                         cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -46,12 +38,12 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "endwhile"; }
+  std::string GetName() const CM_OVERRIDE { return "endwhile"; }
 
   cmTypeMacro(cmEndWhileCommand, cmCommand);
 };
diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx
index f3f8c2f..a3d6852 100644
--- a/Source/cmExecProgramCommand.cxx
+++ b/Source/cmExecProgramCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExecProgramCommand.h"
 
 #include "cmSystemTools.h"
@@ -19,7 +10,7 @@
 bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -90,7 +81,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
                                               args[1].c_str(), verbose);
   } else {
     result = cmExecProgramCommand::RunCommand(command.c_str(), output, retVal,
-                                              0, verbose);
+                                              CM_NULLPTR, verbose);
   }
   if (!result) {
     retVal = -1;
@@ -209,7 +200,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
   }
   fflush(stdout);
   fflush(stderr);
-  const char* cmd[] = { "/bin/sh", "-c", command, 0 };
+  const char* cmd[] = { "/bin/sh", "-c", command, CM_NULLPTR };
   cmsysProcess_SetCommand(cp, cmd);
 #endif
 
@@ -219,7 +210,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
   int length;
   char* data;
   int p;
-  while ((p = cmsysProcess_WaitForData(cp, &data, &length, 0), p)) {
+  while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     if (p == cmsysProcess_Pipe_STDOUT || p == cmsysProcess_Pipe_STDERR) {
       if (verbose) {
         cmSystemTools::Stdout(data, length);
@@ -229,7 +220,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
   }
 
   // All output has been read.  Wait for the process to exit.
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 
   // Check the result of running the process.
   std::string msg;
diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h
index e6e76d2..1cc46d3 100644
--- a/Source/cmExecProgramCommand.h
+++ b/Source/cmExecProgramCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExecProgramCommand_h
 #define cmExecProgramCommand_h
 
@@ -27,30 +18,31 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmExecProgramCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmExecProgramCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "exec_program"; }
+  std::string GetName() const CM_OVERRIDE { return "exec_program"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmExecProgramCommand, cmCommand);
 
 private:
   static bool RunCommand(const char* command, std::string& output, int& retVal,
-                         const char* directory = 0, bool verbose = true);
+                         const char* directory = CM_NULLPTR,
+                         bool verbose = true);
 };
 
 #endif
diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx
index 575cdc3..2bcf244 100644
--- a/Source/cmExecuteProcessCommand.cxx
+++ b/Source/cmExecuteProcessCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExecuteProcessCommand.h"
 
 #include "cmSystemTools.h"
@@ -31,7 +22,7 @@ void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
 bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -159,10 +150,9 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
     if (cmds[i].empty()) {
       this->SetError(" given COMMAND argument with no value.");
       return false;
-    } else {
-      // Add the null terminating pointer to the command argument list.
-      cmds[i].push_back(0);
     }
+    // Add the null terminating pointer to the command argument list.
+    cmds[i].push_back(CM_NULLPTR);
   }
 
   // Parse the timeout string.
@@ -228,7 +218,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
   int length;
   char* data;
   int p;
-  while ((p = cmsysProcess_WaitForData(cp, &data, &length, 0), p)) {
+  while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     // Put the output in the right place.
     if (p == cmsysProcess_Pipe_STDOUT && !output_quiet) {
       if (output_variable.empty()) {
@@ -246,7 +236,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   // All output has been read.  Wait for the process to exit.
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 
   // Fix the text in the output strings.
   cmExecuteProcessCommandFixText(tempOutput, output_strip_trailing_whitespace);
diff --git a/Source/cmExecuteProcessCommand.h b/Source/cmExecuteProcessCommand.h
index a89e705..f7e376a 100644
--- a/Source/cmExecuteProcessCommand.h
+++ b/Source/cmExecuteProcessCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExecuteProcessCommand_h
 #define cmExecuteProcessCommand_h
 
@@ -26,24 +17,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmExecuteProcessCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmExecuteProcessCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "execute_process"; }
+  std::string GetName() const CM_OVERRIDE { return "execute_process"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmExecuteProcessCommand, cmCommand);
 };
diff --git a/Source/cmExecutionStatus.h b/Source/cmExecutionStatus.h
index 508c6bd..7d4e97c 100644
--- a/Source/cmExecutionStatus.h
+++ b/Source/cmExecutionStatus.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExecutionStatus_h
 #define cmExecutionStatus_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmExecutionStatus
diff --git a/Source/cmExpandedCommandArgument.cxx b/Source/cmExpandedCommandArgument.cxx
index df7fba1..0bea65f 100644
--- a/Source/cmExpandedCommandArgument.cxx
+++ b/Source/cmExpandedCommandArgument.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExpandedCommandArgument.h"
 
 cmExpandedCommandArgument::cmExpandedCommandArgument()
diff --git a/Source/cmExpandedCommandArgument.h b/Source/cmExpandedCommandArgument.h
index 1f8e405..39cffce 100644
--- a/Source/cmExpandedCommandArgument.h
+++ b/Source/cmExpandedCommandArgument.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExpandedCommandArgument_h
 #define cmExpandedCommandArgument_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmExpandedCommandArgument
diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx
new file mode 100644
index 0000000..f5e6628
--- /dev/null
+++ b/Source/cmExportBuildAndroidMKGenerator.cxx
@@ -0,0 +1,196 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmExportBuildAndroidMKGenerator.h"
+
+#include "cmExportSet.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmTargetExport.h"
+
+#include <algorithm>
+
+cmExportBuildAndroidMKGenerator::cmExportBuildAndroidMKGenerator()
+{
+  this->LG = CM_NULLPTR;
+  this->ExportSet = CM_NULLPTR;
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateImportHeaderCode(
+  std::ostream& os, const std::string&)
+{
+  os << "LOCAL_PATH := $(call my-dir)\n\n";
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateImportFooterCode(std::ostream&)
+{
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateExpectedTargetsCode(
+  std::ostream&, const std::string&)
+{
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateImportTargetCode(
+  std::ostream& os, const cmGeneratorTarget* target)
+{
+  std::string targetName = this->Namespace;
+  targetName += target->GetExportName();
+  os << "include $(CLEAR_VARS)\n";
+  os << "LOCAL_MODULE := ";
+  os << targetName << "\n";
+  os << "LOCAL_SRC_FILES := ";
+  std::string path =
+    cmSystemTools::ConvertToOutputPath(target->GetFullPath().c_str());
+  os << path << "\n";
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateImportPropertyCode(
+  std::ostream&, const std::string&, cmGeneratorTarget const*,
+  ImportPropertyMap const&)
+{
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateMissingTargetsCheckCode(
+  std::ostream&, const std::vector<std::string>&)
+{
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
+  const cmGeneratorTarget* target, std::ostream& os,
+  const ImportPropertyMap& properties)
+{
+  std::string config = "";
+  if (!this->Configurations.empty()) {
+    config = this->Configurations[0];
+  }
+  cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
+    target, os, properties, cmExportBuildAndroidMKGenerator::BUILD, config);
+}
+
+void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
+  const cmGeneratorTarget* target, std::ostream& os,
+  const ImportPropertyMap& properties, GenerateType type,
+  std::string const& config)
+{
+  const bool newCMP0022Behavior =
+    target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
+    target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
+  if (!newCMP0022Behavior) {
+    std::ostringstream w;
+    if (type == cmExportBuildAndroidMKGenerator::BUILD) {
+      w << "export(TARGETS ... ANDROID_MK) called with policy CMP0022";
+    } else {
+      w << "install( EXPORT_ANDROID_MK ...) called with policy CMP0022";
+    }
+    w << " set to OLD for target " << target->Target->GetName() << ". "
+      << "The export will only work with CMP0022 set to NEW.";
+    target->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+  }
+  if (!properties.empty()) {
+    os << "LOCAL_CPP_FEATURES := rtti exceptions\n";
+    for (ImportPropertyMap::const_iterator pi = properties.begin();
+         pi != properties.end(); ++pi) {
+      if (pi->first == "INTERFACE_COMPILE_OPTIONS") {
+        os << "LOCAL_CPP_FEATURES += ";
+        os << (pi->second) << "\n";
+      } else if (pi->first == "INTERFACE_LINK_LIBRARIES") {
+        // need to look at list in pi->second and see if static or shared
+        // FindTargetToLink
+        // target->GetLocalGenerator()->FindGeneratorTargetToUse()
+        // then add to LOCAL_CPPFLAGS
+        std::vector<std::string> libraries;
+        cmSystemTools::ExpandListArgument(pi->second, libraries);
+        std::string staticLibs;
+        std::string sharedLibs;
+        std::string ldlibs;
+        for (std::vector<std::string>::iterator i = libraries.begin();
+             i != libraries.end(); ++i) {
+          cmGeneratorTarget* gt =
+            target->GetLocalGenerator()->FindGeneratorTargetToUse(*i);
+          if (gt) {
+
+            if (gt->GetType() == cmState::SHARED_LIBRARY ||
+                gt->GetType() == cmState::MODULE_LIBRARY) {
+              sharedLibs += " " + *i;
+            } else {
+              staticLibs += " " + *i;
+            }
+          } else {
+            // evaluate any generator expressions with the current
+            // build type of the makefile
+            cmGeneratorExpression ge;
+            CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+            std::string evaluated =
+              cge->Evaluate(target->GetLocalGenerator(), config);
+            bool relpath = false;
+            if (type == cmExportBuildAndroidMKGenerator::INSTALL) {
+              relpath = i->substr(0, 3) == "../";
+            }
+            // check for full path or if it already has a -l, or
+            // in the case of an install check for relative paths
+            // if it is full or a link library then use string directly
+            if (cmSystemTools::FileIsFullPath(evaluated) ||
+                evaluated.substr(0, 2) == "-l" || relpath) {
+              ldlibs += " " + evaluated;
+              // if it is not a path and does not have a -l then add -l
+            } else if (!evaluated.empty()) {
+              ldlibs += " -l" + evaluated;
+            }
+          }
+        }
+        if (!sharedLibs.empty()) {
+          os << "LOCAL_SHARED_LIBRARIES :=" << sharedLibs << "\n";
+        }
+        if (!staticLibs.empty()) {
+          os << "LOCAL_STATIC_LIBRARIES :=" << staticLibs << "\n";
+        }
+        if (!ldlibs.empty()) {
+          os << "LOCAL_EXPORT_LDLIBS :=" << ldlibs << "\n";
+        }
+      } else if (pi->first == "INTERFACE_INCLUDE_DIRECTORIES") {
+        std::string includes = pi->second;
+        std::vector<std::string> includeList;
+        cmSystemTools::ExpandListArgument(includes, includeList);
+        os << "LOCAL_EXPORT_C_INCLUDES := ";
+        std::string end;
+        for (std::vector<std::string>::iterator i = includeList.begin();
+             i != includeList.end(); ++i) {
+          os << end << *i;
+          end = "\\\n";
+        }
+        os << "\n";
+      } else {
+        os << "# " << pi->first << " " << (pi->second) << "\n";
+      }
+    }
+  }
+
+  // Tell the NDK build system if prebuilt static libraries use C++.
+  if (target->GetType() == cmState::STATIC_LIBRARY) {
+    cmLinkImplementation const* li = target->GetLinkImplementation(config);
+    if (std::find(li->Languages.begin(), li->Languages.end(), "CXX") !=
+        li->Languages.end()) {
+      os << "LOCAL_HAS_CPP := true\n";
+    }
+  }
+
+  switch (target->GetType()) {
+    case cmState::SHARED_LIBRARY:
+    case cmState::MODULE_LIBRARY:
+      os << "include $(PREBUILT_SHARED_LIBRARY)\n";
+      break;
+    case cmState::STATIC_LIBRARY:
+      os << "include $(PREBUILT_STATIC_LIBRARY)\n";
+      break;
+    case cmState::EXECUTABLE:
+    case cmState::UTILITY:
+    case cmState::OBJECT_LIBRARY:
+    case cmState::GLOBAL_TARGET:
+    case cmState::INTERFACE_LIBRARY:
+    case cmState::UNKNOWN_LIBRARY:
+      break;
+  }
+  os << "\n";
+}
diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h
new file mode 100644
index 0000000..c9e0145
--- /dev/null
+++ b/Source/cmExportBuildAndroidMKGenerator.h
@@ -0,0 +1,60 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmExportBuildAndroidMKGenerator_h
+#define cmExportBuildAndroidMKGenerator_h
+
+#include "cmExportBuildFileGenerator.h"
+#include "cmListFileCache.h"
+
+class cmExportSet;
+
+/** \class cmExportBuildAndroidMKGenerator
+ * \brief Generate a file exporting targets from a build tree.
+ *
+ * cmExportBuildAndroidMKGenerator generates a file exporting targets from
+ * a build tree.  This exports the targets to the Android ndk build tool
+ * makefile format for prebuilt libraries.
+ *
+ * This is used to implement the EXPORT() command.
+ */
+class cmExportBuildAndroidMKGenerator : public cmExportBuildFileGenerator
+{
+public:
+  cmExportBuildAndroidMKGenerator();
+  // this is so cmExportInstallAndroidMKGenerator can share this
+  // function as they are almost the same
+  enum GenerateType
+  {
+    BUILD,
+    INSTALL
+  };
+  static void GenerateInterfaceProperties(cmGeneratorTarget const* target,
+                                          std::ostream& os,
+                                          const ImportPropertyMap& properties,
+                                          GenerateType type,
+                                          std::string const& config);
+
+protected:
+  // Implement virtual methods from the superclass.
+  void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {}
+  void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {}
+  void GenerateImportHeaderCode(std::ostream& os,
+                                const std::string& config = "") CM_OVERRIDE;
+  void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE;
+  void GenerateImportTargetCode(std::ostream& os,
+                                const cmGeneratorTarget* target) CM_OVERRIDE;
+  void GenerateExpectedTargetsCode(
+    std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE;
+  void GenerateImportPropertyCode(std::ostream& os, const std::string& config,
+                                  cmGeneratorTarget const* target,
+                                  ImportPropertyMap const& properties)
+    CM_OVERRIDE;
+  void GenerateMissingTargetsCheckCode(
+    std::ostream& os,
+    const std::vector<std::string>& missingTargets) CM_OVERRIDE;
+  void GenerateInterfaceProperties(
+    cmGeneratorTarget const* target, std::ostream& os,
+    const ImportPropertyMap& properties) CM_OVERRIDE;
+};
+
+#endif
diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx
index 8ca7a11..68831c7 100644
--- a/Source/cmExportBuildFileGenerator.cxx
+++ b/Source/cmExportBuildFileGenerator.cxx
@@ -1,25 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportBuildFileGenerator.h"
 
 #include "cmExportSet.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTargetExport.h"
+#include "cmake.h"
+
+#include <algorithm>
+#include <map>
+#include <set>
+#include <sstream>
+#include <utility>
 
 cmExportBuildFileGenerator::cmExportBuildFileGenerator()
 {
-  this->LG = 0;
-  this->ExportSet = 0;
+  this->LG = CM_NULLPTR;
+  this->ExportSet = CM_NULLPTR;
 }
 
 void cmExportBuildFileGenerator::Compute(cmLocalGenerator* lg)
@@ -211,11 +216,10 @@ void cmExportBuildFileGenerator::HandleMissingTarget(
       link_libs += missingTarget;
       missingTargets.push_back(missingTarget);
       return;
-    } else {
-      // We are not appending, so all exported targets should be
-      // known here.  This is probably user-error.
-      this->ComplainAboutMissingTarget(depender, dependee, targetOccurrences);
     }
+    // We are not appending, so all exported targets should be
+    // known here.  This is probably user-error.
+    this->ComplainAboutMissingTarget(depender, dependee, targetOccurrences);
   }
   // Assume the target will be exported by another command.
   // Append it with the export namespace.
diff --git a/Source/cmExportBuildFileGenerator.h b/Source/cmExportBuildFileGenerator.h
index be3c70a..0539b6a 100644
--- a/Source/cmExportBuildFileGenerator.h
+++ b/Source/cmExportBuildFileGenerator.h
@@ -1,21 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportBuildFileGenerator_h
 #define cmExportBuildFileGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExportFileGenerator.h"
-#include "cmListFileCache.h"
+
+#include <iosfwd>
+#include <string>
+#include <vector>
 
 class cmExportSet;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmLocalGenerator;
 
 /** \class cmExportBuildFileGenerator
  * \brief Generate a file exporting targets from a build tree.
@@ -50,14 +49,14 @@ public:
 
 protected:
   // Implement virtual methods from the superclass.
-  virtual bool GenerateMainFile(std::ostream& os);
-  virtual void GenerateImportTargetsConfig(
+  bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
+  void GenerateImportTargetsConfig(
     std::ostream& os, const std::string& config, std::string const& suffix,
-    std::vector<std::string>& missingTargets);
-  virtual void HandleMissingTarget(std::string& link_libs,
-                                   std::vector<std::string>& missingTargets,
-                                   cmGeneratorTarget* depender,
-                                   cmGeneratorTarget* dependee);
+    std::vector<std::string>& missingTargets) CM_OVERRIDE;
+  void HandleMissingTarget(std::string& link_libs,
+                           std::vector<std::string>& missingTargets,
+                           cmGeneratorTarget* depender,
+                           cmGeneratorTarget* dependee) CM_OVERRIDE;
 
   void ComplainAboutMissingTarget(cmGeneratorTarget* depender,
                                   cmGeneratorTarget* dependee,
@@ -70,7 +69,7 @@ protected:
                                  ImportPropertyMap& properties);
 
   std::string InstallNameDir(cmGeneratorTarget* target,
-                             const std::string& config);
+                             const std::string& config) CM_OVERRIDE;
 
   std::vector<std::string> FindNamespaces(cmGlobalGenerator* gg,
                                           const std::string& name);
diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx
index a0e7e45..d438363 100644
--- a/Source/cmExportCommand.cxx
+++ b/Source/cmExportCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportCommand.h"
 
 #include "cmGeneratedFileStream.h"
@@ -18,6 +9,7 @@
 #include <cmsys/Encoding.hxx>
 #include <cmsys/RegularExpression.hxx>
 
+#include "cmExportBuildAndroidMKGenerator.h"
 #include "cmExportBuildFileGenerator.h"
 
 #if defined(__HAIKU__)
@@ -34,8 +26,9 @@ cmExportCommand::cmExportCommand()
   , Namespace(&Helper, "NAMESPACE", &ArgumentGroup)
   , Filename(&Helper, "FILE", &ArgumentGroup)
   , ExportOld(&Helper, "EXPORT_LINK_INTERFACE_LIBRARIES", &ArgumentGroup)
+  , AndroidMKFile(&Helper, "ANDROID_MK")
 {
-  this->ExportSet = 0;
+  this->ExportSet = CM_NULLPTR;
 }
 
 // cmExportCommand
@@ -49,11 +42,12 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
 
   if (args[0] == "PACKAGE") {
     return this->HandlePackage(args);
-  } else if (args[0] == "EXPORT") {
-    this->ExportSetName.Follows(0);
+  }
+  if (args[0] == "EXPORT") {
+    this->ExportSetName.Follows(CM_NULLPTR);
     this->ArgumentGroup.Follows(&this->ExportSetName);
   } else {
-    this->Targets.Follows(0);
+    this->Targets.Follows(CM_NULLPTR);
     this->ArgumentGroup.Follows(&this->Targets);
   }
 
@@ -66,13 +60,18 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   std::string fname;
-  if (!this->Filename.WasFound()) {
+  bool android = false;
+  if (this->AndroidMKFile.WasFound()) {
+    fname = this->AndroidMKFile.GetString();
+    android = true;
+  }
+  if (!this->Filename.WasFound() && fname.empty()) {
     if (args[0] != "EXPORT") {
       this->SetError("FILE <filename> option missing.");
       return false;
     }
     fname = this->ExportSetName.GetString() + ".cmake";
-  } else {
+  } else if (fname.empty()) {
     // Make sure the file has a .cmake extension.
     if (cmSystemTools::GetFilenameLastExtension(this->Filename.GetCString()) !=
         ".cmake") {
@@ -176,7 +175,12 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   // Setup export file generation.
-  cmExportBuildFileGenerator* ebfg = new cmExportBuildFileGenerator;
+  cmExportBuildFileGenerator* ebfg = CM_NULLPTR;
+  if (android) {
+    ebfg = new cmExportBuildAndroidMKGenerator;
+  } else {
+    ebfg = new cmExportBuildFileGenerator;
+  }
   ebfg->SetExportFile(fname.c_str());
   ebfg->SetNamespace(this->Namespace.GetCString());
   ebfg->SetAppendMode(this->Append.IsEnabled());
@@ -327,11 +331,10 @@ void cmExportCommand::StorePackageRegistryDir(std::string const& package,
   fname += "/cmake/packages/";
   fname += package;
 #else
-  const char* home = cmSystemTools::GetEnv("HOME");
-  if (!home) {
+  std::string fname;
+  if (!cmSystemTools::GetEnv("HOME", fname)) {
     return;
   }
-  std::string fname = home;
   cmSystemTools::ConvertToUnixSlashes(fname);
   fname += "/.cmake/packages/";
   fname += package;
diff --git a/Source/cmExportCommand.h b/Source/cmExportCommand.h
index a71393a..ebde71c 100644
--- a/Source/cmExportCommand.h
+++ b/Source/cmExportCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportCommand_h
 #define cmExportCommand_h
 
@@ -30,19 +21,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmExportCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmExportCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "export"; }
+  std::string GetName() const CM_OVERRIDE { return "export"; }
 
   cmTypeMacro(cmExportCommand, cmCommand);
 
@@ -54,6 +45,7 @@ private:
   cmCAString Namespace;
   cmCAString Filename;
   cmCAEnabler ExportOld;
+  cmCAString AndroidMKFile;
 
   cmExportSet* ExportSet;
 
diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx
index 736c7da..d3a99fa 100644
--- a/Source/cmExportFileGenerator.cxx
+++ b/Source/cmExportFileGenerator.cxx
@@ -1,32 +1,28 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportFileGenerator.h"
 
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
-#include "cmExportSet.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmInstallExportGenerator.h"
+#include "cmGeneratorTarget.h"
+#include "cmLinkItem.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTargetExport.h"
-#include "cmVersion.h"
+#include "cmake.h"
 
 #include <assert.h>
+#include <cm_auto_ptr.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/auto_ptr.hxx>
+#include <sstream>
+#include <string.h>
+#include <utility>
 
 static std::string cmExportFileGeneratorEscape(std::string const& str)
 {
@@ -69,15 +65,15 @@ const char* cmExportFileGenerator::GetMainExportFileName() const
 bool cmExportFileGenerator::GenerateImportFile()
 {
   // Open the output file to generate it.
-  cmsys::auto_ptr<cmsys::ofstream> foutPtr;
+  CM_AUTO_PTR<cmsys::ofstream> foutPtr;
   if (this->AppendMode) {
     // Open for append.
-    cmsys::auto_ptr<cmsys::ofstream> ap(
+    CM_AUTO_PTR<cmsys::ofstream> ap(
       new cmsys::ofstream(this->MainImportFile.c_str(), std::ios::app));
     foutPtr = ap;
   } else {
     // Generate atomically and with copy-if-different.
-    cmsys::auto_ptr<cmGeneratedFileStream> ap(
+    CM_AUTO_PTR<cmGeneratedFileStream> ap(
       new cmGeneratedFileStream(this->MainImportFile.c_str(), true));
     ap->SetCopyIfDifferent(true);
     foutPtr = ap;
@@ -91,24 +87,8 @@ bool cmExportFileGenerator::GenerateImportFile()
   }
   std::ostream& os = *foutPtr;
 
-  // Protect that file against use with older CMake versions.
-  /* clang-format off */
-  os << "# Generated by CMake " << cmVersion::GetCMakeVersion() << "\n\n";
-  os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
-     << "   message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
-     << "endif()\n";
-  /* clang-format on */
-
-  // Isolate the file policy level.
-  // We use 2.6 here instead of the current version because newer
-  // versions of CMake should be able to export files imported by 2.6
-  // until the import format changes.
-  /* clang-format off */
-  os << "cmake_policy(PUSH)\n"
-     << "cmake_policy(VERSION 2.6)\n";
-  /* clang-format on */
-
   // Start with the import file header.
+  this->GeneratePolicyHeaderCode(os);
   this->GenerateImportHeaderCode(os);
 
   // Create all the imported targets.
@@ -116,7 +96,7 @@ bool cmExportFileGenerator::GenerateImportFile()
 
   // End with the import file footer.
   this->GenerateImportFooterCode(os);
-  os << "cmake_policy(POP)\n";
+  this->GeneratePolicyFooterCode(os);
 
   return result;
 }
@@ -393,7 +373,7 @@ void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
   std::string dirs = cmGeneratorExpression::Preprocess(
     tei->InterfaceIncludeDirectories, preprocessRule, true);
   this->ReplaceInstallPrefix(dirs);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
   std::string exportDirs =
     cge->Evaluate(target->GetLocalGenerator(), "", false, target);
 
@@ -679,7 +659,7 @@ void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
   }
 }
 
-void cmExportFileGenerator::ReplaceInstallPrefix(std::string&)
+void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
 {
   // Do nothing
 }
@@ -827,6 +807,31 @@ void cmExportFileGenerator::SetImportLinkProperty(
   properties[prop] = link_entries;
 }
 
+void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
+{
+  // Protect that file against use with older CMake versions.
+  /* clang-format off */
+  os << "# Generated by CMake\n\n";
+  os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
+     << "   message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
+     << "endif()\n";
+  /* clang-format on */
+
+  // Isolate the file policy level.
+  // We use 2.6 here instead of the current version because newer
+  // versions of CMake should be able to export files imported by 2.6
+  // until the import format changes.
+  /* clang-format off */
+  os << "cmake_policy(PUSH)\n"
+     << "cmake_policy(VERSION 2.6)\n";
+  /* clang-format on */
+}
+
+void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
+{
+  os << "cmake_policy(POP)\n";
+}
+
 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
                                                      const std::string& config)
 {
diff --git a/Source/cmExportFileGenerator.h b/Source/cmExportFileGenerator.h
index 9c96015..e7712d2 100644
--- a/Source/cmExportFileGenerator.h
+++ b/Source/cmExportFileGenerator.h
@@ -1,22 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportFileGenerator_h
 #define cmExportFileGenerator_h
 
-#include "cmCommand.h"
-#include "cmGeneratorExpression.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
+#include "cmGeneratorExpression.h"
 #include "cmVersion.h"
-#include "cmVersionMacros.h"
+#include "cmVersionConfig.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmGeneratorTarget;
 
 #define STRINGIFY_HELPER(X) #X
 #define STRINGIFY(X) STRINGIFY_HELPER(X)
@@ -70,25 +69,28 @@ protected:
                             std::vector<std::string>& missingTargets);
 
   // Methods to implement export file code generation.
-  void GenerateImportHeaderCode(std::ostream& os,
-                                const std::string& config = "");
-  void GenerateImportFooterCode(std::ostream& os);
+  virtual void GeneratePolicyHeaderCode(std::ostream& os);
+  virtual void GeneratePolicyFooterCode(std::ostream& os);
+  virtual void GenerateImportHeaderCode(std::ostream& os,
+                                        const std::string& config = "");
+  virtual void GenerateImportFooterCode(std::ostream& os);
   void GenerateImportVersionCode(std::ostream& os);
-  void GenerateImportTargetCode(std::ostream& os,
-                                cmGeneratorTarget const* target);
-  void GenerateImportPropertyCode(std::ostream& os, const std::string& config,
-                                  cmGeneratorTarget const* target,
-                                  ImportPropertyMap const& properties);
-  void GenerateImportedFileChecksCode(
+  virtual void GenerateImportTargetCode(std::ostream& os,
+                                        cmGeneratorTarget const* target);
+  virtual void GenerateImportPropertyCode(std::ostream& os,
+                                          const std::string& config,
+                                          cmGeneratorTarget const* target,
+                                          ImportPropertyMap const& properties);
+  virtual void GenerateImportedFileChecksCode(
     std::ostream& os, cmGeneratorTarget* target,
     ImportPropertyMap const& properties,
     const std::set<std::string>& importedLocations);
-  void GenerateImportedFileCheckLoop(std::ostream& os);
-  void GenerateMissingTargetsCheckCode(
+  virtual void GenerateImportedFileCheckLoop(std::ostream& os);
+  virtual void GenerateMissingTargetsCheckCode(
     std::ostream& os, const std::vector<std::string>& missingTargets);
 
-  void GenerateExpectedTargetsCode(std::ostream& os,
-                                   const std::string& expectedTargets);
+  virtual void GenerateExpectedTargetsCode(std::ostream& os,
+                                           const std::string& expectedTargets);
 
   // Collect properties with detailed information about targets beyond
   // their location on disk.
@@ -132,9 +134,9 @@ protected:
                                  ImportPropertyMap& properties);
   void PopulateCompatibleInterfaceProperties(cmGeneratorTarget* target,
                                              ImportPropertyMap& properties);
-  void GenerateInterfaceProperties(cmGeneratorTarget const* target,
-                                   std::ostream& os,
-                                   const ImportPropertyMap& properties);
+  virtual void GenerateInterfaceProperties(
+    cmGeneratorTarget const* target, std::ostream& os,
+    const ImportPropertyMap& properties);
   void PopulateIncludeDirectoriesInterface(
     cmTargetExport* target,
     cmGeneratorExpression::PreprocessContext preprocessRule,
@@ -161,8 +163,8 @@ protected:
     std::vector<std::string>& missingTargets,
     FreeTargetsReplace replace = NoReplaceFreeTargets);
 
-  void GenerateRequiredCMakeVersion(std::ostream& os,
-                                    const char* versionString);
+  virtual void GenerateRequiredCMakeVersion(std::ostream& os,
+                                            const char* versionString);
 
   // The namespace in which the exports are placed in the generated file.
   std::string Namespace;
diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx
new file mode 100644
index 0000000..58b7510
--- /dev/null
+++ b/Source/cmExportInstallAndroidMKGenerator.cxx
@@ -0,0 +1,137 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmExportInstallAndroidMKGenerator.h"
+
+#include "cmAlgorithms.h"
+#include "cmExportBuildAndroidMKGenerator.h"
+#include "cmExportSet.h"
+#include "cmExportSetMap.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmInstallExportGenerator.h"
+#include "cmInstallTargetGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmTargetExport.h"
+
+cmExportInstallAndroidMKGenerator::cmExportInstallAndroidMKGenerator(
+  cmInstallExportGenerator* iegen)
+  : cmExportInstallFileGenerator(iegen)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode(
+  std::ostream& os, const std::string&)
+{
+  std::string installDir = this->IEGen->GetDestination();
+  os << "LOCAL_PATH := $(call my-dir)\n";
+  size_t numDotDot = cmSystemTools::CountChar(installDir.c_str(), '/');
+  numDotDot += (installDir.size() > 0) ? 1 : 0;
+  std::string path;
+  for (size_t n = 0; n < numDotDot; n++) {
+    path += "/..";
+  }
+  os << "_IMPORT_PREFIX := "
+     << "$(LOCAL_PATH)" << path << "\n\n";
+  for (std::vector<cmTargetExport*>::const_iterator tei =
+         this->IEGen->GetExportSet()->GetTargetExports()->begin();
+       tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) {
+    // Collect import properties for this target.
+    cmTargetExport const* te = *tei;
+    if (te->Target->GetType() == cmState::INTERFACE_LIBRARY) {
+      continue;
+    }
+    std::string dest;
+    if (te->LibraryGenerator) {
+      dest = te->LibraryGenerator->GetDestination("");
+    }
+    if (te->ArchiveGenerator) {
+      dest = te->ArchiveGenerator->GetDestination("");
+    }
+    te->Target->Target->SetProperty("__dest", dest.c_str());
+  }
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportFooterCode(std::ostream&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportTargetCode(
+  std::ostream& os, const cmGeneratorTarget* target)
+{
+  std::string targetName = this->Namespace;
+  targetName += target->GetExportName();
+  os << "include $(CLEAR_VARS)\n";
+  os << "LOCAL_MODULE := ";
+  os << targetName << "\n";
+  os << "LOCAL_SRC_FILES := $(_IMPORT_PREFIX)/";
+  os << target->Target->GetProperty("__dest") << "/";
+  std::string config = "";
+  if (!this->Configurations.empty()) {
+    config = this->Configurations[0];
+  }
+  os << target->GetFullName(config) << "\n";
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateExpectedTargetsCode(
+  std::ostream&, const std::string&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportPropertyCode(
+  std::ostream&, const std::string&, cmGeneratorTarget const*,
+  ImportPropertyMap const&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateMissingTargetsCheckCode(
+  std::ostream&, const std::vector<std::string>&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateInterfaceProperties(
+  cmGeneratorTarget const* target, std::ostream& os,
+  const ImportPropertyMap& properties)
+{
+  std::string config = "";
+  if (!this->Configurations.empty()) {
+    config = this->Configurations[0];
+  }
+  cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
+    target, os, properties, cmExportBuildAndroidMKGenerator::INSTALL, config);
+}
+
+void cmExportInstallAndroidMKGenerator::LoadConfigFiles(std::ostream&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportPrefix(std::ostream&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateRequiredCMakeVersion(
+  std::ostream&, const char*)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::CleanupTemporaryVariables(
+  std::ostream&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportedFileCheckLoop(
+  std::ostream&)
+{
+}
+
+void cmExportInstallAndroidMKGenerator::GenerateImportedFileChecksCode(
+  std::ostream&, cmGeneratorTarget*, ImportPropertyMap const&,
+  const std::set<std::string>&)
+{
+}
+
+bool cmExportInstallAndroidMKGenerator::GenerateImportFileConfig(
+  const std::string&, std::vector<std::string>&)
+{
+  return true;
+}
diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h
new file mode 100644
index 0000000..c713027
--- /dev/null
+++ b/Source/cmExportInstallAndroidMKGenerator.h
@@ -0,0 +1,64 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmExportInstallAndroidMKGenerator_h
+#define cmExportInstallAndroidMKGenerator_h
+
+#include "cmExportInstallFileGenerator.h"
+
+class cmInstallExportGenerator;
+class cmInstallTargetGenerator;
+
+/** \class cmExportInstallAndroidMKGenerator
+ * \brief Generate a file exporting targets from an install tree.
+ *
+ * cmExportInstallAndroidMKGenerator generates files exporting targets from
+ * install an installation tree.  The files are placed in a temporary
+ * location for installation by cmInstallExportGenerator.  The file format
+ * is for the ndk build system and is a makefile fragment specifing prebuilt
+ * libraries to the ndk build system.
+ *
+ * This is used to implement the INSTALL(EXPORT_ANDROID_MK) command.
+ */
+class cmExportInstallAndroidMKGenerator : public cmExportInstallFileGenerator
+{
+public:
+  /** Construct with the export installer that will install the
+      files.  */
+  cmExportInstallAndroidMKGenerator(cmInstallExportGenerator* iegen);
+
+protected:
+  // Implement virtual methods from the superclass.
+  void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {}
+  void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {}
+  void GenerateImportHeaderCode(std::ostream& os,
+                                const std::string& config = "") CM_OVERRIDE;
+  void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE;
+  void GenerateImportTargetCode(std::ostream& os,
+                                const cmGeneratorTarget* target) CM_OVERRIDE;
+  void GenerateExpectedTargetsCode(
+    std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE;
+  void GenerateImportPropertyCode(std::ostream& os, const std::string& config,
+                                  cmGeneratorTarget const* target,
+                                  ImportPropertyMap const& properties)
+    CM_OVERRIDE;
+  void GenerateMissingTargetsCheckCode(
+    std::ostream& os,
+    const std::vector<std::string>& missingTargets) CM_OVERRIDE;
+  void GenerateInterfaceProperties(
+    cmGeneratorTarget const* target, std::ostream& os,
+    const ImportPropertyMap& properties) CM_OVERRIDE;
+  void GenerateImportPrefix(std::ostream& os) CM_OVERRIDE;
+  void LoadConfigFiles(std::ostream&) CM_OVERRIDE;
+  void GenerateRequiredCMakeVersion(std::ostream& os,
+                                    const char* versionString) CM_OVERRIDE;
+  void CleanupTemporaryVariables(std::ostream&) CM_OVERRIDE;
+  void GenerateImportedFileCheckLoop(std::ostream& os) CM_OVERRIDE;
+  void GenerateImportedFileChecksCode(
+    std::ostream& os, cmGeneratorTarget* target,
+    ImportPropertyMap const& properties,
+    const std::set<std::string>& importedLocations) CM_OVERRIDE;
+  bool GenerateImportFileConfig(const std::string& config,
+                                std::vector<std::string>&) CM_OVERRIDE;
+};
+
+#endif
diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx
index 38b08f0..0e043de 100644
--- a/Source/cmExportInstallFileGenerator.cxx
+++ b/Source/cmExportInstallFileGenerator.cxx
@@ -1,26 +1,27 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportInstallFileGenerator.h"
 
 #include "cmAlgorithms.h"
 #include "cmExportSet.h"
 #include "cmExportSetMap.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmInstallExportGenerator.h"
 #include "cmInstallTargetGenerator.h"
 #include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTargetExport.h"
 
+#include <sstream>
+#include <utility>
+
 cmExportInstallFileGenerator::cmExportInstallFileGenerator(
   cmInstallExportGenerator* iegen)
   : IEGen(iegen)
@@ -65,55 +66,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
     this->GenerateExpectedTargetsCode(os, expectedTargets);
   }
 
-  // Set an _IMPORT_PREFIX variable for import location properties
-  // to reference if they are relative to the install prefix.
-  std::string installPrefix =
-    this->IEGen->GetLocalGenerator()->GetMakefile()->GetSafeDefinition(
-      "CMAKE_INSTALL_PREFIX");
-  std::string const& expDest = this->IEGen->GetDestination();
-  if (cmSystemTools::FileIsFullPath(expDest)) {
-    // The export file is being installed to an absolute path so the
-    // package is not relocatable.  Use the configured install prefix.
-    /* clang-format off */
-    os <<
-      "# The installation prefix configured by this project.\n"
-      "set(_IMPORT_PREFIX \"" << installPrefix << "\")\n"
-      "\n";
-    /* clang-format on */
-  } else {
-    // Add code to compute the installation prefix relative to the
-    // import file location.
-    std::string absDest = installPrefix + "/" + expDest;
-    std::string absDestS = absDest + "/";
-    os << "# Compute the installation prefix relative to this file.\n"
-       << "get_filename_component(_IMPORT_PREFIX"
-       << " \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n";
-    if (cmHasLiteralPrefix(absDestS.c_str(), "/lib/") ||
-        cmHasLiteralPrefix(absDestS.c_str(), "/lib64/") ||
-        cmHasLiteralPrefix(absDestS.c_str(), "/usr/lib/") ||
-        cmHasLiteralPrefix(absDestS.c_str(), "/usr/lib64/")) {
-      // Handle "/usr move" symlinks created by some Linux distros.
-      /* clang-format off */
-      os <<
-        "# Use original install prefix when loaded through a\n"
-        "# cross-prefix symbolic link such as /lib -> /usr/lib.\n"
-        "get_filename_component(_realCurr \"${_IMPORT_PREFIX}\" REALPATH)\n"
-        "get_filename_component(_realOrig \"" << absDest << "\" REALPATH)\n"
-        "if(_realCurr STREQUAL _realOrig)\n"
-        "  set(_IMPORT_PREFIX \"" << absDest << "\")\n"
-        "endif()\n"
-        "unset(_realOrig)\n"
-        "unset(_realCurr)\n";
-      /* clang-format on */
-    }
-    std::string dest = expDest;
-    while (!dest.empty()) {
-      os << "get_filename_component(_IMPORT_PREFIX \"${_IMPORT_PREFIX}\" "
-            "PATH)\n";
-      dest = cmSystemTools::GetFilenamePath(dest);
-    }
-    os << "\n";
-  }
+  // Compute the relative import prefix for the file
+  this->GenerateImportPrefix(os);
 
   std::vector<std::string> missingTargets;
 
@@ -191,24 +145,9 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
     this->GenerateRequiredCMakeVersion(os, "2.8.12");
   }
 
-  // Now load per-configuration properties for them.
-  /* clang-format off */
-  os << "# Load information for each installed configuration.\n"
-     << "get_filename_component(_DIR \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n"
-     << "file(GLOB CONFIG_FILES \"${_DIR}/"
-     << this->GetConfigImportFileGlob() << "\")\n"
-     << "foreach(f ${CONFIG_FILES})\n"
-     << "  include(${f})\n"
-     << "endforeach()\n"
-     << "\n";
-  /* clang-format on */
+  this->LoadConfigFiles(os);
 
-  // Cleanup the import prefix variable.
-  /* clang-format off */
-  os << "# Cleanup temporary variables.\n"
-     << "set(_IMPORT_PREFIX)\n"
-     << "\n";
-  /* clang-format on */
+  this->CleanupTemporaryVariables(os);
   this->GenerateImportedFileCheckLoop(os);
 
   bool result = true;
@@ -229,6 +168,86 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
   return result;
 }
 
+void cmExportInstallFileGenerator::GenerateImportPrefix(std::ostream& os)
+{
+  // Set an _IMPORT_PREFIX variable for import location properties
+  // to reference if they are relative to the install prefix.
+  std::string installPrefix =
+    this->IEGen->GetLocalGenerator()->GetMakefile()->GetSafeDefinition(
+      "CMAKE_INSTALL_PREFIX");
+  std::string const& expDest = this->IEGen->GetDestination();
+  if (cmSystemTools::FileIsFullPath(expDest)) {
+    // The export file is being installed to an absolute path so the
+    // package is not relocatable.  Use the configured install prefix.
+    /* clang-format off */
+    os <<
+      "# The installation prefix configured by this project.\n"
+      "set(_IMPORT_PREFIX \"" << installPrefix << "\")\n"
+      "\n";
+    /* clang-format on */
+  } else {
+    // Add code to compute the installation prefix relative to the
+    // import file location.
+    std::string absDest = installPrefix + "/" + expDest;
+    std::string absDestS = absDest + "/";
+    os << "# Compute the installation prefix relative to this file.\n"
+       << "get_filename_component(_IMPORT_PREFIX"
+       << " \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n";
+    if (cmHasLiteralPrefix(absDestS.c_str(), "/lib/") ||
+        cmHasLiteralPrefix(absDestS.c_str(), "/lib64/") ||
+        cmHasLiteralPrefix(absDestS.c_str(), "/usr/lib/") ||
+        cmHasLiteralPrefix(absDestS.c_str(), "/usr/lib64/")) {
+      // Handle "/usr move" symlinks created by some Linux distros.
+      /* clang-format off */
+      os <<
+        "# Use original install prefix when loaded through a\n"
+        "# cross-prefix symbolic link such as /lib -> /usr/lib.\n"
+        "get_filename_component(_realCurr \"${_IMPORT_PREFIX}\" REALPATH)\n"
+        "get_filename_component(_realOrig \"" << absDest << "\" REALPATH)\n"
+        "if(_realCurr STREQUAL _realOrig)\n"
+        "  set(_IMPORT_PREFIX \"" << absDest << "\")\n"
+        "endif()\n"
+        "unset(_realOrig)\n"
+        "unset(_realCurr)\n";
+      /* clang-format on */
+    }
+    std::string dest = expDest;
+    while (!dest.empty()) {
+      os << "get_filename_component(_IMPORT_PREFIX \"${_IMPORT_PREFIX}\" "
+            "PATH)\n";
+      dest = cmSystemTools::GetFilenamePath(dest);
+    }
+    os << "if(_IMPORT_PREFIX STREQUAL \"/\")\n"
+       << "  set(_IMPORT_PREFIX \"\")\n"
+       << "endif()\n"
+       << "\n";
+  }
+}
+
+void cmExportInstallFileGenerator::CleanupTemporaryVariables(std::ostream& os)
+{
+  /* clang-format off */
+  os << "# Cleanup temporary variables.\n"
+     << "set(_IMPORT_PREFIX)\n"
+     << "\n";
+  /* clang-format on */
+}
+
+void cmExportInstallFileGenerator::LoadConfigFiles(std::ostream& os)
+{
+  // Now load per-configuration properties for them.
+  /* clang-format off */
+  os << "# Load information for each installed configuration.\n"
+     << "get_filename_component(_DIR \"${CMAKE_CURRENT_LIST_FILE}\" PATH)\n"
+     << "file(GLOB CONFIG_FILES \"${_DIR}/"
+     << this->GetConfigImportFileGlob() << "\")\n"
+     << "foreach(f ${CONFIG_FILES})\n"
+     << "  include(${f})\n"
+     << "endforeach()\n"
+     << "\n";
+  /* clang-format on */
+}
+
 void cmExportInstallFileGenerator::ReplaceInstallPrefix(std::string& input)
 {
   std::string::size_type pos = 0;
@@ -468,7 +487,7 @@ void cmExportInstallFileGenerator::ComplainAboutMissingTarget(
 }
 
 std::string cmExportInstallFileGenerator::InstallNameDir(
-  cmGeneratorTarget* target, const std::string&)
+  cmGeneratorTarget* target, const std::string& /*config*/)
 {
   std::string install_name_dir;
 
diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h
index 723b6e5..3c9777a 100644
--- a/Source/cmExportInstallFileGenerator.h
+++ b/Source/cmExportInstallFileGenerator.h
@@ -1,19 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportInstallFileGenerator_h
 #define cmExportInstallFileGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExportFileGenerator.h"
 
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmGeneratorTarget;
+class cmGlobalGenerator;
 class cmInstallExportGenerator;
 class cmInstallTargetGenerator;
 
@@ -52,16 +53,16 @@ public:
 
 protected:
   // Implement virtual methods from the superclass.
-  virtual bool GenerateMainFile(std::ostream& os);
-  virtual void GenerateImportTargetsConfig(
+  bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
+  void GenerateImportTargetsConfig(
     std::ostream& os, const std::string& config, std::string const& suffix,
-    std::vector<std::string>& missingTargets);
-  virtual void HandleMissingTarget(std::string& link_libs,
-                                   std::vector<std::string>& missingTargets,
-                                   cmGeneratorTarget* depender,
-                                   cmGeneratorTarget* dependee);
+    std::vector<std::string>& missingTargets) CM_OVERRIDE;
+  void HandleMissingTarget(std::string& link_libs,
+                           std::vector<std::string>& missingTargets,
+                           cmGeneratorTarget* depender,
+                           cmGeneratorTarget* dependee) CM_OVERRIDE;
 
-  virtual void ReplaceInstallPrefix(std::string& input);
+  void ReplaceInstallPrefix(std::string& input) CM_OVERRIDE;
 
   void ComplainAboutMissingTarget(cmGeneratorTarget* depender,
                                   cmGeneratorTarget* dependee,
@@ -70,9 +71,17 @@ protected:
   std::vector<std::string> FindNamespaces(cmGlobalGenerator* gg,
                                           const std::string& name);
 
+  /** Generate the relative import prefix.  */
+  virtual void GenerateImportPrefix(std::ostream&);
+
+  /** Generate the relative import prefix.  */
+  virtual void LoadConfigFiles(std::ostream&);
+
+  virtual void CleanupTemporaryVariables(std::ostream&);
+
   /** Generate a per-configuration file for the targets.  */
-  bool GenerateImportFileConfig(const std::string& config,
-                                std::vector<std::string>& missingTargets);
+  virtual bool GenerateImportFileConfig(
+    const std::string& config, std::vector<std::string>& missingTargets);
 
   /** Fill in properties indicating installed file locations.  */
   void SetImportLocationProperty(const std::string& config,
@@ -82,7 +91,7 @@ protected:
                                  std::set<std::string>& importedLocations);
 
   std::string InstallNameDir(cmGeneratorTarget* target,
-                             const std::string& config);
+                             const std::string& config) CM_OVERRIDE;
 
   cmInstallExportGenerator* IEGen;
 
diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx
index ab43aa8..f80980a 100644
--- a/Source/cmExportLibraryDependenciesCommand.cxx
+++ b/Source/cmExportLibraryDependenciesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportLibraryDependenciesCommand.h"
 
 #include "cmGeneratedFileStream.h"
@@ -16,7 +7,7 @@
 #include "cmVersion.h"
 #include "cmake.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
 
 bool cmExportLibraryDependenciesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -27,7 +18,7 @@ bool cmExportLibraryDependenciesCommand::InitialPass(
         "see CMP0033.")) {
     return true;
   }
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -53,18 +44,18 @@ void cmExportLibraryDependenciesCommand::FinalPass()
 void cmExportLibraryDependenciesCommand::ConstFinalPass() const
 {
   // Use copy-if-different if not appending.
-  cmsys::auto_ptr<cmsys::ofstream> foutPtr;
+  CM_AUTO_PTR<cmsys::ofstream> foutPtr;
   if (this->Append) {
-    cmsys::auto_ptr<cmsys::ofstream> ap(
+    CM_AUTO_PTR<cmsys::ofstream> ap(
       new cmsys::ofstream(this->Filename.c_str(), std::ios::app));
     foutPtr = ap;
   } else {
-    cmsys::auto_ptr<cmGeneratedFileStream> ap(
+    CM_AUTO_PTR<cmGeneratedFileStream> ap(
       new cmGeneratedFileStream(this->Filename.c_str(), true));
     ap->SetCopyIfDifferent(true);
     foutPtr = ap;
   }
-  std::ostream& fout = *foutPtr.get();
+  std::ostream& fout = *foutPtr;
 
   if (!fout) {
     cmSystemTools::Error("Error Writing ", this->Filename.c_str());
@@ -152,7 +143,7 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
   // versions.
   const char* vertest =
     "\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" GREATER 2.4";
-  fout << "# Generated by CMake " << cmVersion::GetCMakeVersion() << "\n\n";
+  fout << "# Generated by CMake\n\n";
   fout << "if(" << vertest << ")\n";
   fout << "  # Information for CMake 2.6 and above.\n";
   for (std::map<std::string, std::string>::const_iterator i =
diff --git a/Source/cmExportLibraryDependenciesCommand.h b/Source/cmExportLibraryDependenciesCommand.h
index 3fb3565..fa9f353 100644
--- a/Source/cmExportLibraryDependenciesCommand.h
+++ b/Source/cmExportLibraryDependenciesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportLibraryDependenciesCommand_h
 #define cmExportLibraryDependenciesCommand_h
 
@@ -18,13 +9,19 @@ class cmExportLibraryDependenciesCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmExportLibraryDependenciesCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmExportLibraryDependenciesCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "export_library_dependencies"; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmExportLibraryDependenciesCommand;
+  }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "export_library_dependencies";
+  }
 
-  virtual void FinalPass();
-  virtual bool HasFinalPass() const { return true; }
+  void FinalPass() CM_OVERRIDE;
+  bool HasFinalPass() const CM_OVERRIDE { return true; }
 
 private:
   std::string Filename;
diff --git a/Source/cmExportSet.cxx b/Source/cmExportSet.cxx
index c468e3e..a936679 100644
--- a/Source/cmExportSet.cxx
+++ b/Source/cmExportSet.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportSet.h"
 
 #include "cmAlgorithms.h"
diff --git a/Source/cmExportSet.h b/Source/cmExportSet.h
index 49f2cac..420f472 100644
--- a/Source/cmExportSet.h
+++ b/Source/cmExportSet.h
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportSet_h
 #define cmExportSet_h
 
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
-class cmTargetExport;
 class cmInstallExportGenerator;
 class cmLocalGenerator;
+class cmTargetExport;
 
 /// A set of targets that were installed with the same EXPORT parameter.
 class cmExportSet
diff --git a/Source/cmExportSetMap.cxx b/Source/cmExportSetMap.cxx
index ac1c66e..0740828 100644
--- a/Source/cmExportSetMap.cxx
+++ b/Source/cmExportSetMap.cxx
@@ -1,20 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportSetMap.h"
 
 #include "cmAlgorithms.h"
 #include "cmExportSet.h"
 
+#include <utility>
+
 cmExportSet* cmExportSetMap::operator[](const std::string& name)
 {
   std::map<std::string, cmExportSet*>::iterator it = this->find(name);
diff --git a/Source/cmExportSetMap.h b/Source/cmExportSetMap.h
index d2954e3..5090692 100644
--- a/Source/cmExportSetMap.h
+++ b/Source/cmExportSetMap.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportSetMap_h
 #define cmExportSetMap_h
 
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
 
 class cmExportSet;
 
diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx
index 5a826f2..9fc71f6 100644
--- a/Source/cmExportTryCompileFileGenerator.cxx
+++ b/Source/cmExportTryCompileFileGenerator.cxx
@@ -1,21 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportTryCompileFileGenerator.h"
 
-#include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
 #include "cmGeneratorExpressionDAGChecker.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
+
+#include <map>
+#include <utility>
 
 cmExportTryCompileFileGenerator::cmExportTryCompileFileGenerator(
   cmGlobalGenerator* gg, const std::vector<std::string>& targets,
@@ -63,13 +62,13 @@ std::string cmExportTryCompileFileGenerator::FindTargets(
 
   cmGeneratorExpression ge;
 
-  cmGeneratorExpressionDAGChecker dagChecker(tgt->GetName(), propName, 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(tgt->GetName(), propName,
+                                             CM_NULLPTR, CM_NULLPTR);
 
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
 
-  cmTarget dummyHead;
-  dummyHead.SetType(cmState::EXECUTABLE, "try_compile_dummy_exe");
-  dummyHead.SetMakefile(tgt->Target->GetMakefile());
+  cmTarget dummyHead("try_compile_dummy_exe", cmState::EXECUTABLE,
+                     cmTarget::VisibilityNormal, tgt->Target->GetMakefile());
 
   cmGeneratorTarget gDummyHead(&dummyHead, tgt->GetLocalGenerator());
 
diff --git a/Source/cmExportTryCompileFileGenerator.h b/Source/cmExportTryCompileFileGenerator.h
index 26f4db1..88a70a1 100644
--- a/Source/cmExportTryCompileFileGenerator.h
+++ b/Source/cmExportTryCompileFileGenerator.h
@@ -1,21 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExportTryCompileFileGenerator_h
 #define cmExportTryCompileFileGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExportFileGenerator.h"
 
-class cmInstallExportGenerator;
-class cmInstallTargetGenerator;
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
 
 class cmExportTryCompileFileGenerator : public cmExportFileGenerator
 {
@@ -28,15 +27,15 @@ public:
   void SetConfig(const std::string& config) { this->Config = config; }
 protected:
   // Implement virtual methods from the superclass.
-  virtual bool GenerateMainFile(std::ostream& os);
+  bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
 
-  virtual void GenerateImportTargetsConfig(std::ostream&, const std::string&,
-                                           std::string const&,
-                                           std::vector<std::string>&)
+  void GenerateImportTargetsConfig(std::ostream&, const std::string&,
+                                   std::string const&,
+                                   std::vector<std::string>&) CM_OVERRIDE
   {
   }
-  virtual void HandleMissingTarget(std::string&, std::vector<std::string>&,
-                                   cmGeneratorTarget*, cmGeneratorTarget*)
+  void HandleMissingTarget(std::string&, std::vector<std::string>&,
+                           cmGeneratorTarget*, cmGeneratorTarget*) CM_OVERRIDE
   {
   }
 
@@ -45,7 +44,7 @@ protected:
                           std::set<const cmGeneratorTarget*>& emitted);
 
   std::string InstallNameDir(cmGeneratorTarget* target,
-                             const std::string& config);
+                             const std::string& config) CM_OVERRIDE;
 
 private:
   std::string FindTargets(const std::string& prop,
diff --git a/Source/cmExprLexer.cxx b/Source/cmExprLexer.cxx
index 4704f03..0ecab22 100644
--- a/Source/cmExprLexer.cxx
+++ b/Source/cmExprLexer.cxx
@@ -1,3 +1,5 @@
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 #line 2 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
 
@@ -437,17 +439,8 @@ static yyconst flex_int16_t yy_chk[37] =
 #define YY_RESTORE_YY_MORE_OFFSET
 #line 1 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
 #line 2 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmExprLexer.h b/Source/cmExprLexer.h
index 03b36ce..efe6440 100644
--- a/Source/cmExprLexer.h
+++ b/Source/cmExprLexer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExpr_yyHEADER_H
 #define cmExpr_yyHEADER_H 1
 #define cmExpr_yyIN_HEADER 1
diff --git a/Source/cmExprLexer.in.l b/Source/cmExprLexer.in.l
index febd244..e32abd9 100644
--- a/Source/cmExprLexer.in.l
+++ b/Source/cmExprLexer.in.l
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmExprParser.cxx b/Source/cmExprParser.cxx
index c12b42e..077106f 100644
--- a/Source/cmExprParser.cxx
+++ b/Source/cmExprParser.cxx
@@ -104,17 +104,8 @@
 /* Copy the first part of user declarations.  */
 
 
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmExprParser.y b/Source/cmExprParser.y
index f2c85d0..a265c20 100644
--- a/Source/cmExprParser.y
+++ b/Source/cmExprParser.y
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmExprParserHelper.cxx b/Source/cmExprParserHelper.cxx
index 2ba9b8d..1b49def 100644
--- a/Source/cmExprParserHelper.cxx
+++ b/Source/cmExprParserHelper.cxx
@@ -1,27 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExprParserHelper.h"
 
-#include "cmMakefile.h"
-#include "cmSystemTools.h"
+#include <cmConfigure.h>
 
 #include "cmExprLexer.h"
 
+#include <iostream>
+#include <sstream>
+
 int cmExpr_yyparse(yyscan_t yyscanner);
 //
 cmExprParserHelper::cmExprParserHelper()
 {
   this->FileLine = -1;
-  this->FileName = 0;
+  this->FileName = CM_NULLPTR;
 }
 
 cmExprParserHelper::~cmExprParserHelper()
@@ -81,10 +74,9 @@ int cmExprParserHelper::LexInput(char* buf, int maxlen)
       this->CurrentLine++;
     }
     return (1);
-  } else {
-    buf[0] = '\n';
-    return (0);
   }
+  buf[0] = '\n';
+  return (0);
 }
 
 void cmExprParserHelper::Error(const char* str)
diff --git a/Source/cmExprParserHelper.h b/Source/cmExprParserHelper.h
index af0b916..8f00f1d 100644
--- a/Source/cmExprParserHelper.h
+++ b/Source/cmExprParserHelper.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExprParserHelper_h
 #define cmExprParserHelper_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 #define YYSTYPE cmExprParserHelper::ParserType
 #define YYSTYPE_IS_DECLARED
@@ -24,9 +18,6 @@
  *
  * Finds dependencies for java file and list of outputs
  */
-
-class cmMakefile;
-
 class cmExprParserHelper
 {
 public:
diff --git a/Source/cmExternalMakefileProjectGenerator.cxx b/Source/cmExternalMakefileProjectGenerator.cxx
index 0e42d75..825ec65 100644
--- a/Source/cmExternalMakefileProjectGenerator.cxx
+++ b/Source/cmExternalMakefileProjectGenerator.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExternalMakefileProjectGenerator.h"
 
-#include <assert.h>
+class cmMakefile;
 
 void cmExternalMakefileProjectGenerator::EnableLanguage(
-  std::vector<std::string> const&, cmMakefile*, bool)
+  std::vector<std::string> const& /*unused*/, cmMakefile* /*unused*/,
+  bool /*unused*/)
 {
 }
 
@@ -33,28 +24,37 @@ std::string cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
   return fullName;
 }
 
-std::string cmExternalMakefileProjectGenerator::GetGlobalGeneratorName(
-  const std::string& fullName)
+cmExternalMakefileProjectGeneratorFactory::
+  cmExternalMakefileProjectGeneratorFactory(const std::string& n,
+                                            const std::string& doc)
+  : Name(n)
+  , Documentation(doc)
 {
-  // at least one global generator must be supported
-  assert(!this->SupportedGlobalGenerators.empty());
+}
 
-  if (fullName.empty()) {
-    return "";
-  }
+cmExternalMakefileProjectGeneratorFactory::
+  ~cmExternalMakefileProjectGeneratorFactory()
+{
+}
 
-  // if we get only the short name, take the first global generator as default
-  if (fullName == this->GetName()) {
-    return this->SupportedGlobalGenerators[0];
-  }
+std::string cmExternalMakefileProjectGeneratorFactory::GetName() const
+{
+  return this->Name;
+}
 
-  // otherwise search for the matching global generator
-  for (std::vector<std::string>::const_iterator it =
-         this->SupportedGlobalGenerators.begin();
-       it != this->SupportedGlobalGenerators.end(); ++it) {
-    if (this->CreateFullGeneratorName(*it, this->GetName()) == fullName) {
-      return *it;
-    }
-  }
-  return "";
+std::string cmExternalMakefileProjectGeneratorFactory::GetDocumentation() const
+{
+  return this->Documentation;
+}
+
+std::vector<std::string>
+cmExternalMakefileProjectGeneratorFactory::GetSupportedGlobalGenerators() const
+{
+  return this->SupportedGlobalGenerators;
+}
+
+void cmExternalMakefileProjectGeneratorFactory::AddSupportedGlobalGenerator(
+  const std::string& base)
+{
+  this->SupportedGlobalGenerators.push_back(base);
 }
diff --git a/Source/cmExternalMakefileProjectGenerator.h b/Source/cmExternalMakefileProjectGenerator.h
index 5d4d54d..c49d39b 100644
--- a/Source/cmExternalMakefileProjectGenerator.h
+++ b/Source/cmExternalMakefileProjectGenerator.h
@@ -1,22 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExternalMakefileProjectGenerator_h
 #define cmExternalMakefileProjectGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmDocumentation.h"
+#include <string>
+#include <vector>
 
 class cmGlobalGenerator;
+class cmMakefile;
 
 /** \class cmExternalMakefileProjectGenerator
  * \brief Base class for generators for "External Makefile based IDE projects".
@@ -35,11 +28,6 @@ class cmExternalMakefileProjectGenerator
 public:
   virtual ~cmExternalMakefileProjectGenerator() {}
 
-  ///! Get the name for this generator.
-  virtual std::string GetName() const = 0;
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const = 0;
   virtual void EnableLanguage(std::vector<std::string> const& languages,
                               cmMakefile*, bool optional);
 
@@ -55,8 +43,6 @@ public:
     return this->SupportedGlobalGenerators;
   }
 
-  ///! Get the name of the global generator for the given full name
-  std::string GetGlobalGeneratorName(const std::string& fullName);
   /** Create a full name from the given global generator name and the
    * extra generator name
    */
@@ -66,11 +52,59 @@ public:
   ///! Generate the project files, the Makefiles have already been generated
   virtual void Generate() = 0;
 
+  void SetName(const std::string& n) { Name = n; }
+  std::string GetName() const { return Name; }
+
 protected:
   ///! Contains the names of the global generators support by this generator.
   std::vector<std::string> SupportedGlobalGenerators;
   ///! the global generator which creates the makefiles
   const cmGlobalGenerator* GlobalGenerator;
+
+  std::string Name;
+};
+
+class cmExternalMakefileProjectGeneratorFactory
+{
+public:
+  cmExternalMakefileProjectGeneratorFactory(const std::string& n,
+                                            const std::string& doc);
+  virtual ~cmExternalMakefileProjectGeneratorFactory();
+
+  std::string GetName() const;
+  std::string GetDocumentation() const;
+  std::vector<std::string> GetSupportedGlobalGenerators() const;
+  std::vector<std::string> Aliases;
+
+  virtual cmExternalMakefileProjectGenerator*
+  CreateExternalMakefileProjectGenerator() const = 0;
+
+  void AddSupportedGlobalGenerator(const std::string& base);
+
+private:
+  std::string Name;
+  std::string Documentation;
+  std::vector<std::string> SupportedGlobalGenerators;
+};
+
+template <class T>
+class cmExternalMakefileProjectGeneratorSimpleFactory
+  : public cmExternalMakefileProjectGeneratorFactory
+{
+public:
+  cmExternalMakefileProjectGeneratorSimpleFactory(const std::string& n,
+                                                  const std::string& doc)
+    : cmExternalMakefileProjectGeneratorFactory(n, doc)
+  {
+  }
+
+  cmExternalMakefileProjectGenerator* CreateExternalMakefileProjectGenerator()
+    const CM_OVERRIDE
+  {
+    T* p = new T;
+    p->SetName(GetName());
+    return p;
+  }
 };
 
 #endif
diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx
index 589bf53..18c732d 100644
--- a/Source/cmExtraCodeBlocksGenerator.cxx
+++ b/Source/cmExtraCodeBlocksGenerator.cxx
@@ -1,27 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraCodeBlocksGenerator.h"
 
+#include "cmAlgorithms.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
-#include <cmsys/SystemTools.hxx>
+#include <algorithm>
+#include <map>
+#include <ostream>
+#include <string.h>
+#include <utility>
 
 /* Some useful URLs:
 Homepage:
@@ -36,24 +33,30 @@ Discussion:
 http://forums.codeblocks.org/index.php/topic,6789.0.html
 */
 
-void cmExtraCodeBlocksGenerator::GetDocumentation(cmDocumentationEntry& entry,
-                                                  const std::string&) const
+cmExtraCodeBlocksGenerator::cmExtraCodeBlocksGenerator()
+  : cmExternalMakefileProjectGenerator()
 {
-  entry.Name = this->GetName();
-  entry.Brief = "Generates CodeBlocks project files.";
 }
 
-cmExtraCodeBlocksGenerator::cmExtraCodeBlocksGenerator()
-  : cmExternalMakefileProjectGenerator()
+cmExternalMakefileProjectGeneratorFactory*
+cmExtraCodeBlocksGenerator::GetFactory()
 {
+  static cmExternalMakefileProjectGeneratorSimpleFactory<
+    cmExtraCodeBlocksGenerator>
+    factory("CodeBlocks", "Generates CodeBlocks project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
 #if defined(_WIN32)
-  this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
-  this->SupportedGlobalGenerators.push_back("NMake Makefiles");
+    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
+    factory.AddSupportedGlobalGenerator("NMake Makefiles");
 // disable until somebody actually tests it:
-//  this->SupportedGlobalGenerators.push_back("MSYS Makefiles");
+// this->AddSupportedGlobalGenerator("MSYS Makefiles");
 #endif
-  this->SupportedGlobalGenerators.push_back("Ninja");
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
+    factory.AddSupportedGlobalGenerator("Ninja");
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
+  }
+
+  return &factory;
 }
 
 void cmExtraCodeBlocksGenerator::Generate()
@@ -118,11 +121,10 @@ void Tree::InsertPath(const std::vector<std::string>& splitted,
       if (start + 1 < splitted.size()) {
         it->InsertPath(splitted, start + 1, fileName);
         return;
-      } else {
-        // last part of splitted
-        it->files.push_back(fileName);
-        return;
       }
+      // last part of splitted
+      it->files.push_back(fileName);
+      return;
     }
   }
   // Not found in folders, thus insert
@@ -132,12 +134,11 @@ void Tree::InsertPath(const std::vector<std::string>& splitted,
     newFolder.InsertPath(splitted, start + 1, fileName);
     folders.push_back(newFolder);
     return;
-  } else {
-    // last part of splitted
-    newFolder.files.push_back(fileName);
-    folders.push_back(newFolder);
-    return;
   }
+  // last part of splitted
+  newFolder.files.push_back(fileName);
+  folders.push_back(newFolder);
+  return;
 }
 
 void Tree::BuildVirtualFolder(cmXMLWriter& xml) const
@@ -248,7 +249,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
       // We don't want paths with CMakeFiles in them
       // or do we?
       // In speedcrunch those where purely internal
-      if (splitted.size() >= 1 &&
+      if (!splitted.empty() &&
           relative.find("CMakeFiles") == std::string::npos) {
         tree.InsertPath(splitted, 1, fileName);
       }
@@ -289,8 +290,8 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
 
   xml.StartElement("Build");
 
-  this->AppendTarget(xml, "all", 0, make.c_str(), lgs[0], compiler.c_str(),
-                     makeArgs);
+  this->AppendTarget(xml, "all", CM_NULLPTR, make.c_str(), lgs[0],
+                     compiler.c_str(), makeArgs);
 
   // add all executable and library targets and some of the GLOBAL
   // and UTILITY targets
@@ -306,7 +307,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
           // not from the subdirs
           if (strcmp((*lg)->GetCurrentBinaryDirectory(),
                      (*lg)->GetBinaryDirectory()) == 0) {
-            this->AppendTarget(xml, targetName, 0, make.c_str(), *lg,
+            this->AppendTarget(xml, targetName, CM_NULLPTR, make.c_str(), *lg,
                                compiler.c_str(), makeArgs);
           }
         } break;
@@ -322,7 +323,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
             break;
           }
 
-          this->AppendTarget(xml, targetName, 0, make.c_str(), *lg,
+          this->AppendTarget(xml, targetName, CM_NULLPTR, make.c_str(), *lg,
                              compiler.c_str(), makeArgs);
           break;
         case cmState::EXECUTABLE:
@@ -376,8 +377,10 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
                              makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
           for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
                si != sources.end(); si++) {
-            // don't add source files which have the GENERATED property set:
-            if ((*si)->GetPropertyAsBool("GENERATED")) {
+            // don't add source files from UTILITY target which have the
+            // GENERATED property set:
+            if (gt->GetType() == cmState::UTILITY &&
+                (*si)->GetPropertyAsBool("GENERATED")) {
               continue;
             }
 
@@ -513,7 +516,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
   xml.StartElement("Target");
   xml.Attribute("title", targetName);
 
-  if (target != 0) {
+  if (target != CM_NULLPTR) {
     int cbTargetType = this->GetCBTargetType(target);
     std::string workingDir = lg->GetCurrentBinaryDirectory();
     if (target->GetType() == cmState::EXECUTABLE) {
@@ -521,12 +524,12 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
       // set the working directory to this dir.
       const char* runtimeOutputDir =
         makefile->GetDefinition("CMAKE_RUNTIME_OUTPUT_DIRECTORY");
-      if (runtimeOutputDir != 0) {
+      if (runtimeOutputDir != CM_NULLPTR) {
         workingDir = runtimeOutputDir;
       } else {
         const char* executableOutputDir =
           makefile->GetDefinition("EXECUTABLE_OUTPUT_PATH");
-        if (executableOutputDir != 0) {
+        if (executableOutputDir != CM_NULLPTR) {
           workingDir = executableOutputDir;
         }
       }
@@ -587,7 +590,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
                           includes.end());
 
     std::string systemIncludeDirs = makefile->GetSafeDefinition(
-      "CMAKE_EXTRA_GENERATOR_C_SYSTEM_INCLUDE_DIRS");
+      "CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_INCLUDE_DIRS");
     if (!systemIncludeDirs.empty()) {
       std::vector<std::string> dirs;
       cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs);
@@ -595,7 +598,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
     }
 
     systemIncludeDirs = makefile->GetSafeDefinition(
-      "CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_INCLUDE_DIRS");
+      "CMAKE_EXTRA_GENERATOR_C_SYSTEM_INCLUDE_DIRS");
     if (!systemIncludeDirs.empty()) {
       std::vector<std::string> dirs;
       cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs);
@@ -659,11 +662,11 @@ std::string cmExtraCodeBlocksGenerator::GetCBCompilerId(const cmMakefile* mf)
   // projects with C/C++ and Fortran are handled as C/C++ projects
   bool pureFortran = false;
   std::string compilerIdVar;
-  if (this->GlobalGenerator->GetLanguageEnabled("CXX") == true) {
+  if (this->GlobalGenerator->GetLanguageEnabled("CXX")) {
     compilerIdVar = "CMAKE_CXX_COMPILER_ID";
-  } else if (this->GlobalGenerator->GetLanguageEnabled("C") == true) {
+  } else if (this->GlobalGenerator->GetLanguageEnabled("C")) {
     compilerIdVar = "CMAKE_C_COMPILER_ID";
-  } else if (this->GlobalGenerator->GetLanguageEnabled("Fortran") == true) {
+  } else if (this->GlobalGenerator->GetLanguageEnabled("Fortran")) {
     compilerIdVar = "CMAKE_Fortran_COMPILER_ID";
     pureFortran = true;
   }
@@ -671,7 +674,7 @@ std::string cmExtraCodeBlocksGenerator::GetCBCompilerId(const cmMakefile* mf)
   std::string compilerId = mf->GetSafeDefinition(compilerIdVar);
   std::string compiler = "gcc"; // default to gcc
   if (compilerId == "MSVC") {
-    if (mf->IsDefinitionSet("MSVC10") == true) {
+    if (mf->IsDefinitionSet("MSVC10")) {
       compiler = "msvc10";
     } else {
       compiler = "msvc8";
@@ -709,21 +712,22 @@ std::string cmExtraCodeBlocksGenerator::GetCBCompilerId(const cmMakefile* mf)
 // Translate the cmake target type into the CodeBlocks target type id
 int cmExtraCodeBlocksGenerator::GetCBTargetType(cmGeneratorTarget* target)
 {
-  if (target->GetType() == cmState::EXECUTABLE) {
-    if ((target->GetPropertyAsBool("WIN32_EXECUTABLE")) ||
-        (target->GetPropertyAsBool("MACOSX_BUNDLE"))) {
-      return 0;
-    } else {
+  switch (target->GetType()) {
+    case cmState::EXECUTABLE:
+      if ((target->GetPropertyAsBool("WIN32_EXECUTABLE")) ||
+          (target->GetPropertyAsBool("MACOSX_BUNDLE"))) {
+        return 0;
+      }
       return 1;
-    }
-  } else if ((target->GetType() == cmState::STATIC_LIBRARY) ||
-             (target->GetType() == cmState::OBJECT_LIBRARY)) {
-    return 2;
-  } else if ((target->GetType() == cmState::SHARED_LIBRARY) ||
-             (target->GetType() == cmState::MODULE_LIBRARY)) {
-    return 3;
+    case cmState::STATIC_LIBRARY:
+    case cmState::OBJECT_LIBRARY:
+      return 2;
+    case cmState::SHARED_LIBRARY:
+    case cmState::MODULE_LIBRARY:
+      return 3;
+    default:
+      return 4;
   }
-  return 4;
 }
 
 // Create the command line for building the given target using the selected
@@ -733,7 +737,7 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand(
   const std::string& makeFlags)
 {
   std::string command = make;
-  if (makeFlags.size() > 0) {
+  if (!makeFlags.empty()) {
     command += " ";
     command += makeFlags;
   }
@@ -742,7 +746,7 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand(
   if (generator == "NMake Makefiles") {
     // For Windows ConvertToOutputPath already adds quotes when required.
     // These need to be escaped, see
-    // http://public.kitware.com/Bug/view.php?id=13952
+    // https://gitlab.kitware.com/cmake/cmake/issues/13952
     std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
     command += " /NOLOGO /f ";
     command += makefileName;
@@ -750,7 +754,7 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand(
     command += target;
   } else if (generator == "MinGW Makefiles") {
     // no escaping of spaces in this case, see
-    // http://public.kitware.com/Bug/view.php?id=10014
+    // https://gitlab.kitware.com/cmake/cmake/issues/10014
     std::string makefileName = makefile;
     command += " -f \"";
     command += makefileName;
diff --git a/Source/cmExtraCodeBlocksGenerator.h b/Source/cmExtraCodeBlocksGenerator.h
index fe4f513..06aadc4 100644
--- a/Source/cmExtraCodeBlocksGenerator.h
+++ b/Source/cmExtraCodeBlocksGenerator.h
@@ -1,23 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExtraCodeBlocksGenerator_h
 #define cmExtraCodeBlocksGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
 
+#include <string>
+#include <vector>
+
+class cmGeneratorTarget;
 class cmLocalGenerator;
 class cmMakefile;
-class cmGeneratorTarget;
 class cmXMLWriter;
 
 /** \class cmExtraCodeBlocksGenerator
@@ -28,20 +23,9 @@ class cmExtraCodeBlocksGenerator : public cmExternalMakefileProjectGenerator
 public:
   cmExtraCodeBlocksGenerator();
 
-  virtual std::string GetName() const
-  {
-    return cmExtraCodeBlocksGenerator::GetActualName();
-  }
-  static std::string GetActualName() { return "CodeBlocks"; }
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmExtraCodeBlocksGenerator;
-  }
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
 
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
 private:
   struct CbpUnit
diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx
index ba58767..360c852 100644
--- a/Source/cmExtraCodeLiteGenerator.cxx
+++ b/Source/cmExtraCodeLiteGenerator.cxx
@@ -1,50 +1,49 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-  Copyright 2013 Eran Ifrah (eran.ifrah at gmail.com)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraCodeLiteGenerator.h"
 
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmXMLWriter.h"
 #include "cmake.h"
 
-#include "cmStandardIncludes.h"
-#include "cmXMLWriter.h"
-#include <cmsys/Directory.hxx>
 #include <cmsys/SystemInformation.hxx>
-#include <cmsys/SystemTools.hxx>
-
-void cmExtraCodeLiteGenerator::GetDocumentation(cmDocumentationEntry& entry,
-                                                const std::string&) const
-{
-  entry.Name = this->GetName();
-  entry.Brief = "Generates CodeLite project files.";
-}
+#include <map>
+#include <set>
+#include <sstream>
+#include <string.h>
+#include <utility>
 
 cmExtraCodeLiteGenerator::cmExtraCodeLiteGenerator()
   : cmExternalMakefileProjectGenerator()
   , ConfigName("NoConfig")
   , CpuCount(2)
 {
+}
+
+cmExternalMakefileProjectGeneratorFactory*
+cmExtraCodeLiteGenerator::GetFactory()
+{
+  static cmExternalMakefileProjectGeneratorSimpleFactory<
+    cmExtraCodeLiteGenerator>
+    factory("CodeLite", "Generates CodeLite project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
 #if defined(_WIN32)
-  this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
-  this->SupportedGlobalGenerators.push_back("NMake Makefiles");
+    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
+    factory.AddSupportedGlobalGenerator("NMake Makefiles");
 #endif
-  this->SupportedGlobalGenerators.push_back("Ninja");
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
+    factory.AddSupportedGlobalGenerator("Ninja");
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
+  }
+
+  return &factory;
 }
 
 void cmExtraCodeLiteGenerator::Generate()
@@ -60,6 +59,7 @@ void cmExtraCodeLiteGenerator::Generate()
 
   // loop projects and locate the root project.
   // and extract the information for creating the worspace
+  // root makefile
   for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
          it = projectMap.begin();
        it != projectMap.end(); ++it) {
@@ -86,26 +86,14 @@ void cmExtraCodeLiteGenerator::Generate()
   xml.StartElement("CodeLite_Workspace");
   xml.Attribute("Name", workspaceProjectName);
 
-  // for each sub project in the workspace create a codelite project
-  for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
-         it = projectMap.begin();
-       it != projectMap.end(); ++it) {
-    // retrive project information
-    std::string outputDir = it->second[0]->GetCurrentBinaryDirectory();
-    std::string projectName = it->second[0]->GetProjectName();
-    std::string filename = outputDir + "/" + projectName + ".project";
-
-    // Make the project file relative to the workspace
-    filename = cmSystemTools::RelativePath(this->WorkspacePath.c_str(),
-                                           filename.c_str());
+  bool const targetsAreProjects =
+    this->GlobalGenerator->GlobalSettingIsOn("CMAKE_CODELITE_USE_TARGETS");
 
-    // create a project file
-    this->CreateProjectFile(it->second);
-    xml.StartElement("Project");
-    xml.Attribute("Name", projectName);
-    xml.Attribute("Path", filename);
-    xml.Attribute("Active", "No");
-    xml.EndElement();
+  std::vector<std::string> ProjectNames;
+  if (targetsAreProjects) {
+    ProjectNames = CreateProjectsByTarget(&xml);
+  } else {
+    ProjectNames = CreateProjectsByProjectMaps(&xml);
   }
 
   xml.StartElement("BuildMatrix");
@@ -113,14 +101,10 @@ void cmExtraCodeLiteGenerator::Generate()
   xml.Attribute("Name", this->ConfigName);
   xml.Attribute("Selected", "yes");
 
-  for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
-         it = projectMap.begin();
-       it != projectMap.end(); ++it) {
-    // retrive project information
-    std::string projectName = it->second[0]->GetProjectName();
-
+  for (std::vector<std::string>::iterator it(ProjectNames.begin());
+       it != ProjectNames.end(); it++) {
     xml.StartElement("Project");
-    xml.Attribute("Name", projectName);
+    xml.Attribute("Name", *it);
     xml.Attribute("ConfigName", this->ConfigName);
     xml.EndElement();
   }
@@ -130,6 +114,79 @@ void cmExtraCodeLiteGenerator::Generate()
   xml.EndElement(); // CodeLite_Workspace
 }
 
+// Create projects where targets are the projects
+std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget(
+  cmXMLWriter* xml)
+{
+  std::vector<std::string> retval;
+  // for each target in the workspace create a codelite project
+  const std::vector<cmLocalGenerator*>& lgs =
+    this->GlobalGenerator->GetLocalGenerators();
+  for (std::vector<cmLocalGenerator*>::const_iterator lg(lgs.begin());
+       lg != lgs.end(); lg++) {
+    for (std::vector<cmGeneratorTarget*>::const_iterator lt =
+           (*lg)->GetGeneratorTargets().begin();
+         lt != (*lg)->GetGeneratorTargets().end(); lt++) {
+      cmState::TargetType type = (*lt)->GetType();
+      std::string outputDir = (*lg)->GetCurrentBinaryDirectory();
+      std::string filename = outputDir + "/" + (*lt)->GetName() + ".project";
+      retval.push_back((*lt)->GetName());
+      // Make the project file relative to the workspace
+      std::string relafilename = cmSystemTools::RelativePath(
+        this->WorkspacePath.c_str(), filename.c_str());
+      std::string visualname = (*lt)->GetName();
+      switch (type) {
+        case cmState::SHARED_LIBRARY:
+        case cmState::STATIC_LIBRARY:
+        case cmState::MODULE_LIBRARY:
+          visualname = "lib" + visualname;
+        case cmState::EXECUTABLE:
+          xml->StartElement("Project");
+          xml->Attribute("Name", visualname);
+          xml->Attribute("Path", relafilename);
+          xml->Attribute("Active", "No");
+          xml->EndElement();
+
+          CreateNewProjectFile(*lt, filename);
+          break;
+        default:
+          break;
+      }
+    }
+  }
+  return retval;
+}
+
+// The "older way of doing it.
+std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps(
+  cmXMLWriter* xml)
+{
+  std::vector<std::string> retval;
+  // for each sub project in the workspace create a codelite project
+  for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
+         it = this->GlobalGenerator->GetProjectMap().begin();
+       it != this->GlobalGenerator->GetProjectMap().end(); it++) {
+
+    std::string outputDir = it->second[0]->GetCurrentBinaryDirectory();
+    std::string projectName = it->second[0]->GetProjectName();
+    retval.push_back(projectName);
+    std::string filename = outputDir + "/" + projectName + ".project";
+
+    // Make the project file relative to the workspace
+    filename = cmSystemTools::RelativePath(this->WorkspacePath.c_str(),
+                                           filename.c_str());
+
+    // create a project file
+    this->CreateProjectFile(it->second);
+    xml->StartElement("Project");
+    xml->Attribute("Name", projectName);
+    xml->Attribute("Path", filename);
+    xml->Attribute("Active", "No");
+    xml->EndElement();
+  }
+  return retval;
+}
+
 /* create the project file */
 void cmExtraCodeLiteGenerator::CreateProjectFile(
   const std::vector<cmLocalGenerator*>& lgs)
@@ -142,6 +199,70 @@ void cmExtraCodeLiteGenerator::CreateProjectFile(
   this->CreateNewProjectFile(lgs, filename);
 }
 
+std::string cmExtraCodeLiteGenerator::CollectSourceFiles(
+  const cmMakefile* makefile, const cmGeneratorTarget* gt,
+  std::map<std::string, cmSourceFile*>& cFiles,
+  std::set<std::string>& otherFiles)
+{
+  const std::vector<std::string>& srcExts =
+    this->GlobalGenerator->GetCMakeInstance()->GetSourceExtensions();
+
+  std::string projectType;
+  switch (gt->GetType()) {
+    case cmState::EXECUTABLE: {
+      projectType = "Executable";
+    } break;
+    case cmState::STATIC_LIBRARY: {
+      projectType = "Static Library";
+    } break;
+    case cmState::SHARED_LIBRARY: {
+      projectType = "Dynamic Library";
+    } break;
+    case cmState::MODULE_LIBRARY: {
+      projectType = "Dynamic Library";
+    } break;
+    default: // intended fallthrough
+      break;
+  }
+
+  switch (gt->GetType()) {
+    case cmState::EXECUTABLE:
+    case cmState::STATIC_LIBRARY:
+    case cmState::SHARED_LIBRARY:
+    case cmState::MODULE_LIBRARY: {
+      std::vector<cmSourceFile*> sources;
+      gt->GetSourceFiles(sources,
+                         makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
+      for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
+           si != sources.end(); si++) {
+        // check whether it is a C/C++ implementation file
+        bool isCFile = false;
+        std::string lang = (*si)->GetLanguage();
+        if (lang == "C" || lang == "CXX") {
+          std::string srcext = (*si)->GetExtension();
+          for (std::vector<std::string>::const_iterator ext = srcExts.begin();
+               ext != srcExts.end(); ++ext) {
+            if (srcext == *ext) {
+              isCFile = true;
+              break;
+            }
+          }
+        }
+
+        // then put it accordingly into one of the two containers
+        if (isCFile) {
+          cFiles[(*si)->GetFullPath()] = *si;
+        } else {
+          otherFiles.insert((*si)->GetFullPath());
+        }
+      }
+    }
+    default: // intended fallthrough
+      break;
+  }
+  return projectType;
+}
+
 void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   const std::vector<cmLocalGenerator*>& lgs, const std::string& filename)
 {
@@ -158,81 +279,41 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   xml.Attribute("Name", lgs[0]->GetProjectName());
   xml.Attribute("InternalType", "");
 
+  std::string projectType;
+
   // Collect all used source files in the project
   // Sort them into two containers, one for C/C++ implementation files
   // which may have an acompanying header, one for all other files
-  std::string projectType;
-
-  std::vector<std::string> srcExts =
-    this->GlobalGenerator->GetCMakeInstance()->GetSourceExtensions();
-  std::vector<std::string> headerExts =
-    this->GlobalGenerator->GetCMakeInstance()->GetHeaderExtensions();
-
   std::map<std::string, cmSourceFile*> cFiles;
   std::set<std::string> otherFiles;
+
   for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
        lg != lgs.end(); lg++) {
     cmMakefile* makefile = (*lg)->GetMakefile();
     std::vector<cmGeneratorTarget*> targets = (*lg)->GetGeneratorTargets();
     for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
          ti != targets.end(); ti++) {
+      projectType = CollectSourceFiles(makefile, *ti, cFiles, otherFiles);
+    }
+  }
 
-      switch ((*ti)->GetType()) {
-        case cmState::EXECUTABLE: {
-          projectType = "Executable";
-        } break;
-        case cmState::STATIC_LIBRARY: {
-          projectType = "Static Library";
-        } break;
-        case cmState::SHARED_LIBRARY: {
-          projectType = "Dynamic Library";
-        } break;
-        case cmState::MODULE_LIBRARY: {
-          projectType = "Dynamic Library";
-        } break;
-        default: // intended fallthrough
-          break;
-      }
+  // Get the project path ( we need it later to convert files to
+  // their relative path)
+  std::string projectPath = cmSystemTools::GetFilenamePath(filename);
 
-      switch ((*ti)->GetType()) {
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY: {
-          std::vector<cmSourceFile*> sources;
-          cmGeneratorTarget* gt = *ti;
-          gt->GetSourceFiles(sources,
-                             makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
-          for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
-               si != sources.end(); si++) {
-            // check whether it is a C/C++ implementation file
-            bool isCFile = false;
-            std::string lang = (*si)->GetLanguage();
-            if (lang == "C" || lang == "CXX") {
-              std::string srcext = (*si)->GetExtension();
-              for (std::vector<std::string>::const_iterator ext =
-                     srcExts.begin();
-                   ext != srcExts.end(); ++ext) {
-                if (srcext == *ext) {
-                  isCFile = true;
-                  break;
-                }
-              }
-            }
+  CreateProjectSourceEntries(cFiles, otherFiles, &xml, projectPath, mf,
+                             projectType);
 
-            // then put it accordingly into one of the two containers
-            if (isCFile) {
-              cFiles[(*si)->GetFullPath()] = *si;
-            } else {
-              otherFiles.insert((*si)->GetFullPath());
-            }
-          }
-        }
-        default: // intended fallthrough
-          break;
-      }
-    }
-  }
+  xml.EndElement(); // CodeLite_Project
+}
+
+void cmExtraCodeLiteGenerator::FindMatchingHeaderfiles(
+  std::map<std::string, cmSourceFile*>& cFiles,
+  std::set<std::string>& otherFiles)
+{
+
+  const std::vector<std::string>& headerExts =
+    this->GlobalGenerator->GetCMakeInstance()->GetHeaderExtensions();
 
   // The following loop tries to add header files matching to implementation
   // files to the project. It does that by iterating over all source files,
@@ -265,11 +346,17 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
       }
     }
   }
+}
 
-  // Get the project path ( we need it later to convert files to
-  // their relative path)
-  std::string projectPath = cmSystemTools::GetFilenamePath(filename);
+void cmExtraCodeLiteGenerator::CreateProjectSourceEntries(
+  std::map<std::string, cmSourceFile*>& cFiles,
+  std::set<std::string>& otherFiles, cmXMLWriter* _xml,
+  const std::string& projectPath, const cmMakefile* mf,
+  const std::string& projectType)
+{
 
+  cmXMLWriter& xml(*_xml);
+  FindMatchingHeaderfiles(cFiles, otherFiles);
   // Create 2 virtual folders: src and include
   // and place all the implementation files into the src
   // folder, the rest goes to the include folder
@@ -282,8 +369,10 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
          cFiles.begin();
        sit != cFiles.end(); ++sit) {
     xml.StartElement("File");
-    xml.Attribute("Name", cmSystemTools::RelativePath(projectPath.c_str(),
-                                                      sit->first.c_str()));
+    std::string fpath(sit->first);
+    std::string frelapath =
+      cmSystemTools::RelativePath(projectPath.c_str(), sit->first.c_str());
+    xml.Attribute("Name", frelapath);
     xml.EndElement();
   }
   xml.EndElement(); // VirtualDirectory
@@ -340,11 +429,18 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   xml.EndElement(); // ResourceCompiler
 
   xml.StartElement("General");
-  xml.Attribute("OutputFile", "$(IntermediateDirectory)/$(ProjectName)");
+  std::string outputPath = mf->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
+  if (!outputPath.empty())
+    xml.Attribute("OutputFile", outputPath + "/$(ProjectName)");
+  else
+    xml.Attribute("OutputFile", "$(IntermediateDirectory)/$(ProjectName)");
   xml.Attribute("IntermediateDirectory", "./");
   xml.Attribute("Command", "./$(ProjectName)");
   xml.Attribute("CommandArguments", "");
-  xml.Attribute("WorkingDirectory", "$(IntermediateDirectory)");
+  if (!outputPath.empty())
+    xml.Attribute("WorkingDirectory", outputPath);
+  else
+    xml.Attribute("WorkingDirectory", "$(IntermediateDirectory)");
   xml.Attribute("PauseExecWhenProcTerminates", "yes");
   xml.EndElement(); // General
 
@@ -398,6 +494,53 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
 
   xml.EndElement(); // GlobalSettings
   xml.EndElement(); // Settings
+}
+
+void cmExtraCodeLiteGenerator::CreateNewProjectFile(
+  const cmGeneratorTarget* gt, const std::string& filename)
+{
+  const cmMakefile* mf = gt->Makefile;
+  cmGeneratedFileStream fout(filename.c_str());
+  if (!fout) {
+    return;
+  }
+  cmXMLWriter xml(fout);
+
+  ////////////////////////////////////
+  xml.StartDocument("utf-8");
+  xml.StartElement("CodeLite_Project");
+  std::string visualname = gt->GetName();
+  switch (gt->GetType()) {
+    case cmState::STATIC_LIBRARY:
+    case cmState::SHARED_LIBRARY:
+    case cmState::MODULE_LIBRARY:
+      visualname = "lib" + visualname;
+    default: // intended fallthrough
+      break;
+  }
+  xml.Attribute("Name", visualname);
+  xml.Attribute("InternalType", "");
+
+  // Collect all used source files in the project
+  // Sort them into two containers, one for C/C++ implementation files
+  // which may have an acompanying header, one for all other files
+  std::string projectType;
+
+  std::vector<std::string> headerExts =
+    this->GlobalGenerator->GetCMakeInstance()->GetHeaderExtensions();
+
+  std::map<std::string, cmSourceFile*> cFiles;
+  std::set<std::string> otherFiles;
+
+  projectType = CollectSourceFiles(mf, gt, cFiles, otherFiles);
+
+  // Get the project path ( we need it later to convert files to
+  // their relative path)
+  std::string projectPath = cmSystemTools::GetFilenamePath(filename);
+
+  CreateProjectSourceEntries(cFiles, otherFiles, &xml, projectPath, mf,
+                             projectType);
+
   xml.EndElement(); // CodeLite_Project
 }
 
@@ -407,7 +550,7 @@ std::string cmExtraCodeLiteGenerator::GetCodeLiteCompilerName(
   // figure out which language to use
   // for now care only for C and C++
   std::string compilerIdVar = "CMAKE_CXX_COMPILER_ID";
-  if (this->GlobalGenerator->GetLanguageEnabled("CXX") == false) {
+  if (!this->GlobalGenerator->GetLanguageEnabled("CXX")) {
     compilerIdVar = "CMAKE_C_COMPILER_ID";
   }
 
diff --git a/Source/cmExtraCodeLiteGenerator.h b/Source/cmExtraCodeLiteGenerator.h
index 01ff31f..a349db5 100644
--- a/Source/cmExtraCodeLiteGenerator.h
+++ b/Source/cmExtraCodeLiteGenerator.h
@@ -1,22 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-  Copyright 2013 Eran Ifrah (eran.ifrah at gmail.com)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalCodeLiteGenerator_h
 #define cmGlobalCodeLiteGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
 
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 class cmLocalGenerator;
+class cmMakefile;
+class cmGeneratorTarget;
+class cmXMLWriter;
+class cmSourceFile;
 
 class cmExtraCodeLiteGenerator : public cmExternalMakefileProjectGenerator
 {
@@ -32,28 +32,33 @@ protected:
   std::string GetCleanCommand(const cmMakefile* mf) const;
   std::string GetRebuildCommand(const cmMakefile* mf) const;
   std::string GetSingleFileBuildCommand(const cmMakefile* mf) const;
+  std::vector<std::string> CreateProjectsByTarget(cmXMLWriter* xml);
+  std::vector<std::string> CreateProjectsByProjectMaps(cmXMLWriter* xml);
+  std::string CollectSourceFiles(const cmMakefile* makefile,
+                                 const cmGeneratorTarget* gt,
+                                 std::map<std::string, cmSourceFile*>& cFiles,
+                                 std::set<std::string>& otherFiles);
+  void FindMatchingHeaderfiles(std::map<std::string, cmSourceFile*>& cFiles,
+                               std::set<std::string>& otherFiles);
+  void CreateProjectSourceEntries(std::map<std::string, cmSourceFile*>& cFiles,
+                                  std::set<std::string>& otherFiles,
+                                  cmXMLWriter* xml,
+                                  const std::string& projectPath,
+                                  const cmMakefile* mf,
+                                  const std::string& projectType);
 
 public:
   cmExtraCodeLiteGenerator();
 
-  virtual std::string GetName() const
-  {
-    return cmExtraCodeLiteGenerator::GetActualName();
-  }
-  static std::string GetActualName() { return "CodeLite"; }
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmExtraCodeLiteGenerator;
-  }
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
-
-  virtual void Generate();
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
+
+  void Generate() CM_OVERRIDE;
   void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs);
 
   void CreateNewProjectFile(const std::vector<cmLocalGenerator*>& lgs,
                             const std::string& filename);
+  void CreateNewProjectFile(const cmGeneratorTarget* lg,
+                            const std::string& filename);
 };
 
 #endif
diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx
index f24e7fb..e342f4c 100644
--- a/Source/cmExtraEclipseCDT4Generator.cxx
+++ b/Source/cmExtraEclipseCDT4Generator.cxx
@@ -1,30 +1,28 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-  Copyright 2007 Miguel A. Figueroa-Villanueva
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraEclipseCDT4Generator.h"
 
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmSourceGroup.h"
 #include "cmState.h"
-#include "cmTarget.h"
+#include "cmSystemTools.h"
 #include "cmXMLWriter.h"
+#include "cmake.h"
 
-#include "cmSystemTools.h"
+#include <algorithm>
 #include <assert.h>
-#include <stdlib.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
 
 static void AppendAttribute(cmXMLWriter& xml, const char* keyval)
 {
@@ -46,16 +44,6 @@ void AppendDictionary(cmXMLWriter& xml, const char* key, T const& value)
 cmExtraEclipseCDT4Generator::cmExtraEclipseCDT4Generator()
   : cmExternalMakefileProjectGenerator()
 {
-// TODO: Verify if __CYGWIN__ should be checked.
-//#if defined(_WIN32) && !defined(__CYGWIN__)
-#if defined(_WIN32)
-  this->SupportedGlobalGenerators.push_back("NMake Makefiles");
-  this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
-//  this->SupportedGlobalGenerators.push_back("MSYS Makefiles");
-#endif
-  this->SupportedGlobalGenerators.push_back("Ninja");
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
-
   this->SupportsVirtualFolders = true;
   this->GenerateLinkedResources = true;
   this->SupportsGmakeErrorParser = true;
@@ -64,15 +52,31 @@ cmExtraEclipseCDT4Generator::cmExtraEclipseCDT4Generator()
   this->CXXEnabled = false;
 }
 
-void cmExtraEclipseCDT4Generator::GetDocumentation(cmDocumentationEntry& entry,
-                                                   const std::string&) const
+cmExternalMakefileProjectGeneratorFactory*
+cmExtraEclipseCDT4Generator::GetFactory()
 {
-  entry.Name = this->GetName();
-  entry.Brief = "Generates Eclipse CDT 4.0 project files.";
+  static cmExternalMakefileProjectGeneratorSimpleFactory<
+    cmExtraEclipseCDT4Generator>
+    factory("Eclipse CDT4", "Generates Eclipse CDT 4.0 project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
+// TODO: Verify if __CYGWIN__ should be checked.
+//#if defined(_WIN32) && !defined(__CYGWIN__)
+#if defined(_WIN32)
+    factory.AddSupportedGlobalGenerator("NMake Makefiles");
+    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
+// factory.AddSupportedGlobalGenerator("MSYS Makefiles");
+#endif
+    factory.AddSupportedGlobalGenerator("Ninja");
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
+  }
+
+  return &factory;
 }
 
 void cmExtraEclipseCDT4Generator::EnableLanguage(
-  std::vector<std::string> const& languages, cmMakefile*, bool)
+  std::vector<std::string> const& languages, cmMakefile* /*unused*/,
+  bool /*optional*/)
 {
   for (std::vector<std::string>::const_iterator lit = languages.begin();
        lit != languages.end(); ++lit) {
@@ -129,7 +133,7 @@ void cmExtraEclipseCDT4Generator::Generate()
     (this->IsOutOfSourceBuild &&
      mf->IsOn("CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT"));
 
-  if ((this->GenerateSourceProject == false) &&
+  if (!this->GenerateSourceProject &&
       (mf->IsOn("ECLIPSE_CDT4_GENERATE_SOURCE_PROJECT"))) {
     mf->IssueMessage(
       cmake::WARNING,
@@ -208,7 +212,8 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out,
   // get the variables from the environment and from the cache and then
   // figure out which one to use:
 
-  const char* envVarValue = getenv(envVar);
+  std::string envVarValue;
+  const bool envVarSet = cmSystemTools::GetEnv(envVar, envVarValue);
 
   std::string cacheEntryName = "CMAKE_ECLIPSE_ENVVAR_";
   cacheEntryName += envVar;
@@ -217,17 +222,17 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out,
 
   // now we have both, decide which one to use
   std::string valueToUse;
-  if (envVarValue == 0 && cacheValue == 0) {
+  if (!envVarSet && cacheValue == CM_NULLPTR) {
     // nothing known, do nothing
     valueToUse = "";
-  } else if (envVarValue != 0 && cacheValue == 0) {
+  } else if (envVarSet && cacheValue == CM_NULLPTR) {
     // The variable is in the env, but not in the cache. Use it and put it
     // in the cache
     valueToUse = envVarValue;
     mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
                            cacheEntryName.c_str(), cmState::STRING, true);
     mf->GetCMakeInstance()->SaveCache(lg->GetBinaryDirectory());
-  } else if (envVarValue == 0 && cacheValue != 0) {
+  } else if (!envVarSet && cacheValue != CM_NULLPTR) {
     // It is already in the cache, but not in the env, so use it from the cache
     valueToUse = cacheValue;
   } else {
@@ -311,7 +316,7 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile()
                    "false");
 
   // set project specific environment
-  std::stringstream environment;
+  std::ostringstream environment;
   environment << "VERBOSE=1|CMAKE_NO_VERBOSE=1|"; // verbose Makefile output
   // set vsvars32.bat environment available at CMake time,
   //   but not necessarily when eclipse is open
@@ -341,7 +346,7 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile()
   AppendDictionary(xml, "org.eclipse.cdt.make.core.autoBuildTarget", "all");
 
   // set error parsers
-  std::stringstream errorOutputParser;
+  std::ostringstream errorOutputParser;
 
   if (compilerId == "MSVC") {
     errorOutputParser << "org.eclipse.cdt.core.VCErrorParser;";
@@ -398,8 +403,8 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile()
   if (this->IsOutOfSourceBuild) {
     // create a linked resource to CMAKE_SOURCE_DIR
     // (this is not done anymore for each project because of
-    // http://public.kitware.com/Bug/view.php?id=9978 and because I found it
-    // actually quite confusing in bigger projects with many directories and
+    // https://gitlab.kitware.com/cmake/cmake/issues/9978 and because I found
+    // it actually quite confusing in bigger projects with many directories and
     // projects, Alex
 
     std::string sourceLinkedResourceName = "[Source directory]";
@@ -897,8 +902,8 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
        it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) {
     const std::vector<cmGeneratorTarget*> targets =
       (*it)->GetGeneratorTargets();
-    std::string subdir = (*it)->Convert((*it)->GetCurrentBinaryDirectory(),
-                                        cmOutputConverter::HOME_OUTPUT);
+    std::string subdir = (*it)->ConvertToRelativePath(
+      this->HomeOutputDirectory, (*it)->GetCurrentBinaryDirectory());
     if (subdir == ".") {
       subdir = "";
     }
diff --git a/Source/cmExtraEclipseCDT4Generator.h b/Source/cmExtraEclipseCDT4Generator.h
index 0cef071..fe71172 100644
--- a/Source/cmExtraEclipseCDT4Generator.h
+++ b/Source/cmExtraEclipseCDT4Generator.h
@@ -1,24 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-  Copyright 2007 Miguel A. Figueroa-Villanueva
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExtraEclipseCDT4Generator_h
 #define cmExtraEclipseCDT4Generator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
 
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmLocalGenerator;
 class cmMakefile;
-class cmXMLWriter;
 class cmSourceGroup;
+class cmXMLWriter;
 
 /** \class cmExtraEclipseCDT4Generator
  * \brief Write Eclipse project files for Makefile based projects
@@ -35,24 +32,12 @@ public:
 
   cmExtraEclipseCDT4Generator();
 
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmExtraEclipseCDT4Generator;
-  }
-
-  virtual std::string GetName() const
-  {
-    return cmExtraEclipseCDT4Generator::GetActualName();
-  }
-
-  static std::string GetActualName() { return "Eclipse CDT4"; }
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
-  virtual void EnableLanguage(std::vector<std::string> const& languages,
-                              cmMakefile*, bool optional);
+  void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
+                      bool optional) CM_OVERRIDE;
 
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
 private:
   // create .project file in the source tree
@@ -82,7 +67,7 @@ private:
                            const std::string& make,
                            const std::string& makeArguments,
                            const std::string& path, const char* prefix = "",
-                           const char* makeTarget = NULL);
+                           const char* makeTarget = CM_NULLPTR);
   static void AppendScannerProfile(
     cmXMLWriter& xml, const std::string& profileID, bool openActionEnabled,
     const std::string& openActionFilePath, bool pParserEnabled,
diff --git a/Source/cmExtraKateGenerator.cxx b/Source/cmExtraKateGenerator.cxx
index 02159dd..b78d09a 100644
--- a/Source/cmExtraKateGenerator.cxx
+++ b/Source/cmExtraKateGenerator.cxx
@@ -1,45 +1,43 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraKateGenerator.h"
 
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
 
-#include <cmsys/SystemTools.hxx>
+#include <ostream>
+#include <set>
+#include <string.h>
+#include <vector>
 
-void cmExtraKateGenerator::GetDocumentation(cmDocumentationEntry& entry,
-                                            const std::string&) const
+cmExtraKateGenerator::cmExtraKateGenerator()
+  : cmExternalMakefileProjectGenerator()
 {
-  entry.Name = this->GetName();
-  entry.Brief = "Generates Kate project files.";
 }
 
-cmExtraKateGenerator::cmExtraKateGenerator()
-  : cmExternalMakefileProjectGenerator()
+cmExternalMakefileProjectGeneratorFactory* cmExtraKateGenerator::GetFactory()
 {
+  static cmExternalMakefileProjectGeneratorSimpleFactory<cmExtraKateGenerator>
+    factory("Kate", "Generates Kate project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
 #if defined(_WIN32)
-  this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
-  this->SupportedGlobalGenerators.push_back("NMake Makefiles");
+    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
+    factory.AddSupportedGlobalGenerator("NMake Makefiles");
 // disable until somebody actually tests it:
-//  this->SupportedGlobalGenerators.push_back("MSYS Makefiles");
+// factory.AddSupportedGlobalGenerator("MSYS Makefiles");
 #endif
-  this->SupportedGlobalGenerators.push_back("Ninja");
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
+    factory.AddSupportedGlobalGenerator("Ninja");
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
+  }
+
+  return &factory;
 }
 
 void cmExtraKateGenerator::Generate()
@@ -137,9 +135,9 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
             if (targetName == "edit_cache") {
               const char* editCommand =
                 (*it)->GetMakefile()->GetDefinition("CMAKE_EDIT_COMMAND");
-              if (editCommand == 0) {
+              if (editCommand == CM_NULLPTR) {
                 insertTarget = false;
-              } else if (strstr(editCommand, "ccmake") != NULL) {
+              } else if (strstr(editCommand, "ccmake") != CM_NULLPTR) {
                 insertTarget = false;
               }
             }
diff --git a/Source/cmExtraKateGenerator.h b/Source/cmExtraKateGenerator.h
index 71e88a9..badaca9 100644
--- a/Source/cmExtraKateGenerator.h
+++ b/Source/cmExtraKateGenerator.h
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2013 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExtraKateGenerator_h
 #define cmExtraKateGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
 
-class cmLocalGenerator;
+#include <string>
+
 class cmGeneratedFileStream;
+class cmLocalGenerator;
 
 /** \class cmExtraKateGenerator
  * \brief Write Kate project files for Makefile or ninja based projects
@@ -26,20 +20,9 @@ class cmExtraKateGenerator : public cmExternalMakefileProjectGenerator
 public:
   cmExtraKateGenerator();
 
-  virtual std::string GetName() const
-  {
-    return cmExtraKateGenerator::GetActualName();
-  }
-  static std::string GetActualName() { return "Kate"; }
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmExtraKateGenerator;
-  }
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
-
-  virtual void Generate();
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
+
+  void Generate() CM_OVERRIDE;
 
 private:
   void CreateKateProjectFile(const cmLocalGenerator* lg) const;
diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx
index 9b3ea0b..5ae969b 100644
--- a/Source/cmExtraSublimeTextGenerator.cxx
+++ b/Source/cmExtraSublimeTextGenerator.cxx
@@ -1,28 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraSublimeTextGenerator.h"
 
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
-#include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
 
-#include <cmsys/SystemTools.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <ostream>
+#include <set>
+#include <string.h>
+#include <utility>
 
 /*
 Sublime Text 2 Generator
@@ -38,24 +31,30 @@ http://www.sublimetext.com/docs/2/projects.html
 http://sublimetext.info/docs/en/reference/build_systems.html
 */
 
-void cmExtraSublimeTextGenerator::GetDocumentation(cmDocumentationEntry& entry,
-                                                   const std::string&) const
+cmExternalMakefileProjectGeneratorFactory*
+cmExtraSublimeTextGenerator::GetFactory()
 {
-  entry.Name = this->GetName();
-  entry.Brief = "Generates Sublime Text 2 project files.";
+  static cmExternalMakefileProjectGeneratorSimpleFactory<
+    cmExtraSublimeTextGenerator>
+    factory("Sublime Text 2", "Generates Sublime Text 2 project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
+#if defined(_WIN32)
+    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
+    factory.AddSupportedGlobalGenerator("NMake Makefiles");
+// disable until somebody actually tests it:
+// factory.AddSupportedGlobalGenerator("MSYS Makefiles");
+#endif
+    factory.AddSupportedGlobalGenerator("Ninja");
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
+  }
+
+  return &factory;
 }
 
 cmExtraSublimeTextGenerator::cmExtraSublimeTextGenerator()
   : cmExternalMakefileProjectGenerator()
 {
-#if defined(_WIN32)
-  this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
-  this->SupportedGlobalGenerators.push_back("NMake Makefiles");
-// disable until somebody actually tests it:
-//  this->SupportedGlobalGenerators.push_back("MSYS Makefiles");
-#endif
-  this->SupportedGlobalGenerators.push_back("Ninja");
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
 }
 
 void cmExtraSublimeTextGenerator::Generate()
@@ -134,9 +133,9 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
   std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
   std::string compiler = "";
   if (!lgs.empty()) {
-    this->AppendTarget(fout, "all", lgs[0], 0, make.c_str(), mf,
+    this->AppendTarget(fout, "all", lgs[0], CM_NULLPTR, make.c_str(), mf,
                        compiler.c_str(), sourceFileFlags, true);
-    this->AppendTarget(fout, "clean", lgs[0], 0, make.c_str(), mf,
+    this->AppendTarget(fout, "clean", lgs[0], CM_NULLPTR, make.c_str(), mf,
                        compiler.c_str(), sourceFileFlags, false);
   }
 
@@ -155,7 +154,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
           // not from the subdirs
           if (strcmp((*lg)->GetCurrentBinaryDirectory(),
                      (*lg)->GetBinaryDirectory()) == 0) {
-            this->AppendTarget(fout, targetName, *lg, 0, make.c_str(),
+            this->AppendTarget(fout, targetName, *lg, CM_NULLPTR, make.c_str(),
                                makefile, compiler.c_str(), sourceFileFlags,
                                false);
           }
@@ -172,8 +171,9 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
             break;
           }
 
-          this->AppendTarget(fout, targetName, *lg, 0, make.c_str(), makefile,
-                             compiler.c_str(), sourceFileFlags, false);
+          this->AppendTarget(fout, targetName, *lg, CM_NULLPTR, make.c_str(),
+                             makefile, compiler.c_str(), sourceFileFlags,
+                             false);
           break;
         case cmState::EXECUTABLE:
         case cmState::STATIC_LIBRARY:
@@ -199,12 +199,11 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
 void cmExtraSublimeTextGenerator::AppendTarget(
   cmGeneratedFileStream& fout, const std::string& targetName,
   cmLocalGenerator* lg, cmGeneratorTarget* target, const char* make,
-  const cmMakefile* makefile,
-  const char*, // compiler
+  const cmMakefile* makefile, const char* /*compiler*/,
   MapSourceFileFlags& sourceFileFlags, bool firstTarget)
 {
 
-  if (target != 0) {
+  if (target != CM_NULLPTR) {
     std::vector<cmSourceFile*> sourceFiles;
     target->GetSourceFiles(sourceFiles,
                            makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
@@ -295,7 +294,7 @@ std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
     std::string makefileName;
     if (generator == "MinGW Makefiles") {
       // no escaping of spaces in this case, see
-      // http://public.kitware.com/Bug/view.php?id=10014
+      // https://gitlab.kitware.com/cmake/cmake/issues/10014
       makefileName = makefile;
     } else {
       makefileName = cmSystemTools::ConvertToOutputPath(makefile);
@@ -314,27 +313,14 @@ std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
   cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* gtgt)
 {
   std::string flags;
-
-  cmMakefile* makefile = lg->GetMakefile();
   std::string language = source->GetLanguage();
   if (language.empty()) {
     language = "C";
   }
-  const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-  // Add language-specific flags.
-  lg->AddLanguageFlags(flags, language, config);
-
-  lg->AddArchitectureFlags(flags, gtgt, language, config);
+  std::string const& config =
+    lg->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
 
-  // TODO: Fortran support.
-  // // Fortran-specific flags computed for this target.
-  // if(*l == "Fortran")
-  //   {
-  //   this->AddFortranFlags(flags);
-  //   }
-
-  // Add shared-library flags if needed.
-  lg->AddCMP0018Flags(flags, gtgt, language, config);
+  lg->GetTargetCompileFlags(gtgt, config, language, flags);
 
   // Add include directory flags.
   {
@@ -345,17 +331,9 @@ std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
     lg->AppendFlags(flags, includeFlags);
   }
 
-  // Append old-style preprocessor definition flags.
-  lg->AppendFlags(flags, makefile->GetDefineFlags());
-
-  // Add target-specific flags.
-  lg->AddCompileOptions(flags, gtgt, language, config);
-
   // Add source file specific flags.
   lg->AppendFlags(flags, source->GetProperty("COMPILE_FLAGS"));
 
-  // TODO: Handle Apple frameworks.
-
   return flags;
 }
 
diff --git a/Source/cmExtraSublimeTextGenerator.h b/Source/cmExtraSublimeTextGenerator.h
index 6efec7a..c917992 100644
--- a/Source/cmExtraSublimeTextGenerator.h
+++ b/Source/cmExtraSublimeTextGenerator.h
@@ -1,25 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExtraSublimeTextGenerator_h
 #define cmExtraSublimeTextGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
-#include "cmSourceFile.h"
 
-class cmLocalGenerator;
-class cmMakefile;
+#include <map>
+#include <string>
+#include <vector>
+
 class cmGeneratedFileStream;
 class cmGeneratorTarget;
+class cmLocalGenerator;
+class cmMakefile;
+class cmSourceFile;
 
 /** \class cmExtraSublimeTextGenerator
  * \brief Write Sublime Text 2 project files for Makefile based projects
@@ -27,23 +23,11 @@ class cmGeneratorTarget;
 class cmExtraSublimeTextGenerator : public cmExternalMakefileProjectGenerator
 {
 public:
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
   typedef std::map<std::string, std::vector<std::string> > MapSourceFileFlags;
   cmExtraSublimeTextGenerator();
 
-  virtual std::string GetName() const
-  {
-    return cmExtraSublimeTextGenerator::GetActualName();
-  }
-  static std::string GetActualName() { return "Sublime Text 2"; }
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmExtraSublimeTextGenerator;
-  }
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
-
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
 private:
   void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs);
diff --git a/Source/cmFLTKWrapUICommand.cxx b/Source/cmFLTKWrapUICommand.cxx
index ebd6223..5f621f1 100644
--- a/Source/cmFLTKWrapUICommand.cxx
+++ b/Source/cmFLTKWrapUICommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFLTKWrapUICommand.h"
 
 #include "cmSourceFile.h"
@@ -73,8 +64,8 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
 
       // Add command for generating the .h and .cxx files
       std::string no_main_dependency = "";
-      const char* no_comment = 0;
-      const char* no_working_dir = 0;
+      const char* no_comment = CM_NULLPTR;
+      const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
         cxxres, depends, no_main_dependency, commandLines, no_comment,
         no_working_dir);
diff --git a/Source/cmFLTKWrapUICommand.h b/Source/cmFLTKWrapUICommand.h
index 2e60051..202067f 100644
--- a/Source/cmFLTKWrapUICommand.h
+++ b/Source/cmFLTKWrapUICommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFLTKWrapUICommand_h
 #define cmFLTKWrapUICommand_h
 
@@ -28,14 +19,14 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFLTKWrapUICommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFLTKWrapUICommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This is called at the end after all the information
@@ -43,13 +34,13 @@ public:
    * not implement this method.  At this point, reading and
    * writing to the cache can be done.
    */
-  virtual void FinalPass();
-  virtual bool HasFinalPass() const { return true; }
+  void FinalPass() CM_OVERRIDE;
+  bool HasFinalPass() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "fltk_wrap_ui"; }
+  std::string GetName() const CM_OVERRIDE { return "fltk_wrap_ui"; }
 
 private:
   /**
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index 4e72f36..a71ff71 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileCommand.h"
 
 #include "cmAlgorithms.h"
@@ -34,12 +25,12 @@
 // include sys/stat.h after sys/types.h
 #include <sys/stat.h>
 
+#include <cm_auto_ptr.hxx>
 #include <cmsys/Directory.hxx>
 #include <cmsys/Encoding.hxx>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
 #include <cmsys/RegularExpression.hxx>
-#include <cmsys/auto_ptr.hxx>
 
 // Table of permissions flags.
 #if defined(_WIN32) && !defined(__CYGWIN__)
@@ -104,19 +95,25 @@ bool cmFileCommand::InitialPass(std::vector<std::string> const& args,
   std::string subCommand = args[0];
   if (subCommand == "WRITE") {
     return this->HandleWriteCommand(args, false);
-  } else if (subCommand == "APPEND") {
+  }
+  if (subCommand == "APPEND") {
     return this->HandleWriteCommand(args, true);
-  } else if (subCommand == "DOWNLOAD") {
+  }
+  if (subCommand == "DOWNLOAD") {
     return this->HandleDownloadCommand(args);
-  } else if (subCommand == "UPLOAD") {
+  }
+  if (subCommand == "UPLOAD") {
     return this->HandleUploadCommand(args);
-  } else if (subCommand == "READ") {
+  }
+  if (subCommand == "READ") {
     return this->HandleReadCommand(args);
-  } else if (subCommand == "MD5" || subCommand == "SHA1" ||
-             subCommand == "SHA224" || subCommand == "SHA256" ||
-             subCommand == "SHA384" || subCommand == "SHA512") {
+  }
+  if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
+      subCommand == "SHA256" || subCommand == "SHA384" ||
+      subCommand == "SHA512") {
     return this->HandleHashCommand(args);
-  } else if (subCommand == "STRINGS") {
+  }
+  if (subCommand == "STRINGS") {
     return this->HandleStringsCommand(args);
   } else if (subCommand == "GLOB") {
     return this->HandleGlobCommand(args, false);
@@ -231,17 +228,17 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
   cmCommandArgumentGroup group;
 
   cmCAString readArg(&argHelper, "READ");
-  cmCAString fileNameArg(&argHelper, 0);
-  cmCAString resultArg(&argHelper, 0);
+  cmCAString fileNameArg(&argHelper, CM_NULLPTR);
+  cmCAString resultArg(&argHelper, CM_NULLPTR);
 
   cmCAString offsetArg(&argHelper, "OFFSET", &group);
   cmCAString limitArg(&argHelper, "LIMIT", &group);
   cmCAEnabler hexOutputArg(&argHelper, "HEX", &group);
-  readArg.Follows(0);
+  readArg.Follows(CM_NULLPTR);
   fileNameArg.Follows(&readArg);
   resultArg.Follows(&fileNameArg);
   group.Follows(&resultArg);
-  argHelper.Parse(&args, 0);
+  argHelper.Parse(&args, CM_NULLPTR);
 
   std::string fileName = fileNameArg.GetString();
   if (!cmsys::SystemTools::FileIsFullPath(fileName.c_str())) {
@@ -257,7 +254,7 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
     fileName.c_str(), std::ios::in |
       (hexOutputArg.IsEnabled() ? std::ios::binary : std::ios::in));
 #else
-  cmsys::ifstream file(fileName.c_str(), std::ios::in);
+  cmsys::ifstream file(fileName.c_str());
 #endif
 
   if (!file) {
@@ -330,7 +327,7 @@ bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
     return false;
   }
 
-  cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
+  CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
   if (hash.get()) {
     std::string out = hash->HashFile(args[1]);
     if (!out.empty()) {
@@ -526,7 +523,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
 #if defined(_WIN32) || defined(__CYGWIN__)
   cmsys::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
 #else
-  cmsys::ifstream fin(fileName.c_str(), std::ios::in);
+  cmsys::ifstream fin(fileName.c_str());
 #endif
   if (!fin) {
     std::ostringstream e;
@@ -594,8 +591,9 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
       // how many octets are there?
       unsigned int num_utf8_bytes = 0;
       for (unsigned int j = 0; num_utf8_bytes == 0 && j < 3; j++) {
-        if ((c & utf8_check_table[j][0]) == utf8_check_table[j][1])
+        if ((c & utf8_check_table[j][0]) == utf8_check_table[j][1]) {
           num_utf8_bytes = j + 2;
+        }
       }
 
       // get subsequent octets and check that they are valid
@@ -901,9 +899,9 @@ bool cmFileCommand::HandleDifferentCommand(
    */
 
   // Evaluate arguments.
-  const char* file_lhs = 0;
-  const char* file_rhs = 0;
-  const char* var = 0;
+  const char* file_lhs = CM_NULLPTR;
+  const char* file_rhs = CM_NULLPTR;
+  const char* var = CM_NULLPTR;
   enum Doing
   {
     DoingNone,
@@ -958,7 +956,7 @@ struct cmFileCopier
     , MatchlessFiles(true)
     , FilePermissions(0)
     , DirPermissions(0)
-    , CurrentMatchRule(0)
+    , CurrentMatchRule(CM_NULLPTR)
     , UseGivenPermissionsFile(false)
     , UseGivenPermissionsDir(false)
     , UseSourcePermissions(true)
@@ -1408,11 +1406,14 @@ bool cmFileCopier::Install(const char* fromFile, const char* toFile)
 
   if (cmSystemTools::SameFile(fromFile, toFile)) {
     return true;
-  } else if (cmSystemTools::FileIsSymlink(fromFile)) {
+  }
+  if (cmSystemTools::FileIsSymlink(fromFile)) {
     return this->InstallSymlink(fromFile, toFile);
-  } else if (cmSystemTools::FileIsDirectory(fromFile)) {
+  }
+  if (cmSystemTools::FileIsDirectory(fromFile)) {
     return this->InstallDirectory(fromFile, toFile, match_properties);
-  } else if (cmSystemTools::FileExists(fromFile)) {
+  }
+  if (cmSystemTools::FileExists(fromFile)) {
     return this->InstallFile(fromFile, toFile, match_properties);
   }
   return this->ReportMissing(fromFile);
@@ -1609,13 +1610,15 @@ struct cmFileInstaller : public cmFileCopier
     // Installation does not use source permissions by default.
     this->UseSourcePermissions = false;
     // Check whether to copy files always or only if they have changed.
-    this->Always =
-      cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
+    std::string install_always;
+    if (cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS", install_always)) {
+      this->Always = cmSystemTools::IsOn(install_always.c_str());
+    }
     // Get the current manifest.
     this->Manifest =
       this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
   }
-  ~cmFileInstaller()
+  ~cmFileInstaller() CM_OVERRIDE
   {
     // Save the updated install manifest.
     this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
@@ -1640,12 +1643,12 @@ protected:
     this->Manifest += file.substr(this->DestDirLength);
   }
 
-  virtual std::string const& ToName(std::string const& fromName)
+  std::string const& ToName(std::string const& fromName) CM_OVERRIDE
   {
     return this->Rename.empty() ? fromName : this->Rename;
   }
 
-  virtual void ReportCopy(const char* toFile, Type type, bool copy)
+  void ReportCopy(const char* toFile, Type type, bool copy) CM_OVERRIDE
   {
     if (!this->MessageNever && (copy || !this->MessageLazy)) {
       std::string message = (copy ? "Installing: " : "Up-to-date: ");
@@ -1657,11 +1660,11 @@ protected:
       this->ManifestAppend(toFile);
     }
   }
-  virtual bool ReportMissing(const char* fromFile)
+  bool ReportMissing(const char* fromFile) CM_OVERRIDE
   {
     return (this->Optional || this->cmFileCopier::ReportMissing(fromFile));
   }
-  virtual bool Install(const char* fromFile, const char* toFile)
+  bool Install(const char* fromFile, const char* toFile) CM_OVERRIDE
   {
     // Support installing from empty source to make a directory.
     if (this->InstallType == cmInstallType_DIRECTORY && !*fromFile) {
@@ -1670,16 +1673,16 @@ protected:
     return this->cmFileCopier::Install(fromFile, toFile);
   }
 
-  virtual bool Parse(std::vector<std::string> const& args);
+  bool Parse(std::vector<std::string> const& args) CM_OVERRIDE;
   enum
   {
     DoingType = DoingLast1,
     DoingRename,
     DoingLast2
   };
-  virtual bool CheckKeyword(std::string const& arg);
-  virtual bool CheckValue(std::string const& arg);
-  virtual void DefaultFilePermissions()
+  bool CheckKeyword(std::string const& arg) CM_OVERRIDE;
+  bool CheckValue(std::string const& arg) CM_OVERRIDE;
+  void DefaultFilePermissions() CM_OVERRIDE
   {
     this->cmFileCopier::DefaultFilePermissions();
     // Add execute permissions based on the target type.
@@ -1869,9 +1872,8 @@ bool cmFileInstaller::HandleInstallDestination()
     return false;
   }
 
-  const char* destdir = cmSystemTools::GetEnv("DESTDIR");
-  if (destdir && *destdir) {
-    std::string sdestdir = destdir;
+  std::string sdestdir;
+  if (cmSystemTools::GetEnv("DESTDIR", sdestdir) && !sdestdir.empty()) {
     cmSystemTools::ConvertToUnixSlashes(sdestdir);
     char ch1 = destination[0];
     char ch2 = destination[1];
@@ -1942,9 +1944,9 @@ bool cmFileCommand::HandleRPathChangeCommand(
   std::vector<std::string> const& args)
 {
   // Evaluate arguments.
-  const char* file = 0;
-  const char* oldRPath = 0;
-  const char* newRPath = 0;
+  const char* file = CM_NULLPTR;
+  const char* oldRPath = CM_NULLPTR;
+  const char* newRPath = CM_NULLPTR;
   enum Doing
   {
     DoingNone,
@@ -2032,7 +2034,7 @@ bool cmFileCommand::HandleRPathRemoveCommand(
   std::vector<std::string> const& args)
 {
   // Evaluate arguments.
-  const char* file = 0;
+  const char* file = CM_NULLPTR;
   enum Doing
   {
     DoingNone,
@@ -2096,8 +2098,8 @@ bool cmFileCommand::HandleRPathCheckCommand(
   std::vector<std::string> const& args)
 {
   // Evaluate arguments.
-  const char* file = 0;
-  const char* rpath = 0;
+  const char* file = CM_NULLPTR;
+  const char* rpath = CM_NULLPTR;
   enum Doing
   {
     DoingNone,
@@ -2438,7 +2440,7 @@ public:
 
   inline void release(void)
   {
-    this->Easy = 0;
+    this->Easy = CM_NULLPTR;
     return;
   }
 
@@ -2478,8 +2480,11 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
   const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
   std::string expectedHash;
   std::string hashMatchMSG;
-  cmsys::auto_ptr<cmCryptoHash> hash;
+  CM_AUTO_PTR<cmCryptoHash> hash;
   bool showProgress = false;
+  std::string userpwd;
+
+  std::list<std::string> curl_headers;
 
   while (i != args.end()) {
     if (*i == "TIMEOUT") {
@@ -2534,7 +2539,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
         this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
         return false;
       }
-      hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New("MD5"));
+      hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New("MD5"));
       hashMatchMSG = "MD5 sum";
       expectedHash = cmSystemTools::LowerCase(*i);
     } else if (*i == "SHOW_PROGRESS") {
@@ -2555,7 +2560,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
       }
       std::string algo = i->substr(0, pos);
       expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
-      hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
+      hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
       if (!hash.get()) {
         std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
         err += algo;
@@ -2563,6 +2568,25 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
         return false;
       }
       hashMatchMSG = algo + " hash";
+    } else if (*i == "USERPWD") {
+      ++i;
+      if (i == args.end()) {
+        this->SetError("DOWNLOAD missing string for USERPWD.");
+        return false;
+      }
+      userpwd = *i;
+    } else if (*i == "HTTPHEADER") {
+      ++i;
+      if (i == args.end()) {
+        this->SetError("DOWNLOAD missing string for HTTPHEADER.");
+        return false;
+      }
+      curl_headers.push_back(*i);
+    } else {
+      // Do not return error for compatibility reason.
+      std::string err = "Unexpected argument: ";
+      err += *i;
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
     }
     ++i;
   }
@@ -2697,8 +2721,22 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
     check_curl_result(res, "DOWNLOAD cannot set progress data: ");
   }
 
+  if (!userpwd.empty()) {
+    res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
+    check_curl_result(res, "DOWNLOAD cannot set user password: ");
+  }
+
+  struct curl_slist* headers = CM_NULLPTR;
+  for (std::list<std::string>::const_iterator h = curl_headers.begin();
+       h != curl_headers.end(); ++h) {
+    headers = ::curl_slist_append(headers, h->c_str());
+  }
+  ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
+
   res = ::curl_easy_perform(curl);
 
+  ::curl_slist_free_all(headers);
+
   /* always cleanup */
   g_curl.release();
   ::curl_easy_cleanup(curl);
@@ -2777,6 +2815,9 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
   std::string logVar;
   std::string statusVar;
   bool showProgress = false;
+  std::string userpwd;
+
+  std::list<std::string> curl_headers;
 
   while (i != args.end()) {
     if (*i == "TIMEOUT") {
@@ -2811,6 +2852,25 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
       statusVar = *i;
     } else if (*i == "SHOW_PROGRESS") {
       showProgress = true;
+    } else if (*i == "USERPWD") {
+      ++i;
+      if (i == args.end()) {
+        this->SetError("UPLOAD missing string for USERPWD.");
+        return false;
+      }
+      userpwd = *i;
+    } else if (*i == "HTTPHEADER") {
+      ++i;
+      if (i == args.end()) {
+        this->SetError("UPLOAD missing string for HTTPHEADER.");
+        return false;
+      }
+      curl_headers.push_back(*i);
+    } else {
+      // Do not return error for compatibility reason.
+      std::string err = "Unexpected argument: ";
+      err += *i;
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
     }
 
     ++i;
@@ -2919,8 +2979,22 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
     ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
   check_curl_result(res, "UPLOAD cannot set input file size: ");
 
+  if (!userpwd.empty()) {
+    res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
+    check_curl_result(res, "UPLOAD cannot set user password: ");
+  }
+
+  struct curl_slist* headers = CM_NULLPTR;
+  for (std::list<std::string>::const_iterator h = curl_headers.begin();
+       h != curl_headers.end(); ++h) {
+    headers = ::curl_slist_append(headers, h->c_str());
+  }
+  ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
+
   res = ::curl_easy_perform(curl);
 
+  ::curl_slist_free_all(headers);
+
   /* always cleanup */
   g_curl.release();
   ::curl_easy_cleanup(curl);
@@ -2934,7 +3008,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
   ::curl_global_cleanup();
 
   fclose(fin);
-  fin = NULL;
+  fin = CM_NULLPTR;
 
   if (!logVar.empty()) {
     std::string log;
@@ -2971,11 +3045,11 @@ void cmFileCommand::AddEvaluationFile(const std::string& inputName,
   cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
 
   cmGeneratorExpression outputGe(lfbt);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> outputCge =
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> outputCge =
     outputGe.Parse(outputExpr);
 
   cmGeneratorExpression conditionGe(lfbt);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> conditionCge =
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> conditionCge =
     conditionGe.Parse(condition);
 
   this->Makefile->AddEvaluationFile(inputName, outputCge, conditionCge,
@@ -3056,20 +3130,20 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args)
       if (i >= args.size()) {
         this->Makefile->IssueMessage(cmake::FATAL_ERROR, merr);
         return false;
+      }
+      if (args[i] == "FUNCTION") {
+        guard = GUARD_FUNCTION;
+      } else if (args[i] == "FILE") {
+        guard = GUARD_FILE;
+      } else if (args[i] == "PROCESS") {
+        guard = GUARD_PROCESS;
       } else {
-        if (args[i] == "FUNCTION") {
-          guard = GUARD_FUNCTION;
-        } else if (args[i] == "FILE") {
-          guard = GUARD_FILE;
-        } else if (args[i] == "PROCESS") {
-          guard = GUARD_PROCESS;
-        } else {
-          std::ostringstream e;
-          e << merr << ", but got:\n  \"" << args[i] << "\".";
-          this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-          return false;
-        }
+        std::ostringstream e;
+        e << merr << ", but got:\n  \"" << args[i] << "\".";
+        this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+        return false;
       }
+
     } else if (args[i] == "RESULT_VARIABLE") {
       ++i;
       if (i >= args.size()) {
@@ -3186,7 +3260,8 @@ bool cmFileCommand::HandleTimestampCommand(
   if (args.size() < 3) {
     this->SetError("sub-command TIMESTAMP requires at least two arguments.");
     return false;
-  } else if (args.size() > 5) {
+  }
+  if (args.size() > 5) {
     this->SetError("sub-command TIMESTAMP takes at most four arguments.");
     return false;
   }
diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h
index 84bb456..1d21a19 100644
--- a/Source/cmFileCommand.h
+++ b/Source/cmFileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFileCommand_h
 #define cmFileCommand_h
 
@@ -26,24 +17,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFileCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "file"; }
+  std::string GetName() const CM_OVERRIDE { return "file"; }
 
   cmTypeMacro(cmFileCommand, cmCommand);
 
diff --git a/Source/cmFileLock.cxx b/Source/cmFileLock.cxx
index 828511f..786d6c6 100644
--- a/Source/cmFileLock.cxx
+++ b/Source/cmFileLock.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileLock.h"
 
 #include "cmFileLockResult.h"
diff --git a/Source/cmFileLock.h b/Source/cmFileLock.h
index 538b716..ab3cb1f 100644
--- a/Source/cmFileLock.h
+++ b/Source/cmFileLock.h
@@ -1,19 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFileLock_h
 #define cmFileLock_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
 
 #if defined(_WIN32)
 #include <windows.h> // HANDLE
diff --git a/Source/cmFileLockPool.cxx b/Source/cmFileLockPool.cxx
index 7c51459..7b1564c 100644
--- a/Source/cmFileLockPool.cxx
+++ b/Source/cmFileLockPool.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileLockPool.h"
 
 #include <assert.h>
@@ -140,10 +130,9 @@ cmFileLockResult cmFileLockPool::ScopePool::Lock(const std::string& filename,
   if (result.IsOk()) {
     this->Locks.push_back(lock);
     return cmFileLockResult::MakeOk();
-  } else {
-    delete lock;
-    return result;
   }
+  delete lock;
+  return result;
 }
 
 cmFileLockResult cmFileLockPool::ScopePool::Release(
diff --git a/Source/cmFileLockPool.h b/Source/cmFileLockPool.h
index dc42e6f..fbe01c8 100644
--- a/Source/cmFileLockPool.h
+++ b/Source/cmFileLockPool.h
@@ -1,23 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFileLockPool_h
 #define cmFileLockPool_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <list>
+#include <string>
 
-class cmFileLockResult;
 class cmFileLock;
+class cmFileLockResult;
 
 class cmFileLockPool
 {
diff --git a/Source/cmFileLockResult.cxx b/Source/cmFileLockResult.cxx
index 090fe60..a040705 100644
--- a/Source/cmFileLockResult.cxx
+++ b/Source/cmFileLockResult.cxx
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileLockResult.h"
 
 #include <errno.h>
+#include <string.h>
 
 cmFileLockResult cmFileLockResult::MakeOk()
 {
diff --git a/Source/cmFileLockResult.h b/Source/cmFileLockResult.h
index d5ac354..679432a 100644
--- a/Source/cmFileLockResult.h
+++ b/Source/cmFileLockResult.h
@@ -1,19 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFileLockResult_h
 #define cmFileLockResult_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
 
 #if defined(_WIN32)
 #include <windows.h> // DWORD
diff --git a/Source/cmFileLockUnix.cxx b/Source/cmFileLockUnix.cxx
index 6be6abc..7353b01 100644
--- a/Source/cmFileLockUnix.cxx
+++ b/Source/cmFileLockUnix.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileLock.h"
 
 #include "cmSystemTools.h"
@@ -37,9 +27,8 @@ cmFileLockResult cmFileLock::Release()
 
   if (lockResult == 0) {
     return cmFileLockResult::MakeOk();
-  } else {
-    return cmFileLockResult::MakeSystem();
   }
+  return cmFileLockResult::MakeSystem();
 }
 
 cmFileLockResult cmFileLock::OpenFile()
@@ -47,18 +36,16 @@ cmFileLockResult cmFileLock::OpenFile()
   this->File = ::open(this->Filename.c_str(), O_RDWR);
   if (this->File == -1) {
     return cmFileLockResult::MakeSystem();
-  } else {
-    return cmFileLockResult::MakeOk();
   }
+  return cmFileLockResult::MakeOk();
 }
 
 cmFileLockResult cmFileLock::LockWithoutTimeout()
 {
   if (this->LockFile(F_SETLKW, F_WRLCK) == -1) {
     return cmFileLockResult::MakeSystem();
-  } else {
-    return cmFileLockResult::MakeOk();
   }
+  return cmFileLockResult::MakeOk();
 }
 
 cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
diff --git a/Source/cmFileLockWin32.cxx b/Source/cmFileLockWin32.cxx
index 0ba1e9a..51ac249 100644
--- a/Source/cmFileLockWin32.cxx
+++ b/Source/cmFileLockWin32.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Ruslan Baratov
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileLock.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmFileMonitor.cxx b/Source/cmFileMonitor.cxx
new file mode 100644
index 0000000..41ec8b4
--- /dev/null
+++ b/Source/cmFileMonitor.cxx
@@ -0,0 +1,389 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmFileMonitor.h"
+
+#include <cmsys/SystemTools.hxx>
+
+#include <cassert>
+#include <iostream>
+#include <set>
+#include <unordered_map>
+
+namespace {
+void on_directory_change(uv_fs_event_t* handle, const char* filename,
+                         int events, int status);
+void on_fs_close(uv_handle_t* handle);
+} // namespace
+
+class cmIBaseWatcher
+{
+public:
+  cmIBaseWatcher() = default;
+  virtual ~cmIBaseWatcher() = default;
+
+  virtual void Trigger(const std::string& pathSegment, int events,
+                       int status) const = 0;
+  virtual std::string Path() const = 0;
+  virtual uv_loop_t* Loop() const = 0;
+
+  virtual void StartWatching() = 0;
+  virtual void StopWatching() = 0;
+
+  virtual std::vector<std::string> WatchedFiles() const = 0;
+  virtual std::vector<std::string> WatchedDirectories() const = 0;
+};
+
+class cmVirtualDirectoryWatcher : public cmIBaseWatcher
+{
+public:
+  ~cmVirtualDirectoryWatcher()
+  {
+    for (auto i : this->Children) {
+      delete i.second;
+    }
+  }
+
+  cmIBaseWatcher* Find(const std::string& ps)
+  {
+    const auto i = this->Children.find(ps);
+    return (i == this->Children.end()) ? nullptr : i->second;
+  }
+
+  void Trigger(const std::string& pathSegment, int events,
+               int status) const final
+  {
+    if (pathSegment.empty()) {
+      for (const auto& i : this->Children) {
+        i.second->Trigger(std::string(), events, status);
+      }
+    } else {
+      const auto i = this->Children.find(pathSegment);
+      if (i != this->Children.end()) {
+        i->second->Trigger(std::string(), events, status);
+      }
+    }
+  }
+
+  void StartWatching() override
+  {
+    for (const auto& i : this->Children) {
+      i.second->StartWatching();
+    }
+  }
+
+  void StopWatching() override
+  {
+    for (const auto& i : this->Children) {
+      i.second->StopWatching();
+    }
+  }
+
+  std::vector<std::string> WatchedFiles() const final
+  {
+    std::vector<std::string> result;
+    for (const auto& i : this->Children) {
+      for (const auto& j : i.second->WatchedFiles()) {
+        result.push_back(j);
+      }
+    }
+    return result;
+  }
+
+  std::vector<std::string> WatchedDirectories() const override
+  {
+    std::vector<std::string> result;
+    for (const auto& i : this->Children) {
+      for (const auto& j : i.second->WatchedDirectories()) {
+        result.push_back(j);
+      }
+    }
+    return result;
+  }
+
+  void Reset()
+  {
+    for (auto c : this->Children) {
+      delete c.second;
+    }
+    this->Children.clear();
+  }
+
+  void AddChildWatcher(const std::string& ps, cmIBaseWatcher* watcher)
+  {
+    assert(!ps.empty());
+    assert(this->Children.find(ps) == this->Children.end());
+    assert(watcher);
+
+    this->Children.emplace(std::make_pair(ps, watcher));
+  }
+
+private:
+  std::unordered_map<std::string, cmIBaseWatcher*> Children; // owned!
+};
+
+// Root of all the different (on windows!) root directories:
+class cmRootWatcher : public cmVirtualDirectoryWatcher
+{
+public:
+  cmRootWatcher(uv_loop_t* loop)
+    : mLoop(loop)
+  {
+    assert(loop);
+  }
+
+  std::string Path() const final
+  {
+    assert(false);
+    return std::string();
+  }
+  uv_loop_t* Loop() const final { return this->mLoop; }
+
+private:
+  uv_loop_t* const mLoop; // no ownership!
+};
+
+// Real directories:
+class cmRealDirectoryWatcher : public cmVirtualDirectoryWatcher
+{
+public:
+  cmRealDirectoryWatcher(cmVirtualDirectoryWatcher* p, const std::string& ps)
+    : Parent(p)
+    , PathSegment(ps)
+  {
+    assert(p);
+    assert(!ps.empty());
+
+    p->AddChildWatcher(ps, this);
+  }
+
+  ~cmRealDirectoryWatcher()
+  {
+    // Handle is freed via uv_handle_close callback!
+  }
+
+  void StartWatching() final
+  {
+    if (!this->Handle) {
+      this->Handle = new uv_fs_event_t;
+
+      uv_fs_event_init(this->Loop(), this->Handle);
+      this->Handle->data = this;
+      uv_fs_event_start(this->Handle, &on_directory_change, Path().c_str(), 0);
+    }
+    cmVirtualDirectoryWatcher::StartWatching();
+  }
+
+  void StopWatching() final
+  {
+    if (this->Handle) {
+      uv_fs_event_stop(this->Handle);
+      uv_close(reinterpret_cast<uv_handle_t*>(this->Handle), &on_fs_close);
+      this->Handle = nullptr;
+    }
+    cmVirtualDirectoryWatcher::StopWatching();
+  }
+
+  uv_loop_t* Loop() const final { return this->Parent->Loop(); }
+
+  std::vector<std::string> WatchedDirectories() const override
+  {
+    std::vector<std::string> result = { Path() };
+    for (const auto& j : cmVirtualDirectoryWatcher::WatchedDirectories()) {
+      result.push_back(j);
+    }
+    return result;
+  }
+
+protected:
+  cmVirtualDirectoryWatcher* const Parent;
+  const std::string PathSegment;
+
+private:
+  uv_fs_event_t* Handle = nullptr; // owner!
+};
+
+// Root directories:
+class cmRootDirectoryWatcher : public cmRealDirectoryWatcher
+{
+public:
+  cmRootDirectoryWatcher(cmRootWatcher* p, const std::string& ps)
+    : cmRealDirectoryWatcher(p, ps)
+  {
+  }
+
+  std::string Path() const final { return this->PathSegment; }
+};
+
+// Normal directories below root:
+class cmDirectoryWatcher : public cmRealDirectoryWatcher
+{
+public:
+  cmDirectoryWatcher(cmRealDirectoryWatcher* p, const std::string& ps)
+    : cmRealDirectoryWatcher(p, ps)
+  {
+  }
+
+  std::string Path() const final
+  {
+    return this->Parent->Path() + this->PathSegment + "/";
+  }
+};
+
+class cmFileWatcher : public cmIBaseWatcher
+{
+public:
+  cmFileWatcher(cmRealDirectoryWatcher* p, const std::string& ps,
+                cmFileMonitor::Callback cb)
+    : Parent(p)
+    , PathSegment(ps)
+    , CbList({ cb })
+  {
+    assert(p);
+    assert(!ps.empty());
+    p->AddChildWatcher(ps, this);
+  }
+
+  void StartWatching() final {}
+
+  void StopWatching() final {}
+
+  void AppendCallback(cmFileMonitor::Callback cb) { CbList.push_back(cb); }
+
+  std::string Path() const final
+  {
+    return this->Parent->Path() + this->PathSegment;
+  }
+
+  std::vector<std::string> WatchedDirectories() const final { return {}; }
+
+  std::vector<std::string> WatchedFiles() const final
+  {
+    return { this->Path() };
+  }
+
+  void Trigger(const std::string& ps, int events, int status) const final
+  {
+    assert(ps.empty());
+    assert(status == 0);
+    static_cast<void>(ps);
+
+    const std::string path = this->Path();
+    for (const auto& cb : this->CbList) {
+      cb(path, events, status);
+    }
+  }
+
+  uv_loop_t* Loop() const final { return this->Parent->Loop(); }
+
+private:
+  cmRealDirectoryWatcher* Parent;
+  const std::string PathSegment;
+  std::vector<cmFileMonitor::Callback> CbList;
+};
+
+namespace {
+
+void on_directory_change(uv_fs_event_t* handle, const char* filename,
+                         int events, int status)
+{
+  const cmIBaseWatcher* const watcher =
+    static_cast<const cmIBaseWatcher*>(handle->data);
+  const std::string pathSegment(filename);
+  watcher->Trigger(pathSegment, events, status);
+}
+
+void on_fs_close(uv_handle_t* handle)
+{
+  delete reinterpret_cast<uv_fs_event_t*>(handle);
+}
+
+} // namespace
+
+cmFileMonitor::cmFileMonitor(uv_loop_t* l)
+  : Root(new cmRootWatcher(l))
+{
+}
+
+cmFileMonitor::~cmFileMonitor()
+{
+  delete this->Root;
+}
+
+void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths,
+                                 Callback cb)
+{
+  for (const auto& p : paths) {
+    std::vector<std::string> pathSegments;
+    cmsys::SystemTools::SplitPath(p, pathSegments, true);
+
+    const size_t segmentCount = pathSegments.size();
+    if (segmentCount < 2) { // Expect at least rootdir and filename
+      continue;
+    }
+    cmVirtualDirectoryWatcher* currentWatcher = this->Root;
+    for (size_t i = 0; i < segmentCount; ++i) {
+      assert(currentWatcher);
+
+      const bool fileSegment = (i == segmentCount - 1);
+      const bool rootSegment = (i == 0);
+      assert(
+        !(fileSegment &&
+          rootSegment)); // Can not be both filename and root part of the path!
+
+      const std::string& currentSegment = pathSegments[i];
+
+      cmIBaseWatcher* nextWatcher = currentWatcher->Find(currentSegment);
+      if (!nextWatcher) {
+        if (rootSegment) { // Root part
+          assert(currentWatcher == this->Root);
+          nextWatcher = new cmRootDirectoryWatcher(this->Root, currentSegment);
+          assert(currentWatcher->Find(currentSegment) == nextWatcher);
+        } else if (fileSegment) { // File part
+          assert(currentWatcher != this->Root);
+          nextWatcher = new cmFileWatcher(
+            dynamic_cast<cmRealDirectoryWatcher*>(currentWatcher),
+            currentSegment, cb);
+          assert(currentWatcher->Find(currentSegment) == nextWatcher);
+        } else { // Any normal directory in between
+          nextWatcher = new cmDirectoryWatcher(
+            dynamic_cast<cmRealDirectoryWatcher*>(currentWatcher),
+            currentSegment);
+          assert(currentWatcher->Find(currentSegment) == nextWatcher);
+        }
+      } else {
+        if (fileSegment) {
+          auto filePtr = dynamic_cast<cmFileWatcher*>(nextWatcher);
+          assert(filePtr);
+          filePtr->AppendCallback(cb);
+          continue;
+        }
+      }
+      currentWatcher = dynamic_cast<cmVirtualDirectoryWatcher*>(nextWatcher);
+    }
+  }
+  this->Root->StartWatching();
+}
+
+void cmFileMonitor::StopMonitoring()
+{
+  this->Root->StopWatching();
+  this->Root->Reset();
+}
+
+std::vector<std::string> cmFileMonitor::WatchedFiles() const
+{
+  std::vector<std::string> result;
+  if (this->Root) {
+    result = this->Root->WatchedFiles();
+  }
+  return result;
+}
+
+std::vector<std::string> cmFileMonitor::WatchedDirectories() const
+{
+  std::vector<std::string> result;
+  if (this->Root) {
+    result = this->Root->WatchedDirectories();
+  }
+  return result;
+}
diff --git a/Source/cmFileMonitor.h b/Source/cmFileMonitor.h
new file mode 100644
index 0000000..e05f48d
--- /dev/null
+++ b/Source/cmFileMonitor.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 <functional>
+#include <string>
+#include <vector>
+
+#include "cm_uv.h"
+
+class cmRootWatcher;
+
+class cmFileMonitor
+{
+public:
+  cmFileMonitor(uv_loop_t* l);
+  ~cmFileMonitor();
+
+  using Callback = std::function<void(const std::string&, int, int)>;
+  void MonitorPaths(const std::vector<std::string>& paths, Callback cb);
+  void StopMonitoring();
+
+  std::vector<std::string> WatchedFiles() const;
+  std::vector<std::string> WatchedDirectories() const;
+
+private:
+  cmRootWatcher* Root;
+};
diff --git a/Source/cmFilePathUuid.cxx b/Source/cmFilePathUuid.cxx
new file mode 100644
index 0000000..ad434e3
--- /dev/null
+++ b/Source/cmFilePathUuid.cxx
@@ -0,0 +1,118 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmFilePathUuid.h"
+
+#include "cmBase32.h"
+#include "cmCryptoHash.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include <vector>
+
+cmFilePathUuid::cmFilePathUuid(cmMakefile* makefile)
+{
+  initParentDirs(makefile->GetCurrentSourceDirectory(),
+                 makefile->GetCurrentBinaryDirectory(),
+                 makefile->GetHomeDirectory(),
+                 makefile->GetHomeOutputDirectory());
+}
+
+cmFilePathUuid::cmFilePathUuid(const std::string& currentSrcDir,
+                               const std::string& currentBinDir,
+                               const std::string& projectSrcDir,
+                               const std::string& projectBinDir)
+{
+  initParentDirs(currentSrcDir, currentBinDir, projectSrcDir, projectBinDir);
+}
+
+void cmFilePathUuid::initParentDirs(const std::string& currentSrcDir,
+                                    const std::string& currentBinDir,
+                                    const std::string& projectSrcDir,
+                                    const std::string& projectBinDir)
+{
+  parentDirs[0].first = cmsys::SystemTools::GetRealPath(currentSrcDir);
+  parentDirs[1].first = cmsys::SystemTools::GetRealPath(currentBinDir);
+  parentDirs[2].first = cmsys::SystemTools::GetRealPath(projectSrcDir);
+  parentDirs[3].first = cmsys::SystemTools::GetRealPath(projectBinDir);
+
+  parentDirs[0].second = "CurrentSource";
+  parentDirs[1].second = "CurrentBinary";
+  parentDirs[2].second = "ProjectSource";
+  parentDirs[3].second = "ProjectBinary";
+}
+
+std::string cmFilePathUuid::get(const std::string& filePath,
+                                const char* outputPrefix,
+                                const char* outputSuffix)
+{
+  std::string sourceFilename = cmsys::SystemTools::GetFilenameName(filePath);
+  std::string sourceBasename =
+    cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFilename);
+
+  // Acquire checksum string
+  std::string checksum;
+  {
+    std::string sourceRelPath;
+    std::string sourceRelSeed;
+    GetRelPathSeed(filePath, sourceRelPath, sourceRelSeed);
+    checksum = GetChecksumString(sourceFilename, sourceRelPath, sourceRelSeed);
+  }
+
+  // Compose the file name
+  std::string uuid;
+  if (outputPrefix) {
+    uuid += outputPrefix;
+  }
+  uuid += sourceBasename.substr(0, partLengthName);
+  uuid += "_";
+  uuid += checksum.substr(0, partLengthCheckSum);
+  if (outputSuffix) {
+    uuid += outputSuffix;
+  }
+  return uuid;
+}
+
+void cmFilePathUuid::GetRelPathSeed(const std::string& filePath,
+                                    std::string& sourceRelPath,
+                                    std::string& sourceRelSeed)
+{
+  const std::string sourceNameReal = cmsys::SystemTools::GetRealPath(filePath);
+  std::string parentDirectory;
+  // Find closest project parent directory
+  for (size_t ii = 0; ii != numParentDirs; ++ii) {
+    const std::string& pDir = parentDirs[ii].first;
+    if (!pDir.empty() &&
+        cmsys::SystemTools::IsSubDirectory(sourceNameReal, pDir)) {
+      sourceRelSeed = parentDirs[ii].second;
+      parentDirectory = pDir;
+      break;
+    }
+  }
+  // Check if the file path is below a known project directory
+  if (parentDirectory.empty()) {
+    // Use file syste root as fallback parent directory
+    sourceRelSeed = "FileSystemRoot";
+    cmsys::SystemTools::SplitPathRootComponent(sourceNameReal,
+                                               &parentDirectory);
+  }
+  sourceRelPath = cmsys::SystemTools::RelativePath(
+    parentDirectory, cmsys::SystemTools::GetParentDirectory(sourceNameReal));
+}
+
+std::string cmFilePathUuid::GetChecksumString(
+  const std::string& sourceFilename, const std::string& sourceRelPath,
+  const std::string& sourceRelSeed)
+{
+  std::string checksumBase32;
+  {
+    // Calculate the file ( seed + relative path + name ) checksum
+    std::vector<unsigned char> hashBytes =
+      cmCryptoHash::New("SHA256")->ByteHashString(
+        sourceRelSeed + sourceRelPath + sourceFilename);
+
+    checksumBase32 =
+      cmBase32Encoder().encodeString(&hashBytes[0], hashBytes.size(), false);
+  }
+
+  return checksumBase32;
+}
diff --git a/Source/cmFilePathUuid.h b/Source/cmFilePathUuid.h
new file mode 100644
index 0000000..a450526
--- /dev/null
+++ b/Source/cmFilePathUuid.h
@@ -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.  */
+#ifndef cmFilePathUuid_h
+#define cmFilePathUuid_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <stddef.h>
+#include <string>
+#include <utility>
+
+class cmMakefile;
+
+/** \class cmFilePathUuid
+ * @brief Generates a unique pathless file name with a checksum component
+ *        calculated from the file path.
+ *
+ * The checksum is calculated from the relative file path to the
+ * closest known project directory. This guarantees reproducibility
+ * when source and build directory differ e.g. for different project
+ * build directories.
+ */
+class cmFilePathUuid
+{
+public:
+  /// Maximum number of characters to use from the file name
+  static const size_t partLengthName = 14;
+  /// Maximum number of characters to use from the path checksum
+  static const size_t partLengthCheckSum = 14;
+
+  /// @brief Initilizes the parent directories from a makefile
+  cmFilePathUuid(cmMakefile* makefile);
+
+  /// @brief Initilizes the parent directories manually
+  cmFilePathUuid(const std::string& currentSrcDir,
+                 const std::string& currentBinDir,
+                 const std::string& projectSrcDir,
+                 const std::string& projectBinDir);
+
+  /* @brief Calculates and returns the uuid for a file path
+   *
+   * @arg outputPrefix optional string to prepend to the result
+   * @arg outputSuffix optional string to append to the result
+   */
+  std::string get(const std::string& filePath,
+                  const char* outputPrefix = CM_NULLPTR,
+                  const char* outputSuffix = CM_NULLPTR);
+
+private:
+  void initParentDirs(const std::string& currentSrcDir,
+                      const std::string& currentBinDir,
+                      const std::string& projectSrcDir,
+                      const std::string& projectBinDir);
+
+  /// Returns the relative path and the parent directory key string (seed)
+  void GetRelPathSeed(const std::string& filePath, std::string& sourceRelPath,
+                      std::string& sourceRelSeed);
+
+  std::string GetChecksumString(const std::string& sourceFilename,
+                                const std::string& sourceRelPath,
+                                const std::string& sourceRelSeed);
+
+  /// Size of the parent directory list
+  static const size_t numParentDirs = 4;
+  /// List of (directory name, seed name) pairs
+  std::pair<std::string, std::string> parentDirs[numParentDirs];
+};
+
+#endif
diff --git a/Source/cmFileTimeComparison.cxx b/Source/cmFileTimeComparison.cxx
index 7efe194..a6c9cd0 100644
--- a/Source/cmFileTimeComparison.cxx
+++ b/Source/cmFileTimeComparison.cxx
@@ -1,35 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileTimeComparison.h"
 
+#include <cmConfigure.h>
+#include <string>
+#include <time.h>
+#include <utility>
+
 // Use a hash table to avoid duplicate file time checks from disk.
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 #include <unordered_map>
 #else
 #include <cmsys/hash_map.hxx>
 #endif
 #endif
 
-#include <cmsys/Encoding.hxx>
-
 // Use a platform-specific API to get file times efficiently.
 #if !defined(_WIN32) || defined(__CYGWIN__)
-#define cmFileTimeComparison_Type struct stat
-#include <ctype.h>
 #include <sys/stat.h>
+#define cmFileTimeComparison_Type struct stat
 #else
-#define cmFileTimeComparison_Type FILETIME
+#include <cmsys/Encoding.hxx>
 #include <windows.h>
+#define cmFileTimeComparison_Type FILETIME
 #endif
 
 class cmFileTimeComparisonInternal
@@ -47,13 +41,13 @@ private:
   {
   public:
     size_t operator()(const std::string& s) const { return h(s.c_str()); }
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
     std::hash<const char*> h;
 #else
     cmsys::hash<const char*> h;
 #endif
   };
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
   typedef std::unordered_map<std::string,
 #else
   typedef cmsys::hash_map<std::string,
@@ -140,11 +134,14 @@ int cmFileTimeComparisonInternal::Compare(cmFileTimeComparison_Type* s1,
   // Compare using nanosecond resolution.
   if (s1->st_mtim.tv_sec < s2->st_mtim.tv_sec) {
     return -1;
-  } else if (s1->st_mtim.tv_sec > s2->st_mtim.tv_sec) {
+  }
+  if (s1->st_mtim.tv_sec > s2->st_mtim.tv_sec) {
     return 1;
-  } else if (s1->st_mtim.tv_nsec < s2->st_mtim.tv_nsec) {
+  }
+  if (s1->st_mtim.tv_nsec < s2->st_mtim.tv_nsec) {
     return -1;
-  } else if (s1->st_mtim.tv_nsec > s2->st_mtim.tv_nsec) {
+  }
+  if (s1->st_mtim.tv_nsec > s2->st_mtim.tv_nsec) {
     return 1;
   }
 #elif CMake_STAT_HAS_ST_MTIMESPEC
@@ -185,11 +182,11 @@ bool cmFileTimeComparisonInternal::TimesDiffer(cmFileTimeComparison_Type* s1,
   long long t2 = s2->st_mtim.tv_sec * bil + s2->st_mtim.tv_nsec;
   if (t1 < t2) {
     return (t2 - t1) >= bil;
-  } else if (t2 < t1) {
+  }
+  if (t2 < t1) {
     return (t1 - t2) >= bil;
-  } else {
-    return false;
   }
+  return false;
 #elif CMake_STAT_HAS_ST_MTIMESPEC
   // Times are integers in units of 1ns.
   long long bil = 1000000000;
@@ -240,11 +237,10 @@ bool cmFileTimeComparisonInternal::FileTimeCompare(const char* f1,
     // Compare the two modification times.
     *result = this->Compare(&s1, &s2);
     return true;
-  } else {
-    // No comparison available.  Default to the same time.
-    *result = 0;
-    return false;
   }
+  // No comparison available.  Default to the same time.
+  *result = 0;
+  return false;
 }
 
 bool cmFileTimeComparisonInternal::FileTimesDiffer(const char* f1,
@@ -256,8 +252,7 @@ bool cmFileTimeComparisonInternal::FileTimesDiffer(const char* f1,
   if (this->Stat(f1, &s1) && this->Stat(f2, &s2)) {
     // Compare the two modification times.
     return this->TimesDiffer(&s1, &s2);
-  } else {
-    // No comparison available.  Default to different times.
-    return true;
   }
+  // No comparison available.  Default to different times.
+  return true;
 }
diff --git a/Source/cmFileTimeComparison.h b/Source/cmFileTimeComparison.h
index 409bd64..6eb1500 100644
--- a/Source/cmFileTimeComparison.h
+++ b/Source/cmFileTimeComparison.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFileTimeComparison_h
 #define cmFileTimeComparison_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 class cmFileTimeComparisonInternal;
 
diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx
index c785e6c..982d740 100644
--- a/Source/cmFindBase.cxx
+++ b/Source/cmFindBase.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindBase.h"
 
 #include "cmAlgorithms.h"
@@ -321,7 +312,8 @@ bool cmFindBase::CheckForVariableInCache()
         this->AlreadyInCacheWithoutMetaInfo = true;
       }
       return true;
-    } else if (cached) {
+    }
+    if (cached) {
       const char* hs =
         state->GetCacheEntryProperty(this->VariableName, "HELPSTRING");
       this->VariableDocumentation = hs ? hs : "(none)";
diff --git a/Source/cmFindBase.h b/Source/cmFindBase.h
index 054c33b..8561f5d 100644
--- a/Source/cmFindBase.h
+++ b/Source/cmFindBase.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindBase_h
 #define cmFindBase_h
 
diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx
index 638c1d1..bd5298d 100644
--- a/Source/cmFindCommon.cxx
+++ b/Source/cmFindCommon.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindCommon.h"
 
 #include <algorithm>
@@ -234,13 +225,13 @@ void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore)
 {
   // null-terminated list of paths.
   static const char* paths[] = { "CMAKE_SYSTEM_IGNORE_PATH",
-                                 "CMAKE_IGNORE_PATH", 0 };
+                                 "CMAKE_IGNORE_PATH", CM_NULLPTR };
 
   // Construct the list of path roots with no trailing slashes.
   for (const char** pathName = paths; *pathName; ++pathName) {
     // Get the list of paths to ignore from the variable.
     const char* ignorePath = this->Makefile->GetDefinition(*pathName);
-    if ((ignorePath == 0) || (strlen(ignorePath) == 0)) {
+    if ((ignorePath == CM_NULLPTR) || (strlen(ignorePath) == 0)) {
       continue;
     }
 
diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h
index ebec884..3211bc2 100644
--- a/Source/cmFindCommon.h
+++ b/Source/cmFindCommon.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindCommon_h
 #define cmFindCommon_h
 
@@ -27,7 +18,7 @@ class cmFindCommon : public cmCommand
 {
 public:
   cmFindCommon();
-  ~cmFindCommon();
+  ~cmFindCommon() CM_OVERRIDE;
   cmTypeMacro(cmFindCommon, cmCommand);
 
 protected:
diff --git a/Source/cmFindFileCommand.cxx b/Source/cmFindFileCommand.cxx
index a6666ba..9c66cd2 100644
--- a/Source/cmFindFileCommand.cxx
+++ b/Source/cmFindFileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindFileCommand.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h
index 74b01f1..feb6ad2 100644
--- a/Source/cmFindFileCommand.h
+++ b/Source/cmFindFileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindFileCommand_h
 #define cmFindFileCommand_h
 
@@ -29,8 +20,8 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFindFileCommand; }
-  virtual std::string GetName() const { return "find_file"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFindFileCommand; }
+  std::string GetName() const CM_OVERRIDE { return "find_file"; }
 
   cmTypeMacro(cmFindFileCommand, cmFindPathCommand);
 };
diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx
index a4d4dbb..082350f 100644
--- a/Source/cmFindLibraryCommand.cxx
+++ b/Source/cmFindLibraryCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindLibraryCommand.h"
 
 #include <cmsys/Directory.hxx>
@@ -40,11 +31,10 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn,
     return true;
   }
 
-  if (const char* abi_name =
-        this->Makefile->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
-    std::string abi = abi_name;
-    if (abi.find("ELF N32") != abi.npos) {
-      // Convert lib to lib32.
+  if (this->Makefile->GetState()->GetGlobalPropertyAsBool(
+        "FIND_LIBRARY_USE_LIB32_PATHS")) {
+    // add special 32 bit paths if this is a 32 bit compile.
+    if (this->Makefile->PlatformIs32Bit()) {
       this->AddArchitecturePaths("32");
     }
   }
@@ -379,9 +369,8 @@ std::string cmFindLibraryCommand::FindNormalLibrary()
 {
   if (this->NamesPerDir) {
     return this->FindNormalLibraryNamesPerDir();
-  } else {
-    return this->FindNormalLibraryDirsPerName();
   }
+  return this->FindNormalLibraryDirsPerName();
 }
 
 std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
@@ -429,9 +418,8 @@ std::string cmFindLibraryCommand::FindFrameworkLibrary()
 {
   if (this->NamesPerDir) {
     return this->FindFrameworkLibraryNamesPerDir();
-  } else {
-    return this->FindFrameworkLibraryDirsPerName();
   }
+  return this->FindFrameworkLibraryDirsPerName();
 }
 
 std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h
index a08e151..39393f6 100644
--- a/Source/cmFindLibraryCommand.h
+++ b/Source/cmFindLibraryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindLibraryCommand_h
 #define cmFindLibraryCommand_h
 
@@ -28,24 +19,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFindLibraryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFindLibraryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "find_library"; }
+  std::string GetName() const CM_OVERRIDE { return "find_library"; }
 
   cmTypeMacro(cmFindLibraryCommand, cmFindBase);
 
diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx
index 7908afe..554618e 100644
--- a/Source/cmFindPackageCommand.cxx
+++ b/Source/cmFindPackageCommand.cxx
@@ -1,17 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindPackageCommand.h"
 
 #include "cmAlgorithms.h"
+#include <cmSystemTools.h>
 #include <cmsys/Directory.hxx>
 #include <cmsys/Encoding.hxx>
 #include <cmsys/RegularExpression.hxx>
@@ -33,6 +25,45 @@ cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
 cmFindPackageCommand::PathLabel
   cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
 
+struct StrverscmpGreater
+{
+  bool operator()(const std::string& lhs, const std::string& rhs) const
+  {
+    return cmSystemTools::strverscmp(lhs, rhs) > 0;
+  }
+};
+
+struct StrverscmpLesser
+{
+  bool operator()(const std::string& lhs, const std::string& rhs) const
+  {
+    return cmSystemTools::strverscmp(lhs, rhs) < 0;
+  }
+};
+
+void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
+                                std::vector<std::string>::iterator end,
+                                SortOrderType order, SortDirectionType dir)
+{
+  if (order == Name_order) {
+    if (dir == Dec) {
+      std::sort(begin, end, std::greater<std::string>());
+    } else {
+      std::sort(begin, end);
+    }
+  } else if (order == Natural)
+  // natural order uses letters and numbers (contiguous numbers digit are
+  // compared such that e.g. 000  00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
+  {
+    if (dir == Dec) {
+      std::sort(begin, end, StrverscmpGreater());
+    } else {
+      std::sort(begin, end, StrverscmpLesser());
+    }
+  }
+  // else do not sort
+}
+
 cmFindPackageCommand::cmFindPackageCommand()
 {
   this->CMakePathName = "PACKAGE";
@@ -43,6 +74,7 @@ cmFindPackageCommand::cmFindPackageCommand()
   this->UseConfigFiles = true;
   this->UseFindModules = true;
   this->DebugMode = false;
+  this->UseLib32Paths = false;
   this->UseLib64Paths = false;
   this->PolicyScope = true;
   this->VersionMajor = 0;
@@ -57,7 +89,8 @@ cmFindPackageCommand::cmFindPackageCommand()
   this->VersionFoundTweak = 0;
   this->VersionFoundCount = 0;
   this->RequiredCMakeVersion = 0;
-
+  this->SortOrder = None;
+  this->SortDirection = Asc;
   this->AppendSearchPathGroups();
 }
 
@@ -88,7 +121,7 @@ void cmFindPackageCommand::AppendSearchPathGroups()
 bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -110,6 +143,13 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
     this->LibraryArchitecture = arch;
   }
 
+  // Lookup whether lib32 paths should be used.
+  if (this->Makefile->PlatformIs32Bit() &&
+      this->Makefile->GetState()->GetGlobalPropertyAsBool(
+        "FIND_LIBRARY_USE_LIB32_PATHS")) {
+    this->UseLib32Paths = true;
+  }
+
   // Lookup whether lib64 paths should be used.
   if (this->Makefile->PlatformIs64Bit() &&
       this->Makefile->GetState()->GetGlobalPropertyAsBool(
@@ -127,6 +167,23 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
     this->NoSystemRegistry = true;
   }
 
+  // Check if Sorting should be enabled
+  if (const char* so =
+        this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
+
+    if (strcmp(so, "NAME") == 0) {
+      this->SortOrder = Name_order;
+    } else if (strcmp(so, "NATURAL") == 0) {
+      this->SortOrder = Natural;
+    } else {
+      this->SortOrder = None;
+    }
+  }
+  if (const char* sd =
+        this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
+    this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
+  }
+
   // Find the current root path mode.
   this->SelectDefaultRootPathMode();
 
@@ -664,16 +721,18 @@ bool cmFindPackageCommand::HandlePackageMode()
     // If there are files in ConsideredConfigs, it means that FooConfig.cmake
     // have been found, but they didn't have appropriate versions.
     else if (!this->ConsideredConfigs.empty()) {
+      std::vector<ConfigFileInfo>::const_iterator duplicate_end =
+        cmRemoveDuplicates(this->ConsideredConfigs);
       e << "Could not find a configuration file for package \"" << this->Name
         << "\" that "
         << (this->VersionExact ? "exactly matches" : "is compatible with")
         << " requested version \"" << this->Version << "\".\n"
         << "The following configuration files were considered but not "
            "accepted:\n";
-      for (std::vector<ConfigFileInfo>::size_type i = 0;
-           i < this->ConsideredConfigs.size(); i++) {
-        e << "  " << this->ConsideredConfigs[i].filename
-          << ", version: " << this->ConsideredConfigs[i].version << "\n";
+      for (std::vector<ConfigFileInfo>::const_iterator i =
+             this->ConsideredConfigs.begin();
+           i != duplicate_end; ++i) {
+        e << "  " << i->filename << ", version: " << i->version << "\n";
       }
     } else {
       std::string requestedVersionString;
@@ -766,12 +825,13 @@ bool cmFindPackageCommand::HandlePackageMode()
   std::string consideredVersions;
 
   const char* sep = "";
-  for (std::vector<ConfigFileInfo>::size_type i = 0;
-       i < this->ConsideredConfigs.size(); i++) {
+  for (std::vector<ConfigFileInfo>::const_iterator i =
+         this->ConsideredConfigs.begin();
+       i != this->ConsideredConfigs.end(); ++i) {
     consideredConfigFiles += sep;
     consideredVersions += sep;
-    consideredConfigFiles += this->ConsideredConfigs[i].filename;
-    consideredVersions += this->ConsideredConfigs[i].version;
+    consideredConfigFiles += i->filename;
+    consideredVersions += i->version;
     sep = ";";
   }
 
@@ -1066,8 +1126,8 @@ void cmFindPackageCommand::FillPrefixesUserRegistry()
                                  this->LabeledPaths[PathLabel::UserRegistry]);
   }
 #else
-  if (const char* home = cmSystemTools::GetEnv("HOME")) {
-    std::string dir = home;
+  std::string dir;
+  if (cmSystemTools::GetEnv("HOME", dir)) {
     dir += "/.cmake/packages/";
     dir += this->Name;
     this->LoadPackageRegistryDir(dir,
@@ -1188,7 +1248,7 @@ public:
       cmSystemTools::RemoveFile(this->File);
     }
   }
-  void Release() { this->File = 0; }
+  void Release() { this->File = CM_NULLPTR; }
 };
 
 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
@@ -1239,18 +1299,16 @@ bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
         outPaths.AddPath(fname);
       }
       return true;
-    } else {
-      // The path does not exist.  Assume the stream content is
-      // associated with an old package that no longer exists, and
-      // delete it to keep the package registry clean.
-      return false;
     }
-  } else {
-    // The first line in the stream is not the full path to a file or
-    // directory.  Assume the stream content was created by a future
-    // version of CMake that uses a different format, and leave it.
-    return true;
+    // The path does not exist.  Assume the stream content is
+    // associated with an old package that no longer exists, and
+    // delete it to keep the package registry clean.
+    return false;
   }
+  // The first line in the stream is not the full path to a file or
+  // directory.  Assume the stream content was created by a future
+  // version of CMake that uses a different format, and leave it.
+  return true;
 }
 
 void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
@@ -1489,9 +1547,9 @@ void cmFindPackageCommand::StoreVersionFound()
   this->Makefile->AddDefinition(ver + "_COUNT", buf);
 }
 
+#include <cm_auto_ptr.hxx>
 #include <cmsys/Glob.hxx>
 #include <cmsys/String.h>
-#include <cmsys/auto_ptr.hxx>
 
 class cmFileList;
 class cmFileListGeneratorBase
@@ -1504,10 +1562,10 @@ protected:
 private:
   bool Search(cmFileList&);
   virtual bool Search(std::string const& parent, cmFileList&) = 0;
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
+  virtual CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const = 0;
   friend class cmFileList;
   cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
-  cmsys::auto_ptr<cmFileListGeneratorBase> Next;
+  CM_AUTO_PTR<cmFileListGeneratorBase> Next;
 };
 
 class cmFileList
@@ -1515,7 +1573,7 @@ class cmFileList
 public:
   cmFileList()
     : First()
-    , Last(0)
+    , Last(CM_NULLPTR)
   {
   }
   virtual ~cmFileList() {}
@@ -1540,7 +1598,7 @@ public:
 private:
   virtual bool Visit(std::string const& fullPath) = 0;
   friend class cmFileListGeneratorBase;
-  cmsys::auto_ptr<cmFileListGeneratorBase> First;
+  CM_AUTO_PTR<cmFileListGeneratorBase> First;
   cmFileListGeneratorBase* Last;
 };
 
@@ -1555,13 +1613,12 @@ public:
   }
 
 private:
-  bool Visit(std::string const& fullPath)
+  bool Visit(std::string const& fullPath) CM_OVERRIDE
   {
     if (this->UseSuffixes) {
       return this->FPC->SearchDirectory(fullPath);
-    } else {
-      return this->FPC->CheckDirectory(fullPath);
     }
+    return this->FPC->CheckDirectory(fullPath);
   }
   cmFindPackageCommand* FPC;
   bool UseSuffixes;
@@ -1584,9 +1641,8 @@ bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
 {
   if (this->Next.get()) {
     return this->Next->Search(fullPath + "/", listing);
-  } else {
-    return listing.Visit(fullPath + "/");
   }
+  return listing.Visit(fullPath + "/");
 }
 
 class cmFileListGeneratorFixed : public cmFileListGeneratorBase
@@ -1605,14 +1661,14 @@ public:
 
 private:
   std::string String;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     std::string fullPath = parent + this->String;
     return this->Consider(fullPath, lister);
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(
       new cmFileListGeneratorFixed(*this));
     return g;
   }
@@ -1634,7 +1690,7 @@ public:
 
 private:
   std::vector<std::string> const& Vector;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     for (std::vector<std::string>::const_iterator i = this->Vector.begin();
          i != this->Vector.end(); ++i) {
@@ -1644,9 +1700,9 @@ private:
     }
     return false;
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(
       new cmFileListGeneratorEnumerate(*this));
     return g;
   }
@@ -1655,20 +1711,36 @@ private:
 class cmFileListGeneratorProject : public cmFileListGeneratorBase
 {
 public:
-  cmFileListGeneratorProject(std::vector<std::string> const& names)
+  cmFileListGeneratorProject(std::vector<std::string> const& names,
+                             cmFindPackageCommand::SortOrderType so,
+                             cmFindPackageCommand::SortDirectionType sd)
     : cmFileListGeneratorBase()
     , Names(names)
   {
+    this->SetSort(so, sd);
   }
   cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
     : cmFileListGeneratorBase()
     , Names(r.Names)
   {
+    this->SetSort(r.SortOrder, r.SortDirection);
   }
 
+  void SetSort(cmFindPackageCommand::SortOrderType o,
+               cmFindPackageCommand::SortDirectionType d)
+  {
+    SortOrder = o;
+    SortDirection = d;
+  }
+
+protected:
+  // sort parameters
+  cmFindPackageCommand::SortOrderType SortOrder;
+  cmFindPackageCommand::SortDirectionType SortDirection;
+
 private:
   std::vector<std::string> const& Names;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     // Construct a list of matches.
     std::vector<std::string> matches;
@@ -1687,6 +1759,13 @@ private:
       }
     }
 
+    // before testing the matches check if there is a specific sorting order to
+    // perform
+    if (this->SortOrder != cmFindPackageCommand::None) {
+      cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
+                                 SortDirection);
+    }
+
     for (std::vector<std::string>::const_iterator i = matches.begin();
          i != matches.end(); ++i) {
       if (this->Consider(parent + *i, lister)) {
@@ -1695,9 +1774,9 @@ private:
     }
     return false;
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(
       new cmFileListGeneratorProject(*this));
     return g;
   }
@@ -1723,7 +1802,7 @@ public:
 private:
   std::vector<std::string> const& Names;
   std::string Extension;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     // Construct a list of matches.
     std::vector<std::string> matches;
@@ -1752,9 +1831,9 @@ private:
     }
     return false;
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(
       new cmFileListGeneratorMacProject(*this));
     return g;
   }
@@ -1777,7 +1856,7 @@ public:
 
 private:
   std::string String;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     // Look for matching files.
     std::vector<std::string> matches;
@@ -1796,9 +1875,9 @@ private:
     }
     return false;
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(
       new cmFileListGeneratorCaseInsensitive(*this));
     return g;
   }
@@ -1820,7 +1899,7 @@ public:
 
 private:
   std::string Pattern;
-  virtual bool Search(std::string const& parent, cmFileList& lister)
+  bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
   {
     // Glob the set of matching files.
     std::string expr = parent;
@@ -1842,10 +1921,9 @@ private:
     }
     return false;
   }
-  virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
+  CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
   {
-    cmsys::auto_ptr<cmFileListGeneratorBase> g(
-      new cmFileListGeneratorGlob(*this));
+    CM_AUTO_PTR<cmFileListGeneratorBase> g(new cmFileListGeneratorGlob(*this));
     return g;
   }
 };
@@ -1885,7 +1963,8 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
   {
     cmFindPackageFileList lister(this);
     lister / cmFileListGeneratorFixed(prefix) /
-      cmFileListGeneratorProject(this->Names);
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection);
     if (lister.Search()) {
       return true;
     }
@@ -1895,7 +1974,8 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
   {
     cmFindPackageFileList lister(this);
     lister / cmFileListGeneratorFixed(prefix) /
-      cmFileListGeneratorProject(this->Names) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
       cmFileListGeneratorCaseInsensitive("cmake");
     if (lister.Search()) {
       return true;
@@ -1907,6 +1987,9 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
   if (!this->LibraryArchitecture.empty()) {
     common.push_back("lib/" + this->LibraryArchitecture);
   }
+  if (this->UseLib32Paths) {
+    common.push_back("lib32");
+  }
   if (this->UseLib64Paths) {
     common.push_back("lib64");
   }
@@ -1919,7 +2002,8 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
     lister / cmFileListGeneratorFixed(prefix) /
       cmFileListGeneratorEnumerate(common) /
       cmFileListGeneratorFixed("cmake") /
-      cmFileListGeneratorProject(this->Names);
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection);
     if (lister.Search()) {
       return true;
     }
@@ -1930,7 +2014,8 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
     cmFindPackageFileList lister(this);
     lister / cmFileListGeneratorFixed(prefix) /
       cmFileListGeneratorEnumerate(common) /
-      cmFileListGeneratorProject(this->Names);
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection);
     if (lister.Search()) {
       return true;
     }
@@ -1941,7 +2026,52 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
     cmFindPackageFileList lister(this);
     lister / cmFileListGeneratorFixed(prefix) /
       cmFileListGeneratorEnumerate(common) /
-      cmFileListGeneratorProject(this->Names) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
+      cmFileListGeneratorCaseInsensitive("cmake");
+    if (lister.Search()) {
+      return true;
+    }
+  }
+
+  // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/cmake/(Foo|foo|FOO).*/
+  {
+    cmFindPackageFileList lister(this);
+    lister / cmFileListGeneratorFixed(prefix) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
+      cmFileListGeneratorEnumerate(common) /
+      cmFileListGeneratorFixed("cmake") /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection);
+    if (lister.Search()) {
+      return true;
+    }
+  }
+
+  // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/
+  {
+    cmFindPackageFileList lister(this);
+    lister / cmFileListGeneratorFixed(prefix) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
+      cmFileListGeneratorEnumerate(common) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection);
+    if (lister.Search()) {
+      return true;
+    }
+  }
+
+  // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/(cmake|CMake)/
+  {
+    cmFindPackageFileList lister(this);
+    lister / cmFileListGeneratorFixed(prefix) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
+      cmFileListGeneratorEnumerate(common) /
+      cmFileListGeneratorProject(this->Names, this->SortOrder,
+                                 this->SortDirection) /
       cmFileListGeneratorCaseInsensitive("cmake");
     if (lister.Search()) {
       return true;
diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h
index eff6b80..501a5a5 100644
--- a/Source/cmFindPackageCommand.h
+++ b/Source/cmFindPackageCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindPackageCommand_h
 #define cmFindPackageCommand_h
 
@@ -24,29 +15,50 @@ class cmFindPackageFileList;
 class cmFindPackageCommand : public cmFindCommon
 {
 public:
+  /*! A sorting order strategy to be applied to recovered package folders (see
+   * FIND_PACKAGE_SORT_ORDER)*/
+  enum /*class*/ SortOrderType
+  {
+    None,
+    Name_order,
+    Natural
+  };
+  /*! A sorting direction to be applied to recovered package folders (see
+   * FIND_PACKAGE_SORT_DIRECTION)*/
+  enum /*class*/ SortDirectionType
+  {
+    Asc,
+    Dec
+  };
+
+  /*! sorts a given list of string based on the input sort parameters */
+  static void Sort(std::vector<std::string>::iterator begin,
+                   std::vector<std::string>::iterator end, SortOrderType order,
+                   SortDirectionType dir);
+
   cmFindPackageCommand();
 
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFindPackageCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFindPackageCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "find_package"; }
+  std::string GetName() const CM_OVERRIDE { return "find_package"; }
 
   cmTypeMacro(cmFindPackageCommand, cmFindCommon);
 
@@ -148,6 +160,7 @@ private:
   bool NoUserRegistry;
   bool NoSystemRegistry;
   bool DebugMode;
+  bool UseLib32Paths;
   bool UseLib64Paths;
   bool PolicyScope;
   std::string LibraryArchitecture;
@@ -155,10 +168,30 @@ private:
   std::vector<std::string> Configs;
   std::set<std::string> IgnoredPaths;
 
+  /*! the selected sortOrder (None by default)*/
+  SortOrderType SortOrder;
+  /*! the selected sortDirection (Asc by default)*/
+  SortDirectionType SortDirection;
+
   struct ConfigFileInfo
   {
     std::string filename;
     std::string version;
+
+    bool operator<(ConfigFileInfo const& rhs) const
+    {
+      return this->filename < rhs.filename;
+    }
+
+    bool operator==(ConfigFileInfo const& rhs) const
+    {
+      return this->filename == rhs.filename;
+    }
+
+    bool operator!=(ConfigFileInfo const& rhs) const
+    {
+      return !(*this == rhs);
+    }
   };
   std::vector<ConfigFileInfo> ConsideredConfigs;
 };
diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx
index d24be6a..35929fe 100644
--- a/Source/cmFindPathCommand.cxx
+++ b/Source/cmFindPathCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindPathCommand.h"
 
 #include <cmsys/Glob.hxx>
@@ -117,7 +108,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file,
     if (this->IncludeFileInPath) {
       return fheader;
     }
-    fheader = cmSystemTools::GetFilenamePath(fheader);
+    fheader.resize(fheader.size() - file.size());
     return fheader;
   }
   return "";
@@ -136,9 +127,8 @@ std::string cmFindPathCommand::FindNormalHeader()
       if (cmSystemTools::FileExists(tryPath.c_str())) {
         if (this->IncludeFileInPath) {
           return tryPath;
-        } else {
-          return *p;
         }
+        return *p;
       }
     }
   }
diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h
index e14626a..58cc0f3 100644
--- a/Source/cmFindPathCommand.h
+++ b/Source/cmFindPathCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindPathCommand_h
 #define cmFindPathCommand_h
 
@@ -28,24 +19,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFindPathCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFindPathCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "find_path"; }
+  std::string GetName() const CM_OVERRIDE { return "find_path"; }
 
   cmTypeMacro(cmFindPathCommand, cmFindBase);
   bool IncludeFileInPath;
diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx
index 8d142c9..a6f2518 100644
--- a/Source/cmFindProgramCommand.cxx
+++ b/Source/cmFindProgramCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindProgramCommand.h"
 
 #include <stdlib.h>
@@ -140,9 +131,8 @@ std::string cmFindProgramCommand::FindNormalProgram()
 {
   if (this->NamesPerDir) {
     return this->FindNormalProgramNamesPerDir();
-  } else {
-    return this->FindNormalProgramDirsPerName();
   }
+  return this->FindNormalProgramDirsPerName();
 }
 
 std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
diff --git a/Source/cmFindProgramCommand.h b/Source/cmFindProgramCommand.h
index 3f2ac0e..2d88b79 100644
--- a/Source/cmFindProgramCommand.h
+++ b/Source/cmFindProgramCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFindProgramCommand_h
 #define cmFindProgramCommand_h
 
@@ -29,24 +20,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFindProgramCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFindProgramCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "find_program"; }
+  std::string GetName() const CM_OVERRIDE { return "find_program"; }
 
   cmTypeMacro(cmFindProgramCommand, cmFindBase);
 
diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx
index daf43e6..987741b 100644
--- a/Source/cmForEachCommand.cxx
+++ b/Source/cmForEachCommand.cxx
@@ -1,17 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmForEachCommand.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
 
 cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf)
   : Makefile(mf)
@@ -36,8 +27,7 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
     // if this is the endofreach for this statement
     if (!this->Depth) {
       // Remove the function blocker for this scope or bail.
-      cmsys::auto_ptr<cmFunctionBlocker> fb(
-        mf.RemoveFunctionBlocker(this, lff));
+      CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
       if (!fb.get()) {
         return false;
       }
@@ -82,10 +72,9 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
       // restore the variable to its prior value
       mf.AddDefinition(this->Args[0], oldDef.c_str());
       return true;
-    } else {
-      // close out a nested foreach
-      this->Depth--;
     }
+    // close out a nested foreach
+    this->Depth--;
   }
 
   // record the command
@@ -114,7 +103,7 @@ bool cmForEachFunctionBlocker::ShouldRemove(const cmListFileFunction& lff,
 bool cmForEachCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -184,7 +173,7 @@ bool cmForEachCommand::InitialPass(std::vector<std::string> const& args,
 
 bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args)
 {
-  cmsys::auto_ptr<cmForEachFunctionBlocker> f(
+  CM_AUTO_PTR<cmForEachFunctionBlocker> f(
     new cmForEachFunctionBlocker(this->Makefile));
   f->Args.push_back(args[0]);
 
diff --git a/Source/cmForEachCommand.h b/Source/cmForEachCommand.h
index 60956aa..1e3d786 100644
--- a/Source/cmForEachCommand.h
+++ b/Source/cmForEachCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmForEachCommand_h
 #define cmForEachCommand_h
 
@@ -21,10 +12,10 @@ class cmForEachFunctionBlocker : public cmFunctionBlocker
 {
 public:
   cmForEachFunctionBlocker(cmMakefile* mf);
-  ~cmForEachFunctionBlocker();
-  virtual bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
-                                 cmExecutionStatus&);
-  virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf);
+  ~cmForEachFunctionBlocker() CM_OVERRIDE;
+  bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
+                         cmExecutionStatus&) CM_OVERRIDE;
+  bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
 
   std::vector<std::string> Args;
   std::vector<cmListFileFunction> Functions;
@@ -41,24 +32,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmForEachCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmForEachCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "foreach"; }
+  std::string GetName() const CM_OVERRIDE { return "foreach"; }
 
   cmTypeMacro(cmForEachCommand, cmCommand);
 
diff --git a/Source/cmFortranLexer.cxx b/Source/cmFortranLexer.cxx
index 7cde4cb..a5ef47d 100644
--- a/Source/cmFortranLexer.cxx
+++ b/Source/cmFortranLexer.cxx
@@ -1,14 +1,3 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
 #line 2 "cmFortranLexer.cxx"
 
 #line 4 "cmFortranLexer.cxx"
@@ -19,8 +8,8 @@
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 39
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -99,25 +88,13 @@ typedef unsigned int flex_uint32_t;
 
 #endif /* ! FLEXINT_H */
 
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else   /* ! __cplusplus */
-
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
-
-#define YY_USE_CONST
-
-#endif  /* defined (__STDC__) */
-#endif  /* ! __cplusplus */
-
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* Returned upon end-of-file. */
@@ -204,83 +181,83 @@ typedef size_t yy_size_t;
 
 /* Return all but the first "n" matched characters back to the input stream. */
 #define yyless(n) \
-        do \
-                { \
-                /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-                *yy_cp = yyg->yy_hold_char; \
-                YY_RESTORE_YY_MORE_OFFSET \
-                yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-                YY_DO_BEFORE_ACTION; /* set up yytext again */ \
-                } \
-        while ( 0 )
+		*yy_cp = yyg->yy_hold_char; \
+		YY_RESTORE_YY_MORE_OFFSET \
+		yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
 
 #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-        {
-        FILE *yy_input_file;
-
-        char *yy_ch_buf;                /* input buffer */
-        char *yy_buf_pos;               /* current position in input buffer */
-
-        /* Size of input buffer in bytes, not including room for EOB
-         * characters.
-         */
-        yy_size_t yy_buf_size;
-
-        /* Number of characters read into yy_ch_buf, not including EOB
-         * characters.
-         */
-        yy_size_t yy_n_chars;
-
-        /* Whether we "own" the buffer - i.e., we know we created it,
-         * and can realloc() it to grow it, and should free() it to
-         * delete it.
-         */
-        int yy_is_our_buffer;
-
-        /* Whether this is an "interactive" input source; if so, and
-         * if we're using stdio for input, then we want to use getc()
-         * instead of fread(), to make sure we stop fetching input after
-         * each newline.
-         */
-        int yy_is_interactive;
-
-        /* Whether we're considered to be at the beginning of a line.
-         * If so, '^' rules will be active on the next match, otherwise
-         * not.
-         */
-        int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-        /* Whether to try to fill the input buffer when we reach the
-         * end of it.
-         */
-        int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-        int yy_buffer_status;
+	int yy_buffer_status;
 
 #define YY_BUFFER_NEW 0
 #define YY_BUFFER_NORMAL 1
-        /* When an EOF's been seen but there's still some text to process
-         * then we mark the buffer as YY_EOF_PENDING, to indicate that we
-         * shouldn't try reading from the input source any more.  We might
-         * still have a bunch of tokens to match, though, because of
-         * possible backing-up.
-         *
-         * When we actually see the EOF, we change the status to "new"
-         * (via cmFortran_yyrestart()), so that the user can continue scanning by
-         * just pointing yyin at a new input file.
-         */
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via cmFortran_yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
 #define YY_BUFFER_EOF_PENDING 2
 
-        };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 /* We provide macros for accessing buffer states in case in the
@@ -314,7 +291,7 @@ static void cmFortran_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yys
 
 YY_BUFFER_STATE cmFortran_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
 YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
 
 void *cmFortran_yyalloc (yy_size_t ,yyscan_t yyscanner );
 void *cmFortran_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -323,30 +300,30 @@ void cmFortran_yyfree (void * ,yyscan_t yyscanner );
 #define yy_new_buffer cmFortran_yy_create_buffer
 
 #define yy_set_interactive(is_interactive) \
-        { \
-        if ( ! YY_CURRENT_BUFFER ){ \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){ \
         cmFortran_yyensure_buffer_stack (yyscanner); \
-                YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-        } \
-        YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
-        }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+	}
 
 #define yy_set_bol(at_bol) \
-        { \
-        if ( ! YY_CURRENT_BUFFER ){\
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){\
         cmFortran_yyensure_buffer_stack (yyscanner); \
-                YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-        } \
-        YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
-        }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+	}
 
 #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
 
 /* Begin user sect3 */
 
-#define cmFortran_yywrap(yyscanner) 1
+#define cmFortran_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 typedef unsigned char YY_CHAR;
@@ -358,66 +335,70 @@ typedef int yy_state_type;
 static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
 static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,yyscan_t yyscanner);
 static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
 
 /* Done after the current pattern has been matched and before the
  * corresponding action - sets up yytext.
  */
 #define YY_DO_BEFORE_ACTION \
-        yyg->yytext_ptr = yy_bp; \
-        yyleng = (size_t) (yy_cp - yy_bp); \
-        yyg->yy_hold_char = *yy_cp; \
-        *yy_cp = '\0'; \
-        yyg->yy_c_buf_p = yy_cp;
-
-#define YY_NUM_RULES 45
-#define YY_END_OF_BUFFER 46
+	yyg->yytext_ptr = yy_bp; \
+	yyleng = (int) (yy_cp - yy_bp); \
+	yyg->yy_hold_char = *yy_cp; \
+	*yy_cp = '\0'; \
+	yyg->yy_c_buf_p = yy_cp;
+
+#define YY_NUM_RULES 54
+#define YY_END_OF_BUFFER 55
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
-        {
-        flex_int32_t yy_verify;
-        flex_int32_t yy_nxt;
-        };
-static yyconst flex_int16_t yy_accept[173] =
+	{
+	flex_int32_t yy_verify;
+	flex_int32_t yy_nxt;
+	};
+static yyconst flex_int16_t yy_accept[210] =
     {   0,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-       46,   40,   42,   41,   44,    1,   40,   33,    2,   35,
-       40,   41,   38,   40,   39,   40,   39,   42,   40,   41,
-       40,   39,    9,    8,    9,    4,    3,   40,    0,   10,
-        0,    0,    0,    0,    0,   33,   33,   34,   36,   38,
-       40,   39,    0,   43,   39,    0,    0,    0,   12,    0,
-        0,    0,    0,    0,    0,   40,    0,   11,   39,    0,
-        0,    5,    0,    0,    0,   29,    0,    0,   33,   33,
-       33,   33,    0,    0,   12,   12,    0,    0,    0,   23,
-        0,    0,    0,    0,    0,    0,    6,    0,    0,    0,
-
+       55,   49,   51,   50,   53,    1,   49,   33,    2,   47,
+       48,   35,   37,   50,   39,   49,   46,   46,   46,   46,
+       46,   46,   49,   46,   51,   49,   50,   49,   46,    9,
+        8,    9,    4,    3,   49,    0,   10,    0,    0,    0,
+        0,    0,   33,   33,   34,   36,   39,   49,   46,   46,
+       46,   46,   46,   46,    0,   52,   46,    0,    0,    0,
+       12,    0,    0,    0,    0,    0,    0,   49,    0,   11,
+       46,    0,    0,    5,    0,    0,    0,   29,    0,    0,
+       33,   33,   33,   33,    0,    0,   40,   46,   46,   46,
+
+       46,   45,   12,   12,    0,    0,    0,   23,    0,    0,
+        0,    0,    0,    0,    6,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,   46,   46,   46,   46,    0,    0,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,    0,    0,    0,   30,   31,
-        0,    0,    0,    0,    0,    0,    0,   24,   25,    0,
-        0,    0,    0,    0,    0,    0,    0,    0,   32,   27,
-        0,    0,   20,    0,    0,   26,   21,    0,    0,    0,
-       19,    0,    0,   18,   28,    0,    0,   17,   22,    0,
-        7,   37,    7,   15,    0,   14,   16,    0,    0,    0,
-       13,    0
+       30,   31,    0,    0,    0,    0,    0,    0,   46,   46,
+       46,   46,    0,   24,   25,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,   32,   27,    0,    0,   20,    0,
+       46,   46,   43,   46,    0,   26,   21,    0,    0,    0,
+       19,    0,    0,   18,   28,    0,    0,   41,   46,   46,
+       17,   22,    0,    7,   38,    7,   15,    0,   46,   46,
+
+       14,   16,   42,   44,    0,    0,    0,   13,    0
     } ;
 
-static yyconst flex_int32_t yy_ec[256] =
+static yyconst YY_CHAR yy_ec[256] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
         1,    1,    4,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    5,    6,    7,    8,    9,    1,   10,   11,    1,
-        1,   12,    1,   13,    1,    1,    1,   14,   14,   14,
-       14,   14,   14,   14,   14,   14,   14,   15,   16,   17,
-       18,   19,   20,    1,   21,   21,   22,   23,   24,   25,
-       21,   21,   26,   21,   21,   27,   21,   28,   21,   21,
-       21,   21,   29,   21,   30,   21,   21,   21,   21,   21,
-        1,   31,    1,    1,   32,    1,   21,   21,   33,   34,
-
-       35,   36,   21,   21,   37,   21,   21,   38,   21,   39,
-       21,   21,   21,   21,   40,   21,   41,   21,   21,   21,
-       21,   21,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    5,    6,    7,    8,    9,    1,   10,   11,   12,
+       13,   14,    1,   15,    1,    1,    1,   16,   16,   16,
+       16,   16,   16,   16,   16,   16,   16,   17,   18,   19,
+       20,   21,   22,    1,   23,   24,   25,   26,   27,   28,
+       29,   29,   30,   29,   29,   31,   32,   33,   34,   29,
+       29,   35,   36,   37,   38,   29,   29,   29,   29,   29,
+        1,   39,    1,    1,   40,    1,   23,   24,   41,   42,
+
+       43,   44,   29,   29,   45,   29,   29,   46,   32,   47,
+       34,   29,   29,   35,   48,   37,   49,   29,   29,   29,
+       29,   29,    1,    1,    1,    1,    1,    1,    1,    1,
         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,
@@ -434,195 +415,217 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int32_t yy_meta[42] =
+static yyconst YY_CHAR yy_meta[50] =
     {   0,
         1,    2,    2,    3,    4,    3,    3,    1,    1,    3,
-        3,    1,    3,    5,    1,    3,    1,    3,    6,    1,
-        7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
-        1,    5,    7,    7,    7,    7,    7,    7,    7,    7,
-        7
+        3,    3,    3,    1,    3,    5,    3,    3,    1,    3,
+        6,    1,    7,    7,    7,    7,    7,    7,    7,    7,
+        7,    7,    7,    7,    7,    7,    7,    7,    1,    5,
+        7,    7,    7,    7,    7,    7,    7,    7,    7
     } ;
 
-static yyconst flex_int16_t yy_base[182] =
+static yyconst flex_uint16_t yy_base[219] =
     {   0,
-        0,   40,    0,   41,  220,   48,   44,   54,   56,   65,
-      220,    0,  535,  535,  216,  535,   81,   74,  535,  535,
-      186,  535,  153,  145,    0,   85,  122,   87,  154,  155,
-      195,  227,  535,  147,   91,  535,  535,    0,  147,  535,
-      267,   34,   70,   74,   34,  122,  141,  535,    0,  535,
-      112,    0,   98,  535,    0,  156,  307,    0,  143,   43,
-      155,  151,   48,  101,  130,  348,  130,  535,    0,  121,
-      197,  165,  172,  244,  182,  183,  191,  248,  273,  293,
-      308,  314,  321,  246,  275,  216,  269,  299,  304,  327,
-      307,  304,  312,  116,  107,  367,  535,  327,  334,  347,
-
-      347,  350,  352,  349,  354,  359,  357,  363,  366,  365,
-      369,  372,  369,  373,  374,  101,   86,  372,  535,  535,
-      378,  380,  386,  382,  388,  388,  389,  535,  535,  393,
-      394,  396,  392,  430,  400,   56,   47,  403,  535,  535,
-      409,  414,  535,  409,  416,  535,  535,  416,  419,  441,
-      535,  117,    0,  535,  535,  423,  426,  535,  535,  430,
-      535,  535,  535,  535,  432,  457,  535,  459,    0,   25,
-      535,  535,  476,  483,  489,  492,  499,  506,  513,  520,
-      527
+        0,   48,    0,   49,  513,   56,   52,   57,   62,   68,
+      515,    0,  583,  583,  509,  583,   97,   74,  583,  583,
+      583,  583,  491,  583,  423,  421,    0,   19,   40,  392,
+       36,   47,   86,  146,   88,  186,  413,  235,  275,  583,
+      407,   98,  583,  583,    0,  386,  583,  323,   65,   73,
+       81,   74,  127,  146,  583,  583,  583,  108,    0,   89,
+      120,   92,  362,  116,  161,  583,    0,  167,  371,    0,
+      168,  131,  146,  171,   81,   89,  352,  420,  353,  583,
+        0,  349,  178,  196,  175,  197,  188,  208,  196,  197,
+      256,  262,  324,  330,  337,  143,    0,  151,  220,   56,
+
+      305,    0,  336,  139,  225,  315,  305,  322,  318,  163,
+      320,  268,  266,  369,  583,  340,  347,  350,  350,  351,
+      357,  350,  357,  363,  140,  235,  359,  218,  362,  375,
+      379,  380,  381,  385,  384,  404,  405,  243,  235,  213,
+      583,  583,  405,  407,  410,  171,  410,  409,  419,  418,
+      423,  426,  311,  583,  583,  428,  429,  431,  173,  462,
+      435,  166,  145,  438,  583,  583,  441,  444,  583,  433,
+      448,   89,    0,  438,  450,  583,  583,  452,  457,  487,
+      583,  114,    0,  583,  583,  457,  462,    0,  465,  463,
+      583,  583,  468,  583,  583,  583,  583,  470,  471,  474,
+
+      500,  583,    0,    0,  505,    0,   65,  583,  583,  524,
+      531,  537,  540,  547,  554,  561,  568,  575
     } ;
 
-static yyconst flex_int16_t yy_def[182] =
+static yyconst flex_int16_t yy_def[219] =
     {   0,
-      172,    1,    1,    1,    1,    1,  173,  173,  173,  173,
-      172,  174,  172,  172,  175,  172,  174,  172,  172,  172,
-      174,  172,  172,  174,  176,  174,  176,  172,  172,  172,
-      177,  172,  172,  172,  172,  172,  172,  174,  175,  172,
-      172,  172,  172,  172,  172,  172,  178,  172,  174,  172,
-      174,  176,  172,  172,   27,  172,  172,   57,  174,  172,
-      172,  172,  172,  172,  172,  177,  177,  172,   32,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  178,  178,
-      178,  178,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  179,  180,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  181,  181,
-      172,    0,  172,  172,  172,  172,  172,  172,  172,  172,
-      172
+      209,    1,    1,    1,    1,    1,  210,  210,  210,  210,
+      209,  211,  209,  209,  212,  209,  211,  209,  209,  209,
+      209,  209,  209,  209,  209,  211,  213,  213,  213,  213,
+      213,  213,  211,  213,  209,  209,  209,  214,  209,  209,
+      209,  209,  209,  209,  211,  212,  209,  209,  209,  209,
+      209,  209,  209,  215,  209,  209,  209,  211,  213,  213,
+      213,  213,  213,  213,  209,  209,   34,  209,  209,   69,
+      211,  209,  209,  209,  209,  209,  209,  214,  214,  209,
+       39,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      215,  215,  215,  215,  209,  209,  213,  213,  213,  213,
+
+      213,  213,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  213,  213,  213,  213,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  213,  213,
+      213,  213,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      213,  213,  213,  213,  209,  209,  209,  209,  209,  209,
+      209,  216,  217,  209,  209,  209,  209,  213,  213,  213,
+      209,  209,  209,  209,  209,  209,  209,  209,  213,  213,
+
+      209,  209,  213,  213,  209,  218,  218,  209,    0,  209,
+      209,  209,  209,  209,  209,  209,  209,  209
     } ;
 
-static yyconst flex_int16_t yy_nxt[577] =
+static yyconst flex_uint16_t yy_nxt[633] =
     {   0,
        12,   13,   14,   13,   13,   15,   16,   12,   17,   18,
-       19,   12,   20,   12,   21,   22,   12,   23,   12,   24,
-       25,   25,   25,   25,   25,   25,   25,   25,   25,   25,
-       26,   27,   25,   25,   25,   25,   25,   25,   25,   25,
-       25,   28,   28,  171,   28,   28,   34,   29,   29,   28,
-       30,  153,   28,   35,   36,   29,   34,   73,   34,   31,
-      152,   78,   37,   35,   36,   35,   87,   34,   73,   32,
-       32,   37,   78,   92,   35,   46,   46,   87,   46,   47,
-       32,   32,   41,   48,   92,   41,   53,   54,   56,   53,
-      137,   56,   71,   72,   57,   71,   74,   75,   76,   53,
-
-       54,   77,   53,   42,   43,  136,   44,   74,   75,   76,
-       45,  117,   77,   83,   42,   43,   83,   44,  162,  162,
-      116,   45,   38,   46,   46,   95,   46,   47,   93,   38,
-       38,   48,   68,   38,   94,   55,   38,   84,   38,   93,
-       38,   38,   80,   46,   86,   80,   81,   86,   84,   40,
-       82,   70,   38,   55,   38,   58,   59,   56,   58,   65,
-       56,   38,   38,   57,   51,   38,   96,   59,   38,   96,
-       38,   50,   38,   38,   97,   90,   60,   61,   91,   62,
-       63,   88,   89,   64,   38,   38,   90,   60,   61,   91,
-       62,   63,   88,   89,   64,   66,   98,   68,   71,   72,
-
-       49,   71,   66,   66,  101,  102,   66,   98,   66,   66,
-      103,   66,  104,   66,   66,  101,  102,   86,   40,  172,
-       86,  103,   30,  104,  172,   66,   66,   67,   67,   68,
-       67,   67,   67,   67,   67,   67,   67,   67,   67,   67,
-       69,   67,   67,   67,   67,   67,   67,   69,   69,   69,
-       69,   69,   69,   69,   69,   69,   69,   67,   69,   69,
-       69,   69,   69,   69,   69,   69,   69,   69,   41,   99,
-      105,   41,  100,  106,   80,   46,   86,   80,   81,   86,
-       99,  105,   82,  100,  106,  172,  172,  172,   85,   42,
-       43,  172,   44,  107,   80,   46,   45,   80,   81,  172,
-
-       42,   43,   82,   44,  107,  172,  172,   45,   58,   80,
-       46,   58,   80,   81,  172,   80,   46,   82,   80,   81,
-       85,  172,   83,   82,  108,   83,  110,  109,  113,   60,
-       61,  114,   62,   63,  115,  108,   64,  110,  109,  113,
-       60,   61,  114,   62,   63,  115,   84,   64,   66,  111,
-       68,  172,  118,  172,  112,   66,   66,   84,  119,   66,
-      111,   66,   66,  118,   66,  112,   66,   66,   96,  119,
-      120,   96,  121,  122,  123,  124,   97,  125,   66,   66,
-      126,  120,  127,  121,  122,  123,  124,  128,  125,  129,
-      130,  126,  131,  127,  132,  133,  134,  135,  128,  138,
-
-      129,  130,  139,  131,  140,  132,  133,  134,  135,  141,
-      138,  142,  143,  139,  144,  140,  145,  146,  147,  148,
-      141,  149,  142,  143,  151,  144,  154,  145,  146,  147,
-      148,  150,  149,  155,  150,  151,  156,  154,  157,  158,
-      159,  160,  150,   85,  155,  150,  164,  156,  165,  157,
-      158,  159,  160,  166,   85,  167,  172,  164,  168,  165,
-      168,  168,  172,  168,  166,  172,  167,  172,  172,  172,
-      172,  172,  172,  169,  172,  169,   33,   33,   33,   33,
-       33,   33,   33,   38,  172,  172,  172,   38,   38,   39,
-       39,   39,   39,   39,   39,   39,   52,  172,   52,   67,
-
-       67,   67,   67,   67,   67,   67,   79,   79,   79,   79,
-       79,   79,   79,  161,  161,  161,  172,  161,  161,  161,
-      163,  172,  163,  172,  163,  163,  163,  170,  170,  170,
-      170,  170,  172,  170,   11,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172
+       19,   20,   21,   12,   22,   12,   23,   24,   12,   25,
+       12,   26,   27,   27,   27,   27,   28,   27,   27,   29,
+       27,   30,   27,   27,   27,   31,   27,   32,   33,   34,
+       27,   27,   28,   27,   29,   27,   27,   31,   32,   35,
+       35,   60,   35,   35,   41,   36,   36,   35,   37,   41,
+       35,   42,   43,   36,   41,   60,   42,   43,   44,   38,
+       41,   42,   61,   63,   44,   53,   53,   42,   53,   54,
+       39,   39,   64,   55,   63,  208,   61,   65,   66,   68,
+       65,   85,   68,  127,   64,   69,   39,   39,   48,   83,
+
+       84,   48,   83,   86,  127,   87,   90,   85,   88,   95,
+      110,  189,   95,   89,   97,  195,  195,  100,   86,   87,
+       90,  111,   49,   50,   88,  110,   51,   89,   53,   53,
+       97,   53,   54,  100,   52,  111,   55,   96,   49,   50,
+      104,   51,  102,  104,   98,   52,   45,   92,   53,  183,
+       92,   93,   96,   45,   45,   94,   99,  105,  102,   45,
+       98,   67,   65,   66,   45,   65,   45,   45,   68,  104,
+      182,   68,  104,  105,   69,  124,  106,  149,  107,   83,
+       84,  125,   83,   71,   45,   67,   45,   70,  149,  124,
+       70,  106,  107,   45,   45,  136,  125,  114,  108,   45,
+
+      114,   71,  116,  109,   45,  115,   45,   45,  168,  136,
+      179,   72,   73,  119,  108,   74,   75,  109,  116,  168,
+      122,  179,  123,   76,   45,   45,  117,   72,   73,  119,
+       74,   75,  118,  120,   76,   78,  122,   80,  123,  163,
+      121,  117,   78,   78,  118,  164,  126,  162,   78,  120,
+       78,  152,  129,   78,  121,   78,   78,   92,   53,  164,
+       92,   93,  126,   92,   53,   94,   92,   93,  129,  150,
+      139,   94,  138,   78,   78,   79,   79,   80,   79,   79,
+       79,   79,   79,   79,   79,   79,   79,   79,   79,   79,
+       81,   79,   79,   79,   79,   79,   79,   81,   81,   81,
+
+       81,   81,   81,   81,   81,   81,   81,   81,   81,   81,
+       81,   81,   81,   79,   81,   81,   81,   81,   81,   81,
+       81,   81,   81,   81,   48,   92,   53,   48,   92,   93,
+      132,   92,   53,   94,   92,   93,  128,  104,   95,   94,
+      104,   95,  135,  175,  130,  137,  132,  133,   49,   50,
+      131,  103,   51,  113,  134,   80,  112,  175,  135,  130,
+       52,  137,  131,  133,   49,   50,   96,   51,  134,  140,
+      114,   52,   70,  114,  141,   70,  142,  144,  115,  143,
+      146,   96,  145,  147,  140,  101,  103,  148,   47,  151,
+      141,  153,  142,  144,  143,  146,   72,   73,  145,  147,
+
+       74,   75,  154,  148,  151,  155,  153,  157,   76,  156,
+      158,   82,   72,   73,  159,   74,   75,   77,  154,   76,
+       78,  155,   80,  157,  156,   62,  158,   78,   78,  159,
+      160,  161,  165,   78,  166,   78,  167,  169,   78,  170,
+       78,   78,   58,   57,  171,  172,  160,  161,  165,  173,
+      166,  174,  167,  169,  170,  176,  177,  178,   78,   78,
+      171,  172,  181,  180,  184,  173,  180,  174,  185,  186,
+      187,  176,  177,  178,  188,  190,  191,  103,  181,  192,
+      184,  187,  193,  197,  185,  186,  190,  198,  180,  199,
+      188,  180,  191,  200,  201,  192,  202,  203,  193,  197,
+
+      204,  205,  103,  198,  205,  199,  205,   56,  200,  205,
+      201,   47,  202,  203,  209,   37,  204,  209,  206,  209,
+      209,  209,  209,  206,   40,   40,   40,   40,   40,   40,
+       40,   45,  209,  209,  209,   45,   45,   46,   46,   46,
+       46,   46,   46,   46,   59,  209,   59,   79,   79,   79,
+       79,   79,   79,   79,   91,   91,   91,   91,   91,   91,
+       91,  194,  194,  194,  209,  194,  194,  194,  196,  209,
+      196,  209,  196,  196,  196,  207,  207,  207,  207,  207,
+      209,  207,   11,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209
     } ;
 
-static yyconst flex_int16_t yy_chk[577] =
+static yyconst flex_int16_t yy_chk[633] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    2,    4,  170,    2,    4,    7,    2,    4,    6,
-        6,  137,    6,    7,    7,    6,    8,   42,    9,    6,
-      136,   45,    9,    8,    8,    9,   60,   10,   42,    6,
-        6,   10,   45,   63,   10,   18,   18,   60,   18,   18,
-        6,    6,   17,   18,   63,   17,   26,   26,   28,   26,
-      117,   28,   35,   35,   28,   35,   43,   43,   44,   53,
-
-       53,   44,   53,   17,   17,  116,   17,   43,   43,   44,
-       17,   95,   44,   51,   17,   17,   51,   17,  152,  152,
-       94,   17,   27,   46,   46,   70,   46,   46,   64,   27,
-       27,   46,   67,   27,   65,   27,   27,   51,   27,   64,
-       27,   27,   47,   47,   59,   47,   47,   59,   51,   39,
-       47,   34,   27,   27,   29,   29,   59,   56,   29,   30,
-       56,   29,   29,   56,   24,   29,   72,   29,   29,   72,
-       29,   23,   29,   29,   72,   62,   29,   29,   62,   29,
-       29,   61,   61,   29,   29,   29,   62,   29,   29,   62,
-       29,   29,   61,   61,   29,   31,   73,   31,   71,   71,
-
-       21,   71,   31,   31,   75,   76,   31,   73,   31,   31,
-       76,   31,   77,   31,   31,   75,   76,   86,   15,   11,
-       86,   76,    5,   77,    0,   31,   31,   32,   32,   32,
-       32,   32,   32,   32,   32,   32,   32,   32,   32,   32,
-       32,   32,   32,   32,   32,   32,   32,   32,   32,   32,
-       32,   32,   32,   32,   32,   32,   32,   32,   32,   32,
-       32,   32,   32,   32,   32,   32,   32,   32,   41,   74,
-       78,   41,   74,   84,   79,   79,   85,   79,   79,   85,
-       74,   78,   79,   74,   84,    0,    0,    0,   85,   41,
-       41,    0,   41,   87,   80,   80,   41,   80,   80,    0,
-
-       41,   41,   80,   41,   87,    0,    0,   41,   57,   81,
-       81,   57,   81,   81,    0,   82,   82,   81,   82,   82,
-       57,    0,   83,   82,   88,   83,   89,   88,   91,   57,
-       57,   92,   57,   57,   93,   88,   57,   89,   88,   91,
-       57,   57,   92,   57,   57,   93,   83,   57,   66,   90,
-       66,    0,   98,    0,   90,   66,   66,   83,   99,   66,
-       90,   66,   66,   98,   66,   90,   66,   66,   96,   99,
-      100,   96,  101,  102,  103,  104,   96,  105,   66,   66,
-      106,  100,  107,  101,  102,  103,  104,  108,  105,  109,
-      110,  106,  111,  107,  112,  113,  114,  115,  108,  118,
-
-      109,  110,  121,  111,  122,  112,  113,  114,  115,  123,
-      118,  124,  125,  121,  126,  122,  127,  130,  131,  132,
-      123,  133,  124,  125,  135,  126,  138,  127,  130,  131,
-      132,  134,  133,  141,  134,  135,  142,  138,  144,  145,
-      148,  149,  150,  134,  141,  150,  156,  142,  157,  144,
-      145,  148,  149,  160,  150,  165,    0,  156,  166,  157,
-      168,  166,    0,  168,  160,    0,  165,    0,    0,    0,
-        0,    0,    0,  166,    0,  168,  173,  173,  173,  173,
-      173,  173,  173,  174,    0,    0,    0,  174,  174,  175,
-      175,  175,  175,  175,  175,  175,  176,    0,  176,  177,
-
-      177,  177,  177,  177,  177,  177,  178,  178,  178,  178,
-      178,  178,  178,  179,  179,  179,    0,  179,  179,  179,
-      180,    0,  180,    0,  180,  180,  180,  181,  181,  181,
-      181,  181,    0,  181,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172,  172,  172,  172,  172,
-      172,  172,  172,  172,  172,  172
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    2,
+        4,   28,    2,    4,    7,    2,    4,    6,    6,    8,
+        6,    7,    7,    6,    9,   28,    8,    8,    9,    6,
+       10,    9,   29,   31,   10,   18,   18,   10,   18,   18,
+        6,    6,   32,   18,   31,  207,   29,   33,   33,   35,
+       33,   49,   35,  100,   32,   35,    6,    6,   17,   42,
+
+       42,   17,   42,   50,  100,   50,   52,   49,   51,   58,
+       75,  172,   58,   51,   60,  182,  182,   62,   50,   50,
+       52,   76,   17,   17,   51,   75,   17,   51,   53,   53,
+       60,   53,   53,   62,   17,   76,   53,   58,   17,   17,
+      104,   17,   64,  104,   61,   17,   34,   54,   54,  163,
+       54,   54,   58,   34,   34,   54,   61,   72,   64,   34,
+       61,   34,   65,   65,   34,   65,   34,   34,   68,   71,
+      162,   68,   71,   72,   68,   96,   73,  125,   73,   83,
+       83,   98,   83,   71,   34,   34,   36,   36,  125,   96,
+       36,   73,   73,   36,   36,  110,   98,   84,   74,   36,
+
+       84,   36,   85,   74,   36,   84,   36,   36,  146,  110,
+      159,   36,   36,   87,   74,   36,   36,   74,   85,  146,
+       89,  159,   90,   36,   36,   36,   86,   36,   36,   87,
+       36,   36,   86,   88,   36,   38,   89,   38,   90,  139,
+       88,   86,   38,   38,   86,  140,   99,  138,   38,   88,
+       38,  128,  105,   38,   88,   38,   38,   91,   91,  140,
+       91,   91,   99,   92,   92,   91,   92,   92,  105,  126,
+      113,   92,  112,   38,   38,   39,   39,   39,   39,   39,
+       39,   39,   39,   39,   39,   39,   39,   39,   39,   39,
+       39,   39,   39,   39,   39,   39,   39,   39,   39,   39,
+
+       39,   39,   39,   39,   39,   39,   39,   39,   39,   39,
+       39,   39,   39,   39,   39,   39,   39,   39,   39,   39,
+       39,   39,   39,   39,   48,   93,   93,   48,   93,   93,
+      107,   94,   94,   93,   94,   94,  101,  103,   95,   94,
+      103,   95,  109,  153,  106,  111,  107,  108,   48,   48,
+      106,  103,   48,   82,  108,   79,   77,  153,  109,  106,
+       48,  111,  106,  108,   48,   48,   95,   48,  108,  116,
+      114,   48,   69,  114,  117,   69,  118,  120,  114,  119,
+      122,   95,  121,  123,  116,   63,   69,  124,   46,  127,
+      117,  129,  118,  120,  119,  122,   69,   69,  121,  123,
+
+       69,   69,  130,  124,  127,  131,  129,  133,   69,  132,
+      134,   41,   69,   69,  135,   69,   69,   37,  130,   69,
+       78,  131,   78,  133,  132,   30,  134,   78,   78,  135,
+      136,  137,  143,   78,  144,   78,  145,  147,   78,  148,
+       78,   78,   26,   25,  149,  150,  136,  137,  143,  151,
+      144,  152,  145,  147,  148,  156,  157,  158,   78,   78,
+      149,  150,  161,  160,  164,  151,  160,  152,  167,  168,
+      170,  156,  157,  158,  171,  174,  175,  160,  161,  178,
+      164,  170,  179,  186,  167,  168,  174,  187,  180,  189,
+      171,  180,  175,  190,  193,  178,  198,  199,  179,  186,
+
+      200,  201,  180,  187,  201,  189,  205,   23,  190,  205,
+      193,   15,  198,  199,   11,    5,  200,    0,  201,    0,
+        0,    0,    0,  205,  210,  210,  210,  210,  210,  210,
+      210,  211,    0,    0,    0,  211,  211,  212,  212,  212,
+      212,  212,  212,  212,  213,    0,  213,  214,  214,  214,
+      214,  214,  214,  214,  215,  215,  215,  215,  215,  215,
+      215,  216,  216,  216,    0,  216,  216,  216,  217,    0,
+      217,    0,  217,  217,  217,  218,  218,  218,  218,  218,
+        0,  218,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209,  209,  209,  209,  209,  209,  209,  209,  209,
+      209,  209
     } ;
 
 /* The intent behind this definition is that it'll catch
@@ -634,17 +637,8 @@ static yyconst flex_int16_t yy_chk[577] =
 #define YY_RESTORE_YY_MORE_OFFSET
 #line 1 "cmFortranLexer.in.l"
 #line 2 "cmFortranLexer.in.l"
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*-------------------------------------------------------------------------
   Portions of this source have been derived from makedepf90 version 2.8.8,
 
@@ -659,28 +653,21 @@ static yyconst flex_int16_t yy_chk[577] =
 
 This file must be translated to C and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
   flex -i --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
 
 Modify cmFortranLexer.cxx:
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmFortran_yyalloc, cmFortran_yyrealloc, cmFortran_yyfree
+  - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
+  - remove blank lines at end of file
   - remove "yyscanner = NULL" from end of cmFortran_yylex_destroy
   - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-
-Modify cmFortranLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - add cast in cmFortran_yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
 #include "cmStandardLexer.h"
+#undef YY_NO_UNPUT
 
 #define cmFortranLexer_cxx
 #include "cmFortranParser.h" /* Interface to parser object.  */
@@ -696,7 +683,7 @@ Modify cmFortranLexer.h:
 /*--------------------------------------------------------------------------*/
 
 
-#line 689 "cmFortranLexer.cxx"
+#line 696 "cmFortranLexer.cxx"
 
 #define INITIAL 0
 #define free_fmt 1
@@ -729,8 +716,8 @@ struct yyguts_t
     size_t yy_buffer_stack_max; /**< capacity of stack. */
     YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
     char yy_hold_char;
-    yy_size_t yy_n_chars;
-    yy_size_t yyleng_r;
+    int yy_n_chars;
+    int yyleng_r;
     char *yy_c_buf_p;
     int yy_init;
     int yy_start;
@@ -771,23 +758,23 @@ void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
 
 FILE *cmFortran_yyget_in (yyscan_t yyscanner );
 
-void cmFortran_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmFortran_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmFortran_yyget_out (yyscan_t yyscanner );
 
-void cmFortran_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmFortran_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-yy_size_t cmFortran_yyget_leng (yyscan_t yyscanner );
+			int cmFortran_yyget_leng (yyscan_t yyscanner );
 
 char *cmFortran_yyget_text (yyscan_t yyscanner );
 
 int cmFortran_yyget_lineno (yyscan_t yyscanner );
 
-void cmFortran_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmFortran_yyset_lineno (int _line_number ,yyscan_t yyscanner );
 
 int cmFortran_yyget_column  (yyscan_t yyscanner );
 
-void cmFortran_yyset_column (int column_no ,yyscan_t yyscanner );
+void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -801,8 +788,12 @@ extern int cmFortran_yywrap (yyscan_t yyscanner );
 #endif
 #endif
 
+#ifndef YY_NO_UNPUT
+
     static void yyunput (int c,char *buf_ptr  ,yyscan_t yyscanner);
 
+#endif
+
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
 #endif
@@ -836,7 +827,7 @@ static int input (yyscan_t yyscanner );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -844,33 +835,33 @@ static int input (yyscan_t yyscanner );
  */
 #ifndef YY_INPUT
 #define YY_INPUT(buf,result,max_size) \
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
-                { \
-                int c = '*'; \
-                size_t n; \
-                for ( n = 0; n < max_size && \
-                             (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
-                        buf[n] = (char) c; \
-                if ( c == '\n' ) \
-                        buf[n++] = (char) c; \
-                if ( c == EOF && ferror( yyin ) ) \
-                        YY_FATAL_ERROR( "input in flex scanner failed" ); \
-                result = n; \
-                } \
-        else \
-                { \
-                errno=0; \
-                while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
-                        { \
-                        if( errno != EINTR) \
-                                { \
-                                YY_FATAL_ERROR( "input in flex scanner failed" ); \
-                                break; \
-                                } \
-                        errno=0; \
-                        clearerr(yyin); \
-                        } \
-                }\
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+		{ \
+		int c = '*'; \
+		size_t n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else \
+		{ \
+		errno=0; \
+		while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+			{ \
+			if( errno != EINTR) \
+				{ \
+				YY_FATAL_ERROR( "input in flex scanner failed" ); \
+				break; \
+				} \
+			errno=0; \
+			clearerr(yyin); \
+			} \
+		}\
 \
 
 #endif
@@ -915,135 +906,135 @@ extern int cmFortran_yylex (yyscan_t yyscanner);
 
 /* Code executed at the end of each rule. */
 #ifndef YY_BREAK
-#define YY_BREAK break;
+#define YY_BREAK /*LINTED*/break;
 #endif
 
 #define YY_RULE_SETUP \
-        if ( yyleng > 0 ) \
-                YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
-                                (yytext[yyleng - 1] == '\n'); \
-        YY_USER_ACTION
+	if ( yyleng > 0 ) \
+		YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
+				(yytext[yyleng - 1] == '\n'); \
+	YY_USER_ACTION
 
 /** The main scanner function which does all the work.
  */
 YY_DECL
 {
-        yy_state_type yy_current_state;
-        char *yy_cp, *yy_bp;
-        int yy_act;
+	yy_state_type yy_current_state;
+	char *yy_cp, *yy_bp;
+	int yy_act;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if ( !yyg->yy_init )
-                {
-                yyg->yy_init = 1;
+	if ( !yyg->yy_init )
+		{
+		yyg->yy_init = 1;
 
 #ifdef YY_USER_INIT
-                YY_USER_INIT;
+		YY_USER_INIT;
 #endif
 
-                if ( ! yyg->yy_start )
-                        yyg->yy_start = 1;      /* first start state */
+		if ( ! yyg->yy_start )
+			yyg->yy_start = 1;	/* first start state */
 
-                if ( ! yyin )
-                        yyin = stdin;
+		if ( ! yyin )
+			yyin = stdin;
 
-                if ( ! yyout )
-                        yyout = stdout;
+		if ( ! yyout )
+			yyout = stdout;
 
-                if ( ! YY_CURRENT_BUFFER ) {
-                        cmFortran_yyensure_buffer_stack (yyscanner);
-                        YY_CURRENT_BUFFER_LVALUE =
-                                cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-                }
+		if ( ! YY_CURRENT_BUFFER ) {
+			cmFortran_yyensure_buffer_stack (yyscanner);
+			YY_CURRENT_BUFFER_LVALUE =
+				cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+		}
 
-                cmFortran_yy_load_buffer_state(yyscanner );
-                }
+		cmFortran_yy_load_buffer_state(yyscanner );
+		}
 
-        {
-#line 72 "cmFortranLexer.in.l"
+	{
+#line 65 "cmFortranLexer.in.l"
 
 
-#line 956 "cmFortranLexer.cxx"
+#line 967 "cmFortranLexer.cxx"
 
-        for(;;)             /* loops until end-of-file is reached */
-                {
-                yy_cp = yyg->yy_c_buf_p;
+	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = yyg->yy_c_buf_p;
 
-                /* Support of yytext. */
-                *yy_cp = yyg->yy_hold_char;
+		/* Support of yytext. */
+		*yy_cp = yyg->yy_hold_char;
 
-                /* yy_bp points to the position in yy_ch_buf of the start of
-                 * the current run.
-                 */
-                yy_bp = yy_cp;
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
 
-                yy_current_state = yyg->yy_start;
-                yy_current_state += YY_AT_BOL();
+		yy_current_state = yyg->yy_start;
+		yy_current_state += YY_AT_BOL();
 yy_match:
-                do
-                        {
-                        YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
-                        if ( yy_accept[yy_current_state] )
-                                {
-                                yyg->yy_last_accepting_state = yy_current_state;
-                                yyg->yy_last_accepting_cpos = yy_cp;
-                                }
-                        while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                                {
-                                yy_current_state = (int) yy_def[yy_current_state];
-                                if ( yy_current_state >= 173 )
-                                        yy_c = yy_meta[(unsigned int) yy_c];
-                                }
-                        yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-                        ++yy_cp;
-                        }
-                while ( yy_base[yy_current_state] != 535 );
+		do
+			{
+			YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
+			if ( yy_accept[yy_current_state] )
+				{
+				yyg->yy_last_accepting_state = yy_current_state;
+				yyg->yy_last_accepting_cpos = yy_cp;
+				}
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 210 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 583 );
 
 yy_find_action:
-                yy_act = yy_accept[yy_current_state];
-                if ( yy_act == 0 )
-                        { /* have to back up */
-                        yy_cp = yyg->yy_last_accepting_cpos;
-                        yy_current_state = yyg->yy_last_accepting_state;
-                        yy_act = yy_accept[yy_current_state];
-                        }
-
-                YY_DO_BEFORE_ACTION;
-
-do_action:      /* This label is used only to access EOF actions. */
-
-                switch ( yy_act )
-        { /* beginning of action switch */
-                        case 0: /* must back up */
-                        /* undo the effects of YY_DO_BEFORE_ACTION */
-                        *yy_cp = yyg->yy_hold_char;
-                        yy_cp = yyg->yy_last_accepting_cpos;
-                        yy_current_state = yyg->yy_last_accepting_state;
-                        goto yy_find_action;
+		yy_act = yy_accept[yy_current_state];
+		if ( yy_act == 0 )
+			{ /* have to back up */
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			yy_act = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+do_action:	/* This label is used only to access EOF actions. */
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+			case 0: /* must back up */
+			/* undo the effects of YY_DO_BEFORE_ACTION */
+			*yy_cp = yyg->yy_hold_char;
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			goto yy_find_action;
 
 case 1:
 YY_RULE_SETUP
-#line 74 "cmFortranLexer.in.l"
+#line 67 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringStart(yyextra);
   cmFortranParser_SetOldStartcond(yyextra, YY_START);
   BEGIN(str_dq);
 }
-        YY_BREAK
+	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 80 "cmFortranLexer.in.l"
+#line 73 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringStart(yyextra);
   cmFortranParser_SetOldStartcond(yyextra, YY_START);
   BEGIN(str_sq);
 }
-        YY_BREAK
+	YY_BREAK
 case 3:
-#line 87 "cmFortranLexer.in.l"
+#line 80 "cmFortranLexer.in.l"
 case 4:
 YY_RULE_SETUP
-#line 87 "cmFortranLexer.in.l"
+#line 80 "cmFortranLexer.in.l"
 {
   BEGIN(cmFortranParser_GetOldStartcond(yyextra) );
   yylvalp->string = strdup(cmFortranParser_StringEnd(yyextra));
@@ -1051,17 +1042,17 @@ YY_RULE_SETUP
 }
 case 5:
 /* rule 5 can match eol */
-#line 94 "cmFortranLexer.in.l"
+#line 87 "cmFortranLexer.in.l"
 case 6:
 /* rule 6 can match eol */
 YY_RULE_SETUP
-#line 94 "cmFortranLexer.in.l"
+#line 87 "cmFortranLexer.in.l"
 /* Ignore (continued strings, free fmt) */
-        YY_BREAK
+	YY_BREAK
 case 7:
 /* rule 7 can match eol */
 YY_RULE_SETUP
-#line 96 "cmFortranLexer.in.l"
+#line 89 "cmFortranLexer.in.l"
 {
   if (cmFortranParser_GetOldStartcond(yyextra) == fixed_fmt)
     ; /* Ignore (cont. strings, fixed fmt) */
@@ -1070,11 +1061,11 @@ YY_RULE_SETUP
     unput(yytext[strlen(yytext)-1]);
     }
 }
-        YY_BREAK
+	YY_BREAK
 case 8:
 /* rule 8 can match eol */
 YY_RULE_SETUP
-#line 106 "cmFortranLexer.in.l"
+#line 99 "cmFortranLexer.in.l"
 {
   unput ('\n');
   BEGIN(INITIAL);
@@ -1082,29 +1073,29 @@ YY_RULE_SETUP
 }
 case 9:
 YY_RULE_SETUP
-#line 112 "cmFortranLexer.in.l"
+#line 105 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringAppend(yyextra, yytext[0]);
 }
-        YY_BREAK
+	YY_BREAK
 case 10:
 /* rule 10 can match eol */
 YY_RULE_SETUP
-#line 116 "cmFortranLexer.in.l"
+#line 109 "cmFortranLexer.in.l"
 { return EOSTMT; } /* Treat comments like */
 case 11:
 /* rule 11 can match eol */
 YY_RULE_SETUP
-#line 117 "cmFortranLexer.in.l"
+#line 110 "cmFortranLexer.in.l"
 { return EOSTMT; } /* empty lines */
 case 12:
 YY_RULE_SETUP
-#line 119 "cmFortranLexer.in.l"
+#line 112 "cmFortranLexer.in.l"
 { return CPP_LINE_DIRECTIVE; }
 case 13:
 /* rule 13 can match eol */
 YY_RULE_SETUP
-#line 120 "cmFortranLexer.in.l"
+#line 113 "cmFortranLexer.in.l"
 {
   yytext[yyleng-1] = 0;
   yylvalp->string = strdup(strchr(yytext, '<')+1);
@@ -1112,530 +1103,570 @@ YY_RULE_SETUP
 }
 case 14:
 YY_RULE_SETUP
-#line 125 "cmFortranLexer.in.l"
+#line 118 "cmFortranLexer.in.l"
 { return CPP_INCLUDE; }
 case 15:
 YY_RULE_SETUP
-#line 126 "cmFortranLexer.in.l"
+#line 119 "cmFortranLexer.in.l"
 { return F90PPR_INCLUDE; }
 case 16:
 YY_RULE_SETUP
-#line 127 "cmFortranLexer.in.l"
+#line 120 "cmFortranLexer.in.l"
 { return COCO_INCLUDE; }
 case 17:
 YY_RULE_SETUP
-#line 129 "cmFortranLexer.in.l"
+#line 122 "cmFortranLexer.in.l"
 { return CPP_DEFINE; }
 case 18:
 YY_RULE_SETUP
-#line 130 "cmFortranLexer.in.l"
+#line 123 "cmFortranLexer.in.l"
 { return F90PPR_DEFINE; }
 case 19:
 YY_RULE_SETUP
-#line 132 "cmFortranLexer.in.l"
+#line 125 "cmFortranLexer.in.l"
 { return CPP_UNDEF; }
 case 20:
 YY_RULE_SETUP
-#line 133 "cmFortranLexer.in.l"
+#line 126 "cmFortranLexer.in.l"
 { return F90PPR_UNDEF; }
 case 21:
 YY_RULE_SETUP
-#line 135 "cmFortranLexer.in.l"
+#line 128 "cmFortranLexer.in.l"
 { return CPP_IFDEF; }
 case 22:
 YY_RULE_SETUP
-#line 136 "cmFortranLexer.in.l"
+#line 129 "cmFortranLexer.in.l"
 { return CPP_IFNDEF; }
 case 23:
 YY_RULE_SETUP
-#line 137 "cmFortranLexer.in.l"
+#line 130 "cmFortranLexer.in.l"
 { return CPP_IF; }
 case 24:
 YY_RULE_SETUP
-#line 138 "cmFortranLexer.in.l"
+#line 131 "cmFortranLexer.in.l"
 { return CPP_ELIF; }
 case 25:
 YY_RULE_SETUP
-#line 139 "cmFortranLexer.in.l"
+#line 132 "cmFortranLexer.in.l"
 { return CPP_ELSE; }
 case 26:
 YY_RULE_SETUP
-#line 140 "cmFortranLexer.in.l"
+#line 133 "cmFortranLexer.in.l"
 { return CPP_ENDIF; }
 case 27:
 YY_RULE_SETUP
-#line 142 "cmFortranLexer.in.l"
+#line 135 "cmFortranLexer.in.l"
 { return F90PPR_IFDEF; }
 case 28:
 YY_RULE_SETUP
-#line 143 "cmFortranLexer.in.l"
+#line 136 "cmFortranLexer.in.l"
 { return F90PPR_IFNDEF; }
 case 29:
 YY_RULE_SETUP
-#line 144 "cmFortranLexer.in.l"
+#line 137 "cmFortranLexer.in.l"
 { return F90PPR_IF; }
 case 30:
 YY_RULE_SETUP
-#line 145 "cmFortranLexer.in.l"
+#line 138 "cmFortranLexer.in.l"
 { return F90PPR_ELIF; }
 case 31:
 YY_RULE_SETUP
-#line 146 "cmFortranLexer.in.l"
+#line 139 "cmFortranLexer.in.l"
 { return F90PPR_ELSE; }
 case 32:
 YY_RULE_SETUP
-#line 147 "cmFortranLexer.in.l"
+#line 140 "cmFortranLexer.in.l"
 { return F90PPR_ENDIF; }
 /* Line continuations, possible involving comments.  */
 case 33:
 /* rule 33 can match eol */
 YY_RULE_SETUP
-#line 150 "cmFortranLexer.in.l"
+#line 143 "cmFortranLexer.in.l"
 
-        YY_BREAK
+	YY_BREAK
 case 34:
 /* rule 34 can match eol */
 YY_RULE_SETUP
-#line 151 "cmFortranLexer.in.l"
+#line 144 "cmFortranLexer.in.l"
 
-        YY_BREAK
+	YY_BREAK
 case 35:
 YY_RULE_SETUP
-#line 153 "cmFortranLexer.in.l"
+#line 146 "cmFortranLexer.in.l"
 { return COMMA; }
 case 36:
 YY_RULE_SETUP
-#line 155 "cmFortranLexer.in.l"
+#line 148 "cmFortranLexer.in.l"
 { return DCOLON; }
 case 37:
-/* rule 37 can match eol */
 YY_RULE_SETUP
-#line 157 "cmFortranLexer.in.l"
-{ return GARBAGE; }
+#line 149 "cmFortranLexer.in.l"
+{ return COLON; }
 case 38:
+/* rule 38 can match eol */
 YY_RULE_SETUP
-#line 159 "cmFortranLexer.in.l"
-{ return ASSIGNMENT_OP; }
+#line 151 "cmFortranLexer.in.l"
+{ return GARBAGE; }
 case 39:
 YY_RULE_SETUP
-#line 161 "cmFortranLexer.in.l"
+#line 153 "cmFortranLexer.in.l"
+{ return ASSIGNMENT_OP; }
+case 40:
+YY_RULE_SETUP
+#line 155 "cmFortranLexer.in.l"
+{ return END; }
+case 41:
+YY_RULE_SETUP
+#line 156 "cmFortranLexer.in.l"
+{ return INCLUDE; }
+case 42:
+YY_RULE_SETUP
+#line 157 "cmFortranLexer.in.l"
+{ return INTERFACE; }
+case 43:
+YY_RULE_SETUP
+#line 158 "cmFortranLexer.in.l"
+{ return MODULE; }
+case 44:
+YY_RULE_SETUP
+#line 159 "cmFortranLexer.in.l"
+{ return SUBMODULE; }
+case 45:
+YY_RULE_SETUP
+#line 160 "cmFortranLexer.in.l"
+{ return USE; }
+case 46:
+YY_RULE_SETUP
+#line 162 "cmFortranLexer.in.l"
 {
   yylvalp->string = strdup(yytext);
   return WORD;
 }
-case 40:
+case 47:
 YY_RULE_SETUP
-#line 166 "cmFortranLexer.in.l"
-{ return GARBAGE; }
-case 41:
-/* rule 41 can match eol */
+#line 167 "cmFortranLexer.in.l"
+{ return LPAREN; }
+case 48:
 YY_RULE_SETUP
 #line 168 "cmFortranLexer.in.l"
+{ return RPAREN; }
+case 49:
+YY_RULE_SETUP
+#line 170 "cmFortranLexer.in.l"
+{ return GARBAGE; }
+case 50:
+/* rule 50 can match eol */
+YY_RULE_SETUP
+#line 172 "cmFortranLexer.in.l"
 { return EOSTMT; }
-case 42:
+case 51:
 YY_RULE_SETUP
-#line 171 "cmFortranLexer.in.l"
+#line 175 "cmFortranLexer.in.l"
 /* Ignore */
-        YY_BREAK
-case 43:
-/* rule 43 can match eol */
+	YY_BREAK
+case 52:
+/* rule 52 can match eol */
 YY_RULE_SETUP
-#line 172 "cmFortranLexer.in.l"
+#line 176 "cmFortranLexer.in.l"
 /* Ignore line-endings preceded by \ */
-        YY_BREAK
-case 44:
+	YY_BREAK
+case 53:
 YY_RULE_SETUP
-#line 174 "cmFortranLexer.in.l"
+#line 178 "cmFortranLexer.in.l"
 { return *yytext; }
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(free_fmt):
 case YY_STATE_EOF(fixed_fmt):
 case YY_STATE_EOF(str_sq):
 case YY_STATE_EOF(str_dq):
-#line 176 "cmFortranLexer.in.l"
+#line 180 "cmFortranLexer.in.l"
 {
   if(!cmFortranParser_FilePop(yyextra) )
     {
     return YY_NULL;
     }
 }
-        YY_BREAK
-case 45:
+	YY_BREAK
+case 54:
 YY_RULE_SETUP
-#line 183 "cmFortranLexer.in.l"
+#line 187 "cmFortranLexer.in.l"
 ECHO;
-        YY_BREAK
-#line 1291 "cmFortranLexer.cxx"
-
-        case YY_END_OF_BUFFER:
-                {
-                /* Amount of text matched not including the EOB char. */
-                int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
-
-                /* Undo the effects of YY_DO_BEFORE_ACTION. */
-                *yy_cp = yyg->yy_hold_char;
-                YY_RESTORE_YY_MORE_OFFSET
-
-                if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
-                        {
-                        /* We're scanning a new file or input source.  It's
-                         * possible that this happened because the user
-                         * just pointed yyin at a new source and called
-                         * cmFortran_yylex().  If so, then we have to assure
-                         * consistency between YY_CURRENT_BUFFER and our
-                         * globals.  Here is the right place to do so, because
-                         * this is the first action (other than possibly a
-                         * back-up) that will match for the new input source.
-                         */
-                        yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-                        YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
-                        YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
-                        }
-
-                /* Note that here we test for yy_c_buf_p "<=" to the position
-                 * of the first EOB in the buffer, since yy_c_buf_p will
-                 * already have been incremented past the NUL character
-                 * (since all states make transitions on EOB to the
-                 * end-of-buffer state).  Contrast this with the test
-                 * in input().
-                 */
-                if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-                        { /* This was really a NUL. */
-                        yy_state_type yy_next_state;
-
-                        yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
-
-                        yy_current_state = yy_get_previous_state( yyscanner );
-
-                        /* Okay, we're now positioned to make the NUL
-                         * transition.  We couldn't have
-                         * yy_get_previous_state() go ahead and do it
-                         * for us because it doesn't know how to deal
-                         * with the possibility of jamming (and we don't
-                         * want to build jamming into it because then it
-                         * will run more slowly).
-                         */
-
-                        yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
-
-                        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-
-                        if ( yy_next_state )
-                                {
-                                /* Consume the NUL. */
-                                yy_cp = ++yyg->yy_c_buf_p;
-                                yy_current_state = yy_next_state;
-                                goto yy_match;
-                                }
-
-                        else
-                                {
-                                yy_cp = yyg->yy_c_buf_p;
-                                goto yy_find_action;
-                                }
-                        }
-
-                else switch ( yy_get_next_buffer( yyscanner ) )
-                        {
-                        case EOB_ACT_END_OF_FILE:
-                                {
-                                yyg->yy_did_buffer_switch_on_eof = 0;
-
-                                if ( cmFortran_yywrap(yyscanner ) )
-                                        {
-                                        /* Note: because we've taken care in
-                                         * yy_get_next_buffer() to have set up
-                                         * yytext, we can now set up
-                                         * yy_c_buf_p so that if some total
-                                         * hoser (like flex itself) wants to
-                                         * call the scanner after we return the
-                                         * YY_NULL, it'll still work - another
-                                         * YY_NULL will get returned.
-                                         */
-                                        yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
-
-                                        yy_act = YY_STATE_EOF(YY_START);
-                                        goto do_action;
-                                        }
-
-                                else
-                                        {
-                                        if ( ! yyg->yy_did_buffer_switch_on_eof )
-                                                YY_NEW_FILE;
-                                        }
-                                break;
-                                }
-
-                        case EOB_ACT_CONTINUE_SCAN:
-                                yyg->yy_c_buf_p =
-                                        yyg->yytext_ptr + yy_amount_of_matched_text;
-
-                                yy_current_state = yy_get_previous_state( yyscanner );
-
-                                yy_cp = yyg->yy_c_buf_p;
-                                yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-                                goto yy_match;
-
-                        case EOB_ACT_LAST_MATCH:
-                                yyg->yy_c_buf_p =
-                                &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
-
-                                yy_current_state = yy_get_previous_state( yyscanner );
-
-                                yy_cp = yyg->yy_c_buf_p;
-                                yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-                                goto yy_find_action;
-                        }
-                break;
-                }
-
-        default:
-                YY_FATAL_ERROR(
-                        "fatal flex scanner internal error--no action found" );
-        } /* end of action switch */
-                } /* end of scanning one token */
-        } /* end of user's declarations */
+	YY_BREAK
+#line 1347 "cmFortranLexer.cxx"
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = yyg->yy_hold_char;
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * cmFortran_yylex().  If so, then we have to assure
+			 * consistency between YY_CURRENT_BUFFER and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state( yyscanner );
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
+
+			yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++yyg->yy_c_buf_p;
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = yyg->yy_c_buf_p;
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer( yyscanner ) )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				yyg->yy_did_buffer_switch_on_eof = 0;
+
+				if ( cmFortran_yywrap(yyscanner ) )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				yyg->yy_c_buf_p =
+					yyg->yytext_ptr + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				yyg->yy_c_buf_p =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+	} /* end of user's declarations */
 } /* end of cmFortran_yylex */
 
 /* yy_get_next_buffer - try to read in a new buffer
  *
  * Returns a code representing an action:
- *      EOB_ACT_LAST_MATCH -
- *      EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- *      EOB_ACT_END_OF_FILE - end of file
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
  */
 static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
-        char *source = yyg->yytext_ptr;
-        int number_to_move, i;
-        int ret_val;
-
-        if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
-                YY_FATAL_ERROR(
-                "fatal flex scanner internal error--end of buffer missed" );
-
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
-                { /* Don't try to fill the buffer, so this is an EOF. */
-                if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
-                        {
-                        /* We matched a single character, the EOB, so
-                         * treat this as a final EOF.
-                         */
-                        return EOB_ACT_END_OF_FILE;
-                        }
-
-                else
-                        {
-                        /* We matched some text prior to the EOB, first
-                         * process it.
-                         */
-                        return EOB_ACT_LAST_MATCH;
-                        }
-                }
-
-        /* Try to read more data. */
-
-        /* First move last chars to start of buffer. */
-        number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
-
-        for ( i = 0; i < number_to_move; ++i )
-                *(dest++) = *(source++);
-
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
-                /* don't do the read, it's not guaranteed to return an EOF,
-                 * just force an EOF
-                 */
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
-
-        else
-                {
-                        yy_size_t num_to_read =
-                        YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
-
-                while ( num_to_read <= 0 )
-                        { /* Not enough room in the buffer - grow it. */
-
-                        /* just a shorter name for the current buffer */
-                        YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
-
-                        int yy_c_buf_p_offset =
-                                (int) (yyg->yy_c_buf_p - b->yy_ch_buf);
-
-                        if ( b->yy_is_our_buffer )
-                                {
-                                yy_size_t new_size = b->yy_buf_size * 2;
-
-                                if ( new_size <= 0 )
-                                        b->yy_buf_size += b->yy_buf_size / 8;
-                                else
-                                        b->yy_buf_size *= 2;
-
-                                b->yy_ch_buf = (char *)
-                                        /* Include room in for 2 EOB chars. */
-                                        cmFortran_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
-                                }
-                        else
-                                /* Can't grow it, we don't own it. */
-                                b->yy_ch_buf = 0;
-
-                        if ( ! b->yy_ch_buf )
-                                YY_FATAL_ERROR(
-                                "fatal error - scanner input buffer overflow" );
-
-                        yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
-
-                        num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
-                                                number_to_move - 1;
-
-                        }
-
-                if ( num_to_read > YY_READ_BUF_SIZE )
-                        num_to_read = YY_READ_BUF_SIZE;
-
-                /* Read in more data. */
-                YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
-                        yyg->yy_n_chars, num_to_read );
-
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        if ( yyg->yy_n_chars == 0 )
-                {
-                if ( number_to_move == YY_MORE_ADJ )
-                        {
-                        ret_val = EOB_ACT_END_OF_FILE;
-                        cmFortran_yyrestart(yyin  ,yyscanner);
-                        }
-
-                else
-                        {
-                        ret_val = EOB_ACT_LAST_MATCH;
-                        YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
-                                YY_BUFFER_EOF_PENDING;
-                        }
-                }
-
-        else
-                ret_val = EOB_ACT_CONTINUE_SCAN;
-
-        if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
-                /* Extend the array by 50%, plus the number we really need. */
-                yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
-                YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmFortran_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
-                if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-                        YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
-        }
-
-        yyg->yy_n_chars += number_to_move;
-        YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
-        YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
-
-        yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+	char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+	char *source = yyg->yytext_ptr;
+	yy_size_t number_to_move, i;
+	int ret_val;
+
+	if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
+
+	else
+		{
+			int num_to_read =
+			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
+
+			int yy_c_buf_p_offset =
+				(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					cmFortran_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = NULL;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+						number_to_move - 1;
+
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+			yyg->yy_n_chars, num_to_read );
+
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	if ( yyg->yy_n_chars == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			cmFortran_yyrestart(yyin  ,yyscanner);
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmFortran_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
+	yyg->yy_n_chars += number_to_move;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
+
+	yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
 
-        return ret_val;
+	return ret_val;
 }
 
 /* yy_get_previous_state - get the state just before the EOB char was reached */
 
     static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
 {
-        yy_state_type yy_current_state;
-        char *yy_cp;
+	yy_state_type yy_current_state;
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        yy_current_state = yyg->yy_start;
-        yy_current_state += YY_AT_BOL();
-
-        for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
-                {
-                YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
-                if ( yy_accept[yy_current_state] )
-                        {
-                        yyg->yy_last_accepting_state = yy_current_state;
-                        yyg->yy_last_accepting_cpos = yy_cp;
-                        }
-                while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                        {
-                        yy_current_state = (int) yy_def[yy_current_state];
-                        if ( yy_current_state >= 173 )
-                                yy_c = yy_meta[(unsigned int) yy_c];
-                        }
-                yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-                }
-
-        return yy_current_state;
+	yy_current_state = yyg->yy_start;
+	yy_current_state += YY_AT_BOL();
+
+	for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
+		{
+		YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+		if ( yy_accept[yy_current_state] )
+			{
+			yyg->yy_last_accepting_state = yy_current_state;
+			yyg->yy_last_accepting_cpos = yy_cp;
+			}
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 210 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+		}
+
+	return yy_current_state;
 }
 
 /* yy_try_NUL_trans - try to make a transition on the NUL character
  *
  * synopsis
- *      next_state = yy_try_NUL_trans( current_state );
+ *	next_state = yy_try_NUL_trans( current_state );
  */
     static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state , yyscan_t yyscanner)
 {
-        int yy_is_jam;
+	int yy_is_jam;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
-        char *yy_cp = yyg->yy_c_buf_p;
-
-        YY_CHAR yy_c = 1;
-        if ( yy_accept[yy_current_state] )
-                {
-                yyg->yy_last_accepting_state = yy_current_state;
-                yyg->yy_last_accepting_cpos = yy_cp;
-                }
-        while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                {
-                yy_current_state = (int) yy_def[yy_current_state];
-                if ( yy_current_state >= 173 )
-                        yy_c = yy_meta[(unsigned int) yy_c];
-                }
-        yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-        yy_is_jam = (yy_current_state == 172);
-
-        (void)yyg;
-        return yy_is_jam ? 0 : yy_current_state;
+	char *yy_cp = yyg->yy_c_buf_p;
+
+	YY_CHAR yy_c = 1;
+	if ( yy_accept[yy_current_state] )
+		{
+		yyg->yy_last_accepting_state = yy_current_state;
+		yyg->yy_last_accepting_cpos = yy_cp;
+		}
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 210 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+	yy_is_jam = (yy_current_state == 209);
+
+	(void)yyg;
+	return yy_is_jam ? 0 : yy_current_state;
 }
 
+#ifndef YY_NO_UNPUT
+
     static void yyunput (int c, char * yy_bp , yyscan_t yyscanner)
 {
-        char *yy_cp;
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
     yy_cp = yyg->yy_c_buf_p;
 
-        /* undo effects of setting up yytext */
-        *yy_cp = yyg->yy_hold_char;
+	/* undo effects of setting up yytext */
+	*yy_cp = yyg->yy_hold_char;
 
-        if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-                { /* need to shift things up to make room */
-                /* +2 for EOB chars. */
-                yy_size_t number_to_move = yyg->yy_n_chars + 2;
-                char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
-                                        YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
-                char *source =
-                                &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+		{ /* need to shift things up to make room */
+		/* +2 for EOB chars. */
+		int number_to_move = yyg->yy_n_chars + 2;
+		char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+		char *source =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
 
-                while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-                        *--dest = *--source;
+		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			*--dest = *--source;
 
-                yy_cp += (int) (dest - source);
-                yy_bp += (int) (dest - source);
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
-                        yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+		yy_cp += (int) (dest - source);
+		yy_bp += (int) (dest - source);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+			yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
 
-                if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-                        YY_FATAL_ERROR( "flex scanner push-back overflow" );
-                }
+		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+			YY_FATAL_ERROR( "flex scanner push-back overflow" );
+		}
 
-        *--yy_cp = (char) c;
+	*--yy_cp = (char) c;
 
-        yyg->yytext_ptr = yy_bp;
-        yyg->yy_hold_char = *yy_cp;
-        yyg->yy_c_buf_p = yy_cp;
+	yyg->yytext_ptr = yy_bp;
+	yyg->yy_hold_char = *yy_cp;
+	yyg->yy_c_buf_p = yy_cp;
 }
 
+#endif
+
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (yyscan_t yyscanner)
@@ -1644,74 +1675,74 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 #endif
 
 {
-        int c;
+	int c;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        *yyg->yy_c_buf_p = yyg->yy_hold_char;
-
-        if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
-                {
-                /* yy_c_buf_p now points to the character we want to return.
-                 * If this occurs *before* the EOB characters, then it's a
-                 * valid NUL; if not, then we've hit the end of the buffer.
-                 */
-                if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-                        /* This was really a NUL. */
-                        *yyg->yy_c_buf_p = '\0';
-
-                else
-                        { /* need more input */
-                        yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
-                        ++yyg->yy_c_buf_p;
-
-                        switch ( yy_get_next_buffer( yyscanner ) )
-                                {
-                                case EOB_ACT_LAST_MATCH:
-                                        /* This happens because yy_g_n_b()
-                                         * sees that we've accumulated a
-                                         * token and flags that we need to
-                                         * try matching the token before
-                                         * proceeding.  But for input(),
-                                         * there's no matching to consider.
-                                         * So convert the EOB_ACT_LAST_MATCH
-                                         * to EOB_ACT_END_OF_FILE.
-                                         */
-
-                                        /* Reset buffer status. */
-                                        cmFortran_yyrestart(yyin ,yyscanner);
-
-                                        /*FALLTHROUGH*/
-
-                                case EOB_ACT_END_OF_FILE:
-                                        {
-                                        if ( cmFortran_yywrap(yyscanner ) )
-                                                return EOF;
-
-                                        if ( ! yyg->yy_did_buffer_switch_on_eof )
-                                                YY_NEW_FILE;
+	*yyg->yy_c_buf_p = yyg->yy_hold_char;
+
+	if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			/* This was really a NUL. */
+			*yyg->yy_c_buf_p = '\0';
+
+		else
+			{ /* need more input */
+			int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+			++yyg->yy_c_buf_p;
+
+			switch ( yy_get_next_buffer( yyscanner ) )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					cmFortran_yyrestart(yyin ,yyscanner);
+
+					/*FALLTHROUGH*/
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( cmFortran_yywrap(yyscanner ) )
+						return 0;
+
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
 #ifdef __cplusplus
-                                        return yyinput(yyscanner);
+					return yyinput(yyscanner);
 #else
-                                        return input(yyscanner);
+					return input(yyscanner);
 #endif
-                                        }
+					}
 
-                                case EOB_ACT_CONTINUE_SCAN:
-                                        yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
-                                        break;
-                                }
-                        }
-                }
+				case EOB_ACT_CONTINUE_SCAN:
+					yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
+					break;
+				}
+			}
+		}
 
-        c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
-        *yyg->yy_c_buf_p = '\0';        /* preserve yytext */
-        yyg->yy_hold_char = *++yyg->yy_c_buf_p;
+	c = *(unsigned char *) yyg->yy_c_buf_p;	/* cast for 8-bit char's */
+	*yyg->yy_c_buf_p = '\0';	/* preserve yytext */
+	yyg->yy_hold_char = *++yyg->yy_c_buf_p;
 
-        YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n');
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n');
 
-        return c;
+	return c;
 }
-#endif  /* ifndef YY_NO_INPUT */
+#endif	/* ifndef YY_NO_INPUT */
 
 /** Immediately switch to a different input stream.
  * @param input_file A readable stream.
@@ -1722,14 +1753,14 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if ( ! YY_CURRENT_BUFFER ){
+	if ( ! YY_CURRENT_BUFFER ){
         cmFortran_yyensure_buffer_stack (yyscanner);
-                YY_CURRENT_BUFFER_LVALUE =
+		YY_CURRENT_BUFFER_LVALUE =
             cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-        }
+	}
 
-        cmFortran_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
-        cmFortran_yy_load_buffer_state(yyscanner );
+	cmFortran_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
+	cmFortran_yy_load_buffer_state(yyscanner );
 }
 
 /** Switch to a different input buffer.
@@ -1740,41 +1771,41 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        /* TODO. We should be able to replace this entire function body
-         * with
-         *              cmFortran_yypop_buffer_state();
-         *              cmFortran_yypush_buffer_state(new_buffer);
+	/* TODO. We should be able to replace this entire function body
+	 * with
+	 *		cmFortran_yypop_buffer_state();
+	 *		cmFortran_yypush_buffer_state(new_buffer);
      */
-        cmFortran_yyensure_buffer_stack (yyscanner);
-        if ( YY_CURRENT_BUFFER == new_buffer )
-                return;
-
-        if ( YY_CURRENT_BUFFER )
-                {
-                /* Flush out information for old buffer. */
-                *yyg->yy_c_buf_p = yyg->yy_hold_char;
-                YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        YY_CURRENT_BUFFER_LVALUE = new_buffer;
-        cmFortran_yy_load_buffer_state(yyscanner );
-
-        /* We don't actually know whether we did this switch during
-         * EOF (cmFortran_yywrap()) processing, but the only time this flag
-         * is looked at is after cmFortran_yywrap() is called, so it's safe
-         * to go ahead and always set it.
-         */
-        yyg->yy_did_buffer_switch_on_eof = 1;
+	cmFortran_yyensure_buffer_stack (yyscanner);
+	if ( YY_CURRENT_BUFFER == new_buffer )
+		return;
+
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+	cmFortran_yy_load_buffer_state(yyscanner );
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (cmFortran_yywrap()) processing, but the only time this flag
+	 * is looked at is after cmFortran_yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-        yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-        yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
-        yyg->yy_hold_char = *yyg->yy_c_buf_p;
+	yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+	yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	yyg->yy_hold_char = *yyg->yy_c_buf_p;
 }
 
 /** Allocate and initialize an input buffer state.
@@ -1785,26 +1816,26 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
  */
     YY_BUFFER_STATE cmFortran_yy_create_buffer  (FILE * file, int  size , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
+	YY_BUFFER_STATE b;
 
-        b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-        if ( ! b )
-                YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
+	b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
 
-        b->yy_buf_size = size;
+	b->yy_buf_size = (yy_size_t)size;
 
-        /* yy_ch_buf has to be 2 characters longer than the size given because
-         * we need to put in 2 end-of-buffer characters.
-         */
-        b->yy_ch_buf = (char *) cmFortran_yyalloc(b->yy_buf_size + 2 ,yyscanner );
-        if ( ! b->yy_ch_buf )
-                YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) cmFortran_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
 
-        b->yy_is_our_buffer = 1;
+	b->yy_is_our_buffer = 1;
 
-        cmFortran_yy_init_buffer(b,file ,yyscanner);
+	cmFortran_yy_init_buffer(b,file ,yyscanner);
 
-        return b;
+	return b;
 }
 
 /** Destroy the buffer.
@@ -1815,16 +1846,16 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if ( ! b )
-                return;
+	if ( ! b )
+		return;
 
-        if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
-                YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
 
-        if ( b->yy_is_our_buffer )
-                cmFortran_yyfree((void *) b->yy_ch_buf ,yyscanner );
+	if ( b->yy_is_our_buffer )
+		cmFortran_yyfree((void *) b->yy_ch_buf ,yyscanner );
 
-        cmFortran_yyfree((void *) b ,yyscanner );
+	cmFortran_yyfree((void *) b ,yyscanner );
 }
 
 /* Initializes or reinitializes a buffer.
@@ -1834,13 +1865,13 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
     static void cmFortran_yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file , yyscan_t yyscanner)
 
 {
-        int oerrno = errno;
+	int oerrno = errno;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        cmFortran_yy_flush_buffer(b ,yyscanner);
+	cmFortran_yy_flush_buffer(b ,yyscanner);
 
-        b->yy_input_file = file;
-        b->yy_fill_buffer = 1;
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
 
     /* If b is the current buffer, then cmFortran_yy_init_buffer was _probably_
      * called from cmFortran_yyrestart() or through yy_get_next_buffer.
@@ -1853,7 +1884,7 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
 
         b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
 
-        errno = oerrno;
+	errno = oerrno;
 }
 
 /** Discard all buffered characters. On the next scan, YY_INPUT will be called.
@@ -1863,25 +1894,25 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
     void cmFortran_yy_flush_buffer (YY_BUFFER_STATE  b , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if ( ! b )
-                return;
+	if ( ! b )
+		return;
 
-        b->yy_n_chars = 0;
+	b->yy_n_chars = 0;
 
-        /* We always need two end-of-buffer characters.  The first causes
-         * a transition to the end-of-buffer state.  The second causes
-         * a jam in that state.
-         */
-        b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
-        b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
 
-        b->yy_buf_pos = &b->yy_ch_buf[0];
+	b->yy_buf_pos = &b->yy_ch_buf[0];
 
-        b->yy_at_bol = 1;
-        b->yy_buffer_status = YY_BUFFER_NEW;
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
 
-        if ( b == YY_CURRENT_BUFFER )
-                cmFortran_yy_load_buffer_state(yyscanner );
+	if ( b == YY_CURRENT_BUFFER )
+		cmFortran_yy_load_buffer_state(yyscanner );
 }
 
 /** Pushes the new state onto the stack. The new state becomes
@@ -1893,28 +1924,28 @@ static void cmFortran_yy_load_buffer_state  (yyscan_t yyscanner)
 void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if (new_buffer == NULL)
-                return;
-
-        cmFortran_yyensure_buffer_stack(yyscanner);
-
-        /* This block is copied from cmFortran_yy_switch_to_buffer. */
-        if ( YY_CURRENT_BUFFER )
-                {
-                /* Flush out information for old buffer. */
-                *yyg->yy_c_buf_p = yyg->yy_hold_char;
-                YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        /* Only push if top exists. Otherwise, replace top. */
-        if (YY_CURRENT_BUFFER)
-                yyg->yy_buffer_stack_top++;
-        YY_CURRENT_BUFFER_LVALUE = new_buffer;
-
-        /* copied from cmFortran_yy_switch_to_buffer. */
-        cmFortran_yy_load_buffer_state(yyscanner );
-        yyg->yy_did_buffer_switch_on_eof = 1;
+	if (new_buffer == NULL)
+		return;
+
+	cmFortran_yyensure_buffer_stack(yyscanner);
+
+	/* This block is copied from cmFortran_yy_switch_to_buffer. */
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	/* Only push if top exists. Otherwise, replace top. */
+	if (YY_CURRENT_BUFFER)
+		yyg->yy_buffer_stack_top++;
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+	/* copied from cmFortran_yy_switch_to_buffer. */
+	cmFortran_yy_load_buffer_state(yyscanner );
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 /** Removes and deletes the top of the stack, if present.
@@ -1924,18 +1955,18 @@ void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscan
 void cmFortran_yypop_buffer_state (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if (!YY_CURRENT_BUFFER)
-                return;
-
-        cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
-        YY_CURRENT_BUFFER_LVALUE = NULL;
-        if (yyg->yy_buffer_stack_top > 0)
-                --yyg->yy_buffer_stack_top;
-
-        if (YY_CURRENT_BUFFER) {
-                cmFortran_yy_load_buffer_state(yyscanner );
-                yyg->yy_did_buffer_switch_on_eof = 1;
-        }
+	if (!YY_CURRENT_BUFFER)
+		return;
+
+	cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+	YY_CURRENT_BUFFER_LVALUE = NULL;
+	if (yyg->yy_buffer_stack_top > 0)
+		--yyg->yy_buffer_stack_top;
+
+	if (YY_CURRENT_BUFFER) {
+		cmFortran_yy_load_buffer_state(yyscanner );
+		yyg->yy_did_buffer_switch_on_eof = 1;
+	}
 }
 
 /* Allocates the stack if it does not exist.
@@ -1943,46 +1974,46 @@ void cmFortran_yypop_buffer_state (yyscan_t yyscanner)
  */
 static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
 {
-        yy_size_t num_to_alloc;
+	int num_to_alloc;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if (!yyg->yy_buffer_stack) {
+	if (!yyg->yy_buffer_stack) {
 
-                /* First allocation is just for 2 elements, since we don't know if this
-                 * scanner will even need a stack. We use 2 instead of 1 to avoid an
-                 * immediate realloc on the next call.
+		/* First allocation is just for 2 elements, since we don't know if this
+		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
+		 * immediate realloc on the next call.
          */
-                num_to_alloc = 1;
-                yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyalloc
-                                                                (num_to_alloc * sizeof(struct yy_buffer_state*)
-                                                                , yyscanner);
-                if ( ! yyg->yy_buffer_stack )
-                        YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
-
-                memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
-
-                yyg->yy_buffer_stack_max = num_to_alloc;
-                yyg->yy_buffer_stack_top = 0;
-                return;
-        }
-
-        if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
-
-                /* Increase the buffer to prepare for a possible push. */
-                int grow_size = 8 /* arbitrary grow size */;
-
-                num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
-                yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyrealloc
-                                                                (yyg->yy_buffer_stack,
-                                                                num_to_alloc * sizeof(struct yy_buffer_state*)
-                                                                , yyscanner);
-                if ( ! yyg->yy_buffer_stack )
-                        YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
-
-                /* zero only the new slots.*/
-                memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
-                yyg->yy_buffer_stack_max = num_to_alloc;
-        }
+      num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyalloc
+								(num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
+
+		memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+		yyg->yy_buffer_stack_max = num_to_alloc;
+		yyg->yy_buffer_stack_top = 0;
+		return;
+	}
+
+	if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
+
+		/* Increase the buffer to prepare for a possible push. */
+		yy_size_t grow_size = 8 /* arbitrary grow size */;
+
+		num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyrealloc
+								(yyg->yy_buffer_stack,
+								num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
+
+		/* zero only the new slots.*/
+		memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
+		yyg->yy_buffer_stack_max = num_to_alloc;
+	}
 }
 
 /** Setup the input buffer state to scan directly from a user-specified character buffer.
@@ -1993,31 +2024,31 @@ static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
  */
 YY_BUFFER_STATE cmFortran_yy_scan_buffer  (char * base, yy_size_t  size , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
-
-        if ( size < 2 ||
-             base[size-2] != YY_END_OF_BUFFER_CHAR ||
-             base[size-1] != YY_END_OF_BUFFER_CHAR )
-                /* They forgot to leave room for the EOB's. */
-                return 0;
-
-        b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-        if ( ! b )
-                YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_buffer()" );
-
-        b->yy_buf_size = size - 2;      /* "- 2" to take care of EOB's */
-        b->yy_buf_pos = b->yy_ch_buf = base;
-        b->yy_is_our_buffer = 0;
-        b->yy_input_file = 0;
-        b->yy_n_chars = b->yy_buf_size;
-        b->yy_is_interactive = 0;
-        b->yy_at_bol = 1;
-        b->yy_fill_buffer = 0;
-        b->yy_buffer_status = YY_BUFFER_NEW;
-
-        cmFortran_yy_switch_to_buffer(b ,yyscanner );
-
-        return b;
+	YY_BUFFER_STATE b;
+
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return NULL;
+
+	b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = NULL;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	cmFortran_yy_switch_to_buffer(b ,yyscanner );
+
+	return b;
 }
 
 /** Setup the input buffer state to scan a string. The next call to cmFortran_yylex() will
@@ -2031,7 +2062,7 @@ YY_BUFFER_STATE cmFortran_yy_scan_buffer  (char * base, yy_size_t  size , yyscan
 YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
 {
 
-        return cmFortran_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner);
+	return cmFortran_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
 }
 
 /** Setup the input buffer state to scan the given bytes. The next call to cmFortran_yylex() will
@@ -2041,62 +2072,64 @@ YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char * yystr , yyscan_t yyscan
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE cmFortran_yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE cmFortran_yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
-        char *buf;
-        yy_size_t n;
-        yy_size_t i;
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	yy_size_t i;
 
-        /* Get memory for full buffer, including space for trailing EOB's. */
-        n = _yybytes_len + 2;
-        buf = (char *) cmFortran_yyalloc(n ,yyscanner );
-        if ( ! buf )
-                YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_bytes()" );
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = (yy_size_t) _yybytes_len + 2;
+	buf = (char *) cmFortran_yyalloc(n ,yyscanner );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_bytes()" );
 
-        for ( i = 0; i < _yybytes_len; ++i )
-                buf[i] = yybytes[i];
+	for ( i = 0; i < (size_t)_yybytes_len; ++i )
+		buf[i] = yybytes[i];
 
-        buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
+	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-        b = cmFortran_yy_scan_buffer(buf,n ,yyscanner);
-        if ( ! b )
-                YY_FATAL_ERROR( "bad buffer in cmFortran_yy_scan_bytes()" );
+	b = cmFortran_yy_scan_buffer(buf,n ,yyscanner);
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in cmFortran_yy_scan_bytes()" );
 
-        /* It's okay to grow etc. this buffer, and we should throw it
-         * away when we're done.
-         */
-        b->yy_is_our_buffer = 1;
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
 
-        return b;
+	return b;
 }
 
 #ifndef YY_EXIT_FAILURE
 #define YY_EXIT_FAILURE 2
 #endif
 
-static void yy_fatal_error (yyconst char* msg , yyscan_t)
+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
 {
-        (void) fprintf( stderr, "%s\n", msg );
-        exit( YY_EXIT_FAILURE );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
 }
 
 /* Redefine yyless() so it works in section 3 code. */
 
 #undef yyless
 #define yyless(n) \
-        do \
-                { \
-                /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-                yytext[yyleng] = yyg->yy_hold_char; \
-                yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
-                yyg->yy_hold_char = *yyg->yy_c_buf_p; \
-                *yyg->yy_c_buf_p = '\0'; \
-                yyleng = yyless_macro_arg; \
-                } \
-        while ( 0 )
+		yytext[yyleng] = yyg->yy_hold_char; \
+		yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
+		yyg->yy_hold_char = *yyg->yy_c_buf_p; \
+		*yyg->yy_c_buf_p = '\0'; \
+		yyleng = yyless_macro_arg; \
+		} \
+	while ( 0 )
 
 /* Accessor  methods (get/set functions) to struct members. */
 
@@ -2156,7 +2189,7 @@ FILE *cmFortran_yyget_out  (yyscan_t yyscanner)
 /** Get the length of the current token.
  * @param yyscanner The scanner object.
  */
-yy_size_t cmFortran_yyget_leng  (yyscan_t yyscanner)
+int cmFortran_yyget_leng  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
     return yyleng;
@@ -2183,10 +2216,10 @@ void cmFortran_yyset_extra (YY_EXTRA_TYPE  user_defined , yyscan_t yyscanner)
 }
 
 /** Set the current line number.
- * @param line_number The line number to set.
+ * @param _line_number line number
  * @param yyscanner The scanner object.
  */
-void cmFortran_yyset_lineno (int  line_number , yyscan_t yyscanner)
+void cmFortran_yyset_lineno (int  _line_number , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
@@ -2194,14 +2227,14 @@ void cmFortran_yyset_lineno (int  line_number , yyscan_t yyscanner)
         if (! YY_CURRENT_BUFFER )
            YY_FATAL_ERROR( "cmFortran_yyset_lineno called with no buffer" );
 
-    yylineno = line_number;
+    yylineno = _line_number;
 }
 
 /** Set the current column.
- * @param column_no The column number to set.
+ * @param _column_no column number
  * @param yyscanner The scanner object.
  */
-void cmFortran_yyset_column (int  column_no , yyscan_t yyscanner)
+void cmFortran_yyset_column (int  _column_no , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
@@ -2209,25 +2242,25 @@ void cmFortran_yyset_column (int  column_no , yyscan_t yyscanner)
         if (! YY_CURRENT_BUFFER )
            YY_FATAL_ERROR( "cmFortran_yyset_column called with no buffer" );
 
-    yycolumn = column_no;
+    yycolumn = _column_no;
 }
 
 /** Set the input stream. This does not discard the current
  * input buffer.
- * @param in_str A readable stream.
+ * @param _in_str A readable stream.
  * @param yyscanner The scanner object.
  * @see cmFortran_yy_switch_to_buffer
  */
-void cmFortran_yyset_in (FILE *  in_str , yyscan_t yyscanner)
+void cmFortran_yyset_in (FILE *  _in_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyin = in_str ;
+    yyin = _in_str ;
 }
 
-void cmFortran_yyset_out (FILE *  out_str , yyscan_t yyscanner)
+void cmFortran_yyset_out (FILE *  _out_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyout = out_str ;
+    yyout = _out_str ;
 }
 
 int cmFortran_yyget_debug  (yyscan_t yyscanner)
@@ -2236,10 +2269,10 @@ int cmFortran_yyget_debug  (yyscan_t yyscanner)
     return yy_flex_debug;
 }
 
-void cmFortran_yyset_debug (int  bdebug , yyscan_t yyscanner)
+void cmFortran_yyset_debug (int  _bdebug , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yy_flex_debug = bdebug ;
+    yy_flex_debug = _bdebug ;
 }
 
 /* Accessor methods for yylval and yylloc */
@@ -2315,10 +2348,10 @@ static int yy_init_globals (yyscan_t yyscanner)
      * This function is called from cmFortran_yylex_destroy(), so don't allocate here.
      */
 
-    yyg->yy_buffer_stack = 0;
+    yyg->yy_buffer_stack = NULL;
     yyg->yy_buffer_stack_top = 0;
     yyg->yy_buffer_stack_max = 0;
-    yyg->yy_c_buf_p = (char *) 0;
+    yyg->yy_c_buf_p = NULL;
     yyg->yy_init = 0;
     yyg->yy_start = 0;
 
@@ -2331,8 +2364,8 @@ static int yy_init_globals (yyscan_t yyscanner)
     yyin = stdin;
     yyout = stdout;
 #else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
+    yyin = NULL;
+    yyout = NULL;
 #endif
 
     /* For future reference: Set errno on error, since we are called by
@@ -2347,15 +2380,15 @@ int cmFortran_yylex_destroy  (yyscan_t yyscanner)
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
     /* Pop the buffer stack, destroying each element. */
-        while(YY_CURRENT_BUFFER){
-                cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
-                YY_CURRENT_BUFFER_LVALUE = NULL;
-                cmFortran_yypop_buffer_state(yyscanner);
-        }
+	while(YY_CURRENT_BUFFER){
+		cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+		YY_CURRENT_BUFFER_LVALUE = NULL;
+		cmFortran_yypop_buffer_state(yyscanner);
+	}
 
-        /* Destroy the stack itself. */
-        cmFortran_yyfree(yyg->yy_buffer_stack ,yyscanner);
-        yyg->yy_buffer_stack = NULL;
+	/* Destroy the stack itself. */
+	cmFortran_yyfree(yyg->yy_buffer_stack ,yyscanner);
+	yyg->yy_buffer_stack = NULL;
 
     /* Destroy the start condition stack. */
         cmFortran_yyfree(yyg->yy_start_stack ,yyscanner );
@@ -2377,48 +2410,58 @@ int cmFortran_yylex_destroy  (yyscan_t yyscanner)
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
 {
-        int i;
-        for ( i = 0; i < n; ++i )
-                s1[i] = s2[i];
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	int i;
+	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
 }
 #endif
 
 #ifdef YY_NEED_STRLEN
 static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
 {
-        int n;
-        for ( n = 0; s[n]; ++n )
-                ;
+	int n;
+	for ( n = 0; s[n]; ++n )
+		;
 
-        return n;
+	return n;
 }
 #endif
 
-void *cmFortran_yyalloc (yy_size_t  size , yyscan_t)
+void *cmFortran_yyalloc (yy_size_t  size , yyscan_t yyscanner)
 {
-        return (void *) malloc( size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	return malloc(size);
 }
 
-void *cmFortran_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t)
+void *cmFortran_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscanner)
 {
-        /* The cast to (char *) in the following accommodates both
-         * implementations that use char* generic pointers, and those
-         * that use void* generic pointers.  It works with the latter
-         * because both ANSI C and C++ allow castless assignment from
-         * any pointer type to void*, and deal with argument conversions
-         * as though doing an assignment.
-         */
-        return (void *) realloc( (char *) ptr, size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return realloc(ptr, size);
 }
 
-void cmFortran_yyfree (void * ptr , yyscan_t)
+void cmFortran_yyfree (void * ptr , yyscan_t yyscanner)
 {
-        free( (char *) ptr );   /* see cmFortran_yyrealloc() for (char *) cast */
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	free( (char *) ptr );	/* see cmFortran_yyrealloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#line 182 "cmFortranLexer.in.l"
+#line 187 "cmFortranLexer.in.l"
 
 
 
diff --git a/Source/cmFortranLexer.h b/Source/cmFortranLexer.h
index b9ff0dc..851f37f 100644
--- a/Source/cmFortranLexer.h
+++ b/Source/cmFortranLexer.h
@@ -1,26 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
 #ifndef cmFortran_yyHEADER_H
 #define cmFortran_yyHEADER_H 1
 #define cmFortran_yyIN_HEADER 1
 
+#line 6 "cmFortranLexer.h"
+
+#line 8 "cmFortranLexer.h"
+
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 39
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -99,25 +92,13 @@ typedef unsigned int flex_uint32_t;
 
 #endif /* ! FLEXINT_H */
 
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else   /* ! __cplusplus */
-
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
-
-#define YY_USE_CONST
-
-#endif  /* defined (__STDC__) */
-#endif  /* ! __cplusplus */
-
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* An opaque pointer. */
@@ -163,52 +144,52 @@ typedef size_t yy_size_t;
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-        {
-        FILE *yy_input_file;
-
-        char *yy_ch_buf;                /* input buffer */
-        char *yy_buf_pos;               /* current position in input buffer */
-
-        /* Size of input buffer in bytes, not including room for EOB
-         * characters.
-         */
-        yy_size_t yy_buf_size;
-
-        /* Number of characters read into yy_ch_buf, not including EOB
-         * characters.
-         */
-        yy_size_t yy_n_chars;
-
-        /* Whether we "own" the buffer - i.e., we know we created it,
-         * and can realloc() it to grow it, and should free() it to
-         * delete it.
-         */
-        int yy_is_our_buffer;
-
-        /* Whether this is an "interactive" input source; if so, and
-         * if we're using stdio for input, then we want to use getc()
-         * instead of fread(), to make sure we stop fetching input after
-         * each newline.
-         */
-        int yy_is_interactive;
-
-        /* Whether we're considered to be at the beginning of a line.
-         * If so, '^' rules will be active on the next match, otherwise
-         * not.
-         */
-        int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-        /* Whether to try to fill the input buffer when we reach the
-         * end of it.
-         */
-        int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-        int yy_buffer_status;
+	int yy_buffer_status;
 
-        };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 void cmFortran_yyrestart (FILE *input_file ,yyscan_t yyscanner );
@@ -221,7 +202,7 @@ void cmFortran_yypop_buffer_state (yyscan_t yyscanner );
 
 YY_BUFFER_STATE cmFortran_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
 YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
 
 void *cmFortran_yyalloc (yy_size_t ,yyscan_t yyscanner );
 void *cmFortran_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -229,7 +210,7 @@ void cmFortran_yyfree (void * ,yyscan_t yyscanner );
 
 /* Begin user sect3 */
 
-#define cmFortran_yywrap(yyscanner) 1
+#define cmFortran_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 #define yytext_ptr yytext_r
@@ -243,6 +224,14 @@ void cmFortran_yyfree (void * ,yyscan_t yyscanner );
 
 #endif
 
+#ifndef YY_NO_UNISTD_H
+/* Special case for "unistd.h", since it is non-ANSI. We include it way
+ * down here because we want the user's section 1 to have been scanned first.
+ * The user has a chance to override it with an option.
+ */
+#include <unistd.h>
+#endif
+
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -266,23 +255,23 @@ void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
 
 FILE *cmFortran_yyget_in (yyscan_t yyscanner );
 
-void cmFortran_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmFortran_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmFortran_yyget_out (yyscan_t yyscanner );
 
-void cmFortran_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmFortran_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-yy_size_t cmFortran_yyget_leng (yyscan_t yyscanner );
+			int cmFortran_yyget_leng (yyscan_t yyscanner );
 
 char *cmFortran_yyget_text (yyscan_t yyscanner );
 
 int cmFortran_yyget_lineno (yyscan_t yyscanner );
 
-void cmFortran_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmFortran_yyset_lineno (int _line_number ,yyscan_t yyscanner );
 
 int cmFortran_yyget_column  (yyscan_t yyscanner );
 
-void cmFortran_yyset_column (int column_no ,yyscan_t yyscanner );
+void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -348,5 +337,9 @@ extern int cmFortran_yylex (yyscan_t yyscanner);
 #undef YY_DECL
 #endif
 
+#line 187 "cmFortranLexer.in.l"
+
+
+#line 344 "cmFortranLexer.h"
 #undef cmFortran_yyIN_HEADER
 #endif /* cmFortran_yyHEADER_H */
diff --git a/Source/cmFortranLexer.in.l b/Source/cmFortranLexer.in.l
index e59ff5f..e82eaa0 100644
--- a/Source/cmFortranLexer.in.l
+++ b/Source/cmFortranLexer.in.l
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*-------------------------------------------------------------------------
   Portions of this source have been derived from makedepf90 version 2.8.8,
 
@@ -24,28 +15,21 @@
 
 This file must be translated to C and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
   flex -i --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
 
 Modify cmFortranLexer.cxx:
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmFortran_yyalloc, cmFortran_yyrealloc, cmFortran_yyfree
+  - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
+  - remove blank lines at end of file
   - remove "yyscanner = NULL" from end of cmFortran_yylex_destroy
   - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-
-Modify cmFortranLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
 #include "cmStandardLexer.h"
+#undef YY_NO_UNPUT
 
 #define cmFortranLexer_cxx
 #include "cmFortranParser.h" /* Interface to parser object.  */
@@ -153,17 +137,28 @@ $[ \t]*endif    { return F90PPR_ENDIF; }
 , { return COMMA; }
 
 :: { return DCOLON; }
+: { return COLON; }
 
 <fixed_fmt>\n[ ]{5}[^ ]  { return GARBAGE; }
 
 =|=>                     { return ASSIGNMENT_OP; }
 
+[Ee][Nn][Dd] { return END; }
+[Ii][Nn][Cc][Ll][Uu][Dd][Ee] { return INCLUDE; }
+[Ii][Nn][Tt][Ee][Rr][Ff][Aa][Cc][Ee] { return INTERFACE; }
+[Mm][Oo][Dd][Uu][Ll][Ee] { return MODULE; }
+[Ss][Uu][bb][Mm][Oo][Dd][Uu][Ll][Ee] { return SUBMODULE; }
+[Uu][Ss][Ee] { return USE; }
+
 [a-zA-Z_][a-zA-Z_0-9]* {
   yylvalp->string = strdup(yytext);
   return WORD;
 }
 
-[^ \t\n\r;,!'"a-zA-Z=&]+ { return GARBAGE; }
+\( { return LPAREN; }
+\) { return RPAREN; }
+
+[^ \t\n\r:;,!'"a-zA-Z=&()]+ { return GARBAGE; }
 
 ;|\n { return EOSTMT; }
 
diff --git a/Source/cmFortranParser.cxx b/Source/cmFortranParser.cxx
index 21a6443..896e589 100644
--- a/Source/cmFortranParser.cxx
+++ b/Source/cmFortranParser.cxx
@@ -1,8 +1,8 @@
-/* A Bison parser, made by GNU Bison 3.0.2.  */
+/* A Bison parser, made by GNU Bison 3.0.4.  */
 
 /* Bison implementation for Yacc-like parsers in C
 
-   Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
+   Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -44,7 +44,7 @@
 #define YYBISON 1
 
 /* Bison version.  */
-#define YYBISON_VERSION "3.0.2"
+#define YYBISON_VERSION "3.0.4"
 
 /* Skeleton name.  */
 #define YYSKELETON_NAME "yacc.c"
@@ -70,17 +70,8 @@
 /* Copy the first part of user declarations.  */
 #line 1 "cmFortranParser.y" /* yacc.c:339  */
 
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*-------------------------------------------------------------------------
   Portions of this source have been derived from makedepf90 version 2.8.8,
 
@@ -123,12 +114,6 @@ static void cmFortran_yyerror(yyscan_t yyscanner, const char* message)
   cmFortranParser_Error(parser, message);
 }
 
-static bool cmFortranParserIsKeyword(const char* word,
-                                            const char* keyword)
-{
-  return cmsysString_strcasecmp(word, keyword) == 0;
-}
-
 /* Disable some warnings in the generated code.  */
 #ifdef _MSC_VER
 # pragma warning (disable: 4102) /* Unused goto label.  */
@@ -139,7 +124,7 @@ static bool cmFortranParserIsKeyword(const char* word,
 # pragma warning (disable: 4244) /* Conversion to smaller type, data loss. */
 #endif
 
-#line 143 "cmFortranParser.cxx" /* yacc.c:339  */
+#line 137 "cmFortranParser.cxx" /* yacc.c:339  */
 
 # ifndef YY_NULLPTR
 #  if defined __cplusplus && 201103L <= __cplusplus
@@ -198,12 +183,20 @@ extern int cmFortran_yydebug;
     F90PPR_ELIF = 279,
     F90PPR_ENDIF = 280,
     COMMA = 281,
-    DCOLON = 282,
-    CPP_TOENDL = 283,
-    UNTERMINATED_STRING = 284,
-    STRING = 285,
-    WORD = 286,
-    CPP_INCLUDE_ANGLE = 287
+    COLON = 282,
+    DCOLON = 283,
+    LPAREN = 284,
+    RPAREN = 285,
+    UNTERMINATED_STRING = 286,
+    STRING = 287,
+    WORD = 288,
+    CPP_INCLUDE_ANGLE = 289,
+    END = 290,
+    INCLUDE = 291,
+    INTERFACE = 292,
+    MODULE = 293,
+    SUBMODULE = 294,
+    USE = 295
   };
 #endif
 /* Tokens.  */
@@ -231,24 +224,34 @@ extern int cmFortran_yydebug;
 #define F90PPR_ELIF 279
 #define F90PPR_ENDIF 280
 #define COMMA 281
-#define DCOLON 282
-#define CPP_TOENDL 283
-#define UNTERMINATED_STRING 284
-#define STRING 285
-#define WORD 286
-#define CPP_INCLUDE_ANGLE 287
+#define COLON 282
+#define DCOLON 283
+#define LPAREN 284
+#define RPAREN 285
+#define UNTERMINATED_STRING 286
+#define STRING 287
+#define WORD 288
+#define CPP_INCLUDE_ANGLE 289
+#define END 290
+#define INCLUDE 291
+#define INTERFACE 292
+#define MODULE 293
+#define SUBMODULE 294
+#define USE 295
 
 /* Value type.  */
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE YYSTYPE;
+
 union YYSTYPE
 {
-#line 81 "cmFortranParser.y" /* yacc.c:355  */
+#line 75 "cmFortranParser.y" /* yacc.c:355  */
 
   char* string;
 
-#line 251 "cmFortranParser.cxx" /* yacc.c:355  */
+#line 261 "cmFortranParser.cxx" /* yacc.c:355  */
 };
+
+typedef union YYSTYPE YYSTYPE;
 # define YYSTYPE_IS_TRIVIAL 1
 # define YYSTYPE_IS_DECLARED 1
 #endif
@@ -261,7 +264,7 @@ int cmFortran_yyparse (yyscan_t yyscanner);
 
 /* Copy the second part of user declarations.  */
 
-#line 265 "cmFortranParser.cxx" /* yacc.c:358  */
+#line 277 "cmFortranParser.cxx" /* yacc.c:358  */
 
 #ifdef short
 # undef short
@@ -503,21 +506,21 @@ union yyalloc
 /* YYFINAL -- State number of the termination state.  */
 #define YYFINAL  2
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   290
+#define YYLAST   593
 
 /* YYNTOKENS -- Number of terminals.  */
-#define YYNTOKENS  33
+#define YYNTOKENS  41
 /* YYNNTS -- Number of nonterminals.  */
-#define YYNNTS  16
+#define YYNNTS  14
 /* YYNRULES -- Number of rules.  */
-#define YYNRULES  54
+#define YYNRULES  63
 /* YYNSTATES -- Number of states.  */
-#define YYNSTATES  101
+#define YYNSTATES  126
 
 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
    by yylex, with out-of-bounds checking.  */
 #define YYUNDEFTOK  2
-#define YYMAXUTOK   287
+#define YYMAXUTOK   295
 
 #define YYTRANSLATE(YYX)                                                \
   ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
@@ -554,19 +557,21 @@ static const yytype_uint8 yytranslate[] =
        2,     2,     2,     2,     2,     2,     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
+      25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
+      35,    36,    37,    38,    39,    40
 };
 
 #if YYDEBUG
   /* YYRLINE[YYN] -- Source line where rule number YYN was defined.  */
-static const yytype_uint16 yyrline[] =
+static const yytype_uint8 yyrline[] =
 {
-       0,   104,   104,   104,   106,   106,   108,   114,   124,   154,
-     165,   178,   189,   196,   203,   210,   216,   222,   228,   234,
-     239,   244,   249,   254,   258,   259,   260,   265,   265,   265,
-     266,   266,   267,   267,   268,   268,   269,   269,   270,   270,
-     271,   271,   272,   272,   273,   273,   274,   274,   277,   278,
-     279,   280,   281,   282,   283
+       0,   103,   103,   103,   106,   110,   115,   124,   130,   137,
+     142,   146,   151,   159,   164,   169,   174,   179,   184,   189,
+     194,   199,   203,   207,   211,   215,   216,   221,   221,   221,
+     222,   222,   223,   223,   224,   224,   225,   225,   226,   226,
+     227,   227,   228,   228,   229,   229,   230,   230,   233,   234,
+     235,   236,   237,   238,   239,   240,   241,   242,   243,   244,
+     245,   246,   247,   248
 };
 #endif
 
@@ -580,11 +585,11 @@ static const char *const yytname[] =
   "F90PPR_DEFINE", "CPP_DEFINE", "F90PPR_UNDEF", "CPP_UNDEF", "CPP_IFDEF",
   "CPP_IFNDEF", "CPP_IF", "CPP_ELSE", "CPP_ELIF", "CPP_ENDIF",
   "F90PPR_IFDEF", "F90PPR_IFNDEF", "F90PPR_IF", "F90PPR_ELSE",
-  "F90PPR_ELIF", "F90PPR_ENDIF", "COMMA", "DCOLON", "CPP_TOENDL",
-  "UNTERMINATED_STRING", "STRING", "WORD", "CPP_INCLUDE_ANGLE", "$accept",
-  "code", "stmt", "assignment_stmt", "keyword_stmt", "include", "define",
-  "undef", "ifdef", "ifndef", "if", "elif", "else", "endif", "other",
-  "misc_code", YY_NULLPTR
+  "F90PPR_ELIF", "F90PPR_ENDIF", "COMMA", "COLON", "DCOLON", "LPAREN",
+  "RPAREN", "UNTERMINATED_STRING", "STRING", "WORD", "CPP_INCLUDE_ANGLE",
+  "END", "INCLUDE", "INTERFACE", "MODULE", "SUBMODULE", "USE", "$accept",
+  "code", "stmt", "include", "define", "undef", "ifdef", "ifndef", "if",
+  "elif", "else", "endif", "other", "misc_code", YY_NULLPTR
 };
 #endif
 
@@ -596,14 +601,15 @@ static const yytype_uint16 yytoknum[] =
        0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
      265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
      275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
-     285,   286,   287
+     285,   286,   287,   288,   289,   290,   291,   292,   293,   294,
+     295
 };
 # endif
 
-#define YYPACT_NINF -30
+#define YYPACT_NINF -39
 
 #define yypact_value_is_default(Yystate) \
-  (!!((Yystate) == (-30)))
+  (!!((Yystate) == (-39)))
 
 #define YYTABLE_NINF -1
 
@@ -614,17 +620,19 @@ static const yytype_uint16 yytoknum[] =
      STATE-NUM.  */
 static const yytype_int16 yypact[] =
 {
-     -30,    41,   -30,   -30,   -30,   -30,   -29,   -30,   -30,   -30,
-     -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,
-     -30,   -30,   -30,   -30,   -30,   -30,   259,   -30,   -30,   -30,
-     -30,   -28,   -23,   -18,   -16,   -13,   -30,   -30,   -30,   -30,
-       2,   -30,   -30,   -30,   -30,   -12,    -9,   -30,   -30,    64,
-     -30,   -30,   -30,   -30,   -30,    71,    77,    83,   112,   -30,
-     -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   118,   124,
-     130,   -24,   -30,   159,   165,   -30,   171,   177,   206,   212,
-     218,   -30,   -30,   -30,   -30,   -30,   -30,   -30,    -1,   224,
-     -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   253,
-     -30
+     -39,    21,   -39,     1,   -39,   -20,   -39,   -39,   -39,   -39,
+     -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,
+     -39,   -39,   -39,   -39,   -39,   -39,   -24,   -18,    20,    -8,
+      -3,    39,   -39,    15,    16,    18,    19,    33,   -39,   -39,
+     -39,   -39,   -39,   -39,    59,   -39,   -39,   -39,   -39,   -39,
+      35,    36,    37,   -39,   -39,   -39,   -39,   -39,   -39,    76,
+     114,   129,   167,   182,   -39,   -39,   -39,   -39,   -39,   -39,
+     -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,
+     -39,   -39,   220,   235,   273,   288,   -21,    26,   -39,   326,
+     341,   379,   394,   432,   447,   -39,   -39,   -39,   -39,   -39,
+     -39,   -39,   -39,   -39,    38,    40,    41,   485,   -39,   -39,
+     -39,   -39,   -39,   -39,    45,   -39,   -39,   -39,    43,   500,
+     538,   -39,   -39,   -39,   553,   -39
 };
 
   /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
@@ -632,31 +640,33 @@ static const yytype_int16 yypact[] =
      means the default is an error.  */
 static const yytype_uint8 yydefact[] =
 {
-       2,     0,     1,    26,    25,    46,     0,    27,    28,    29,
-      31,    30,    33,    32,    34,    36,    38,    42,    40,    44,
-      35,    37,    39,    43,    41,    45,     0,    46,     3,     5,
-       4,     0,     0,     0,     0,     0,    46,    46,    46,    46,
-       0,    46,     7,    46,    46,     0,     0,    46,    46,     0,
-      46,    46,    46,    46,    46,     0,     0,     0,     0,    24,
-      51,    50,    53,    52,    54,    49,    48,    47,     0,     0,
-       0,     0,    46,     0,     0,    13,     0,     0,     0,     0,
-       0,    19,    20,    21,    22,    12,     6,    23,     0,     0,
-      11,     8,    14,    15,    16,    17,    18,    46,     9,     0,
-      10
+       2,     0,     1,     0,    25,     0,    27,    28,    29,    31,
+      30,    33,    32,    34,    36,    38,    42,    40,    44,    35,
+      37,    39,    43,    41,    45,    46,     0,     0,     0,     0,
+       0,     0,     3,     0,     0,     0,     0,     0,    46,    46,
+      46,    46,    26,    46,     0,    46,    46,     4,    46,    46,
+       0,     0,     0,    46,    46,    46,    46,    46,    46,     0,
+       0,     0,     0,     0,    15,    57,    56,    62,    58,    59,
+      60,    61,    63,    55,    48,    49,    50,    51,    52,    53,
+      54,    47,     0,     0,     0,     0,     0,     0,    46,     0,
+       0,     0,     0,     0,     0,    21,    22,    23,    24,    14,
+      10,    13,     9,     6,     0,     0,     0,     0,     5,    16,
+      17,    18,    19,    20,     0,    46,    46,    11,     0,     0,
+       0,    46,     7,    12,     0,     8
 };
 
   /* YYPGOTO[NTERM-NUM].  */
 static const yytype_int8 yypgoto[] =
 {
-     -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,   -30,
-     -30,   -30,   -30,   -30,   -27,   -30
+     -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,   -39,
+     -39,   -39,   -38,   -39
 };
 
   /* YYDEFGOTO[NTERM-NUM].  */
 static const yytype_int8 yydefgoto[] =
 {
-      -1,     1,    28,    29,    30,    31,    32,    33,    34,    35,
-      36,    37,    38,    39,    40,    67
+      -1,     1,    32,    33,    34,    35,    36,    37,    38,    39,
+      40,    41,    44,    81
 };
 
   /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM.  If
@@ -664,109 +674,173 @@ static const yytype_int8 yydefgoto[] =
      number is the opposite.  If YYTABLE_NINF, syntax error.  */
 static const yytype_uint8 yytable[] =
 {
-      49,    41,    50,    88,     0,    59,    60,    61,    51,    55,
-      56,    57,    58,    52,    68,    53,    69,    70,    54,    71,
-      73,    74,    72,    76,    77,    78,    79,    80,    62,    63,
-      97,    64,    65,    66,     0,     0,     0,     0,     0,     0,
-       0,     2,     3,     0,     4,    89,     5,     6,     7,     8,
-       9,    10,    11,    12,    13,    14,    15,    16,    17,    18,
-      19,    20,    21,    22,    23,    24,    25,    75,    60,    61,
-      99,     0,    26,    27,    81,    60,    61,     0,     0,     0,
-      82,    60,    61,     0,     0,     0,    83,    60,    61,     0,
-      62,    63,     0,    64,    65,    66,     0,    62,    63,     0,
-      64,    65,    66,    62,    63,     0,    64,    65,    66,    62,
-      63,     0,    64,    65,    66,    84,    60,    61,     0,     0,
-       0,    85,    60,    61,     0,     0,     0,    86,    60,    61,
-       0,     0,     0,    87,    60,    61,     0,     0,    62,    63,
-       0,    64,    65,    66,    62,    63,     0,    64,    65,    66,
-      62,    63,     0,    64,    65,    66,    62,    63,     0,    64,
-      65,    66,    90,    60,    61,     0,     0,     0,    91,    60,
-      61,     0,     0,     0,    92,    60,    61,     0,     0,     0,
-      93,    60,    61,     0,     0,    62,    63,     0,    64,    65,
-      66,    62,    63,     0,    64,    65,    66,    62,    63,     0,
-      64,    65,    66,    62,    63,     0,    64,    65,    66,    94,
-      60,    61,     0,     0,     0,    95,    60,    61,     0,     0,
-       0,    96,    60,    61,     0,     0,     0,    98,    60,    61,
-       0,     0,    62,    63,     0,    64,    65,    66,    62,    63,
-       0,    64,    65,    66,    62,    63,     0,    64,    65,    66,
-      62,    63,     0,    64,    65,    66,   100,    60,    61,     0,
-       0,     0,    42,    43,    44,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     0,     0,     0,     0,    62,
-      63,     0,    64,    65,    66,    45,    46,     0,     0,    47,
-      48
+      59,    60,    61,    62,    42,    63,   104,    82,    83,   105,
+      84,    85,    43,    45,    46,    89,    90,    91,    92,    93,
+      94,     2,     3,    47,     4,    49,    50,     5,     6,     7,
+       8,     9,    10,    11,    12,    13,    14,    15,    16,    17,
+      18,    19,    20,    21,    22,    23,    24,    54,     0,    55,
+     107,    56,    57,    48,   106,    25,    26,    27,    28,    29,
+      30,    31,    64,    65,    66,    51,    58,    52,    86,    87,
+      88,   114,    53,   115,   116,   118,   121,   119,   120,    95,
+      65,    66,     0,   124,     0,    67,    68,    69,    70,    71,
+      72,    73,    74,     0,    75,    76,    77,    78,    79,    80,
+       0,     0,    67,    68,    69,    70,    71,    72,    73,    74,
+       0,    75,    76,    77,    78,    79,    80,    96,    65,    66,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,    97,    65,    66,     0,     0,     0,     0,     0,
+      67,    68,    69,    70,    71,    72,    73,    74,     0,    75,
+      76,    77,    78,    79,    80,    67,    68,    69,    70,    71,
+      72,    73,    74,     0,    75,    76,    77,    78,    79,    80,
+      98,    65,    66,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,    99,    65,    66,     0,     0,
+       0,     0,     0,    67,    68,    69,    70,    71,    72,    73,
+      74,     0,    75,    76,    77,    78,    79,    80,    67,    68,
+      69,    70,    71,    72,    73,    74,     0,    75,    76,    77,
+      78,    79,    80,   100,    65,    66,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,   101,    65,
+      66,     0,     0,     0,     0,     0,    67,    68,    69,    70,
+      71,    72,    73,    74,     0,    75,    76,    77,    78,    79,
+      80,    67,    68,    69,    70,    71,    72,    73,    74,     0,
+      75,    76,    77,    78,    79,    80,   102,    65,    66,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,   103,    65,    66,     0,     0,     0,     0,     0,    67,
+      68,    69,    70,    71,    72,    73,    74,     0,    75,    76,
+      77,    78,    79,    80,    67,    68,    69,    70,    71,    72,
+      73,    74,     0,    75,    76,    77,    78,    79,    80,   108,
+      65,    66,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,   109,    65,    66,     0,     0,     0,
+       0,     0,    67,    68,    69,    70,    71,    72,    73,    74,
+       0,    75,    76,    77,    78,    79,    80,    67,    68,    69,
+      70,    71,    72,    73,    74,     0,    75,    76,    77,    78,
+      79,    80,   110,    65,    66,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,   111,    65,    66,
+       0,     0,     0,     0,     0,    67,    68,    69,    70,    71,
+      72,    73,    74,     0,    75,    76,    77,    78,    79,    80,
+      67,    68,    69,    70,    71,    72,    73,    74,     0,    75,
+      76,    77,    78,    79,    80,   112,    65,    66,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+     113,    65,    66,     0,     0,     0,     0,     0,    67,    68,
+      69,    70,    71,    72,    73,    74,     0,    75,    76,    77,
+      78,    79,    80,    67,    68,    69,    70,    71,    72,    73,
+      74,     0,    75,    76,    77,    78,    79,    80,   117,    65,
+      66,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,   122,    65,    66,     0,     0,     0,     0,
+       0,    67,    68,    69,    70,    71,    72,    73,    74,     0,
+      75,    76,    77,    78,    79,    80,    67,    68,    69,    70,
+      71,    72,    73,    74,     0,    75,    76,    77,    78,    79,
+      80,   123,    65,    66,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,   125,    65,    66,     0,
+       0,     0,     0,     0,    67,    68,    69,    70,    71,    72,
+      73,    74,     0,    75,    76,    77,    78,    79,    80,    67,
+      68,    69,    70,    71,    72,    73,    74,     0,    75,    76,
+      77,    78,    79,    80
 };
 
 static const yytype_int8 yycheck[] =
 {
-      27,    30,    30,    27,    -1,     3,     4,     5,    31,    36,
-      37,    38,    39,    31,    41,    31,    43,    44,    31,    31,
-      47,    48,    31,    50,    51,    52,    53,    54,    26,    27,
-      31,    29,    30,    31,    -1,    -1,    -1,    -1,    -1,    -1,
-      -1,     0,     1,    -1,     3,    72,     5,     6,     7,     8,
+      38,    39,    40,    41,     3,    43,    27,    45,    46,    30,
+      48,    49,    32,    37,    32,    53,    54,    55,    56,    57,
+      58,     0,     1,     3,     3,    33,    29,     6,     7,     8,
        9,    10,    11,    12,    13,    14,    15,    16,    17,    18,
-      19,    20,    21,    22,    23,    24,    25,     3,     4,     5,
-      97,    -1,    31,    32,     3,     4,     5,    -1,    -1,    -1,
-       3,     4,     5,    -1,    -1,    -1,     3,     4,     5,    -1,
-      26,    27,    -1,    29,    30,    31,    -1,    26,    27,    -1,
-      29,    30,    31,    26,    27,    -1,    29,    30,    31,    26,
-      27,    -1,    29,    30,    31,     3,     4,     5,    -1,    -1,
-      -1,     3,     4,     5,    -1,    -1,    -1,     3,     4,     5,
-      -1,    -1,    -1,     3,     4,     5,    -1,    -1,    26,    27,
-      -1,    29,    30,    31,    26,    27,    -1,    29,    30,    31,
-      26,    27,    -1,    29,    30,    31,    26,    27,    -1,    29,
-      30,    31,     3,     4,     5,    -1,    -1,    -1,     3,     4,
-       5,    -1,    -1,    -1,     3,     4,     5,    -1,    -1,    -1,
-       3,     4,     5,    -1,    -1,    26,    27,    -1,    29,    30,
-      31,    26,    27,    -1,    29,    30,    31,    26,    27,    -1,
-      29,    30,    31,    26,    27,    -1,    29,    30,    31,     3,
-       4,     5,    -1,    -1,    -1,     3,     4,     5,    -1,    -1,
-      -1,     3,     4,     5,    -1,    -1,    -1,     3,     4,     5,
-      -1,    -1,    26,    27,    -1,    29,    30,    31,    26,    27,
-      -1,    29,    30,    31,    26,    27,    -1,    29,    30,    31,
-      26,    27,    -1,    29,    30,    31,     3,     4,     5,    -1,
+      19,    20,    21,    22,    23,    24,    25,    32,    -1,    33,
+      88,    33,    33,    33,    28,    34,    35,    36,    37,    38,
+      39,    40,     3,     4,     5,    26,    33,    28,    33,    33,
+      33,    33,    33,    33,    33,    30,    33,   115,   116,     3,
+       4,     5,    -1,   121,    -1,    26,    27,    28,    29,    30,
+      31,    32,    33,    -1,    35,    36,    37,    38,    39,    40,
+      -1,    -1,    26,    27,    28,    29,    30,    31,    32,    33,
+      -1,    35,    36,    37,    38,    39,    40,     3,     4,     5,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
       -1,    -1,     3,     4,     5,    -1,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    26,
-      27,    -1,    29,    30,    31,    26,    27,    -1,    -1,    30,
-      31
+      26,    27,    28,    29,    30,    31,    32,    33,    -1,    35,
+      36,    37,    38,    39,    40,    26,    27,    28,    29,    30,
+      31,    32,    33,    -1,    35,    36,    37,    38,    39,    40,
+       3,     4,     5,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,     3,     4,     5,    -1,    -1,
+      -1,    -1,    -1,    26,    27,    28,    29,    30,    31,    32,
+      33,    -1,    35,    36,    37,    38,    39,    40,    26,    27,
+      28,    29,    30,    31,    32,    33,    -1,    35,    36,    37,
+      38,    39,    40,     3,     4,     5,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,     3,     4,
+       5,    -1,    -1,    -1,    -1,    -1,    26,    27,    28,    29,
+      30,    31,    32,    33,    -1,    35,    36,    37,    38,    39,
+      40,    26,    27,    28,    29,    30,    31,    32,    33,    -1,
+      35,    36,    37,    38,    39,    40,     3,     4,     5,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,     3,     4,     5,    -1,    -1,    -1,    -1,    -1,    26,
+      27,    28,    29,    30,    31,    32,    33,    -1,    35,    36,
+      37,    38,    39,    40,    26,    27,    28,    29,    30,    31,
+      32,    33,    -1,    35,    36,    37,    38,    39,    40,     3,
+       4,     5,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,     3,     4,     5,    -1,    -1,    -1,
+      -1,    -1,    26,    27,    28,    29,    30,    31,    32,    33,
+      -1,    35,    36,    37,    38,    39,    40,    26,    27,    28,
+      29,    30,    31,    32,    33,    -1,    35,    36,    37,    38,
+      39,    40,     3,     4,     5,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,     3,     4,     5,
+      -1,    -1,    -1,    -1,    -1,    26,    27,    28,    29,    30,
+      31,    32,    33,    -1,    35,    36,    37,    38,    39,    40,
+      26,    27,    28,    29,    30,    31,    32,    33,    -1,    35,
+      36,    37,    38,    39,    40,     3,     4,     5,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+       3,     4,     5,    -1,    -1,    -1,    -1,    -1,    26,    27,
+      28,    29,    30,    31,    32,    33,    -1,    35,    36,    37,
+      38,    39,    40,    26,    27,    28,    29,    30,    31,    32,
+      33,    -1,    35,    36,    37,    38,    39,    40,     3,     4,
+       5,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,     3,     4,     5,    -1,    -1,    -1,    -1,
+      -1,    26,    27,    28,    29,    30,    31,    32,    33,    -1,
+      35,    36,    37,    38,    39,    40,    26,    27,    28,    29,
+      30,    31,    32,    33,    -1,    35,    36,    37,    38,    39,
+      40,     3,     4,     5,    -1,    -1,    -1,    -1,    -1,    -1,
+      -1,    -1,    -1,    -1,    -1,    -1,     3,     4,     5,    -1,
+      -1,    -1,    -1,    -1,    26,    27,    28,    29,    30,    31,
+      32,    33,    -1,    35,    36,    37,    38,    39,    40,    26,
+      27,    28,    29,    30,    31,    32,    33,    -1,    35,    36,
+      37,    38,    39,    40
 };
 
   /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
      symbol of state STATE-NUM.  */
 static const yytype_uint8 yystos[] =
 {
-       0,    34,     0,     1,     3,     5,     6,     7,     8,     9,
-      10,    11,    12,    13,    14,    15,    16,    17,    18,    19,
-      20,    21,    22,    23,    24,    25,    31,    32,    35,    36,
-      37,    38,    39,    40,    41,    42,    43,    44,    45,    46,
-      47,    30,     3,     4,     5,    26,    27,    30,    31,    47,
-      30,    31,    31,    31,    31,    47,    47,    47,    47,     3,
-       4,     5,    26,    27,    29,    30,    31,    48,    47,    47,
-      47,    31,    31,    47,    47,     3,    47,    47,    47,    47,
-      47,     3,     3,     3,     3,     3,     3,     3,    27,    47,
-       3,     3,     3,     3,     3,     3,     3,    31,     3,    47,
-       3
+       0,    42,     0,     1,     3,     6,     7,     8,     9,    10,
+      11,    12,    13,    14,    15,    16,    17,    18,    19,    20,
+      21,    22,    23,    24,    25,    34,    35,    36,    37,    38,
+      39,    40,    43,    44,    45,    46,    47,    48,    49,    50,
+      51,    52,     3,    32,    53,    37,    32,     3,    33,    33,
+      29,    26,    28,    33,    32,    33,    33,    33,    33,    53,
+      53,    53,    53,    53,     3,     4,     5,    26,    27,    28,
+      29,    30,    31,    32,    33,    35,    36,    37,    38,    39,
+      40,    54,    53,    53,    53,    53,    33,    33,    33,    53,
+      53,    53,    53,    53,    53,     3,     3,     3,     3,     3,
+       3,     3,     3,     3,    27,    30,    28,    53,     3,     3,
+       3,     3,     3,     3,    33,    33,    33,     3,    30,    53,
+      53,    33,     3,     3,    53,     3
 };
 
   /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
 static const yytype_uint8 yyr1[] =
 {
-       0,    33,    34,    34,    35,    35,    36,    37,    37,    37,
-      37,    37,    37,    37,    37,    37,    37,    37,    37,    37,
-      37,    37,    37,    37,    37,    37,    37,    38,    38,    38,
-      39,    39,    40,    40,    41,    41,    42,    42,    43,    43,
-      44,    44,    45,    45,    46,    46,    47,    47,    48,    48,
-      48,    48,    48,    48,    48
+       0,    41,    42,    42,    43,    43,    43,    43,    43,    43,
+      43,    43,    43,    43,    43,    43,    43,    43,    43,    43,
+      43,    43,    43,    43,    43,    43,    43,    44,    44,    44,
+      45,    45,    46,    46,    47,    47,    48,    48,    49,    49,
+      50,    50,    51,    51,    52,    52,    53,    53,    54,    54,
+      54,    54,    54,    54,    54,    54,    54,    54,    54,    54,
+      54,    54,    54,    54
 };
 
   /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.  */
 static const yytype_uint8 yyr2[] =
 {
-       0,     2,     0,     2,     1,     1,     4,     2,     4,     5,
-       7,     4,     4,     3,     4,     4,     4,     4,     4,     3,
-       3,     3,     3,     4,     3,     1,     1,     1,     1,     1,
+       0,     2,     0,     2,     2,     4,     4,     7,     9,     4,
+       4,     5,     7,     4,     4,     3,     4,     4,     4,     4,
+       4,     3,     3,     3,     3,     1,     2,     1,     1,     1,
        1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
        1,     1,     1,     1,     1,     1,     0,     2,     1,     1,
-       1,     1,     1,     1,     1
+       1,     1,     1,     1,     1,     1,     1,     1,     1,     1,
+       1,     1,     1,     1
 };
 
 
@@ -1448,240 +1522,234 @@ yyreduce:
   YY_REDUCE_PRINT (yyn);
   switch (yyn)
     {
-        case 6:
-#line 109 "cmFortranParser.y" /* yacc.c:1646  */
+        case 4:
+#line 106 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    free((yyvsp[-3].string));
-    }
-#line 1457 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, true);
+  }
+#line 1541 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
-  case 7:
-#line 115 "cmFortranParser.y" /* yacc.c:1646  */
+  case 5:
+#line 110 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    if (cmFortranParserIsKeyword((yyvsp[-1].string), "interface"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, true);
-      }
-    free((yyvsp[-1].string));
-    }
-#line 1471 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
+    free((yyvsp[-2].string));
+  }
+#line 1551 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
-  case 8:
-#line 125 "cmFortranParser.y" /* yacc.c:1646  */
+  case 6:
+#line 115 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    if (cmFortranParserIsKeyword((yyvsp[-3].string), "use"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
-      }
-    else if (cmFortranParserIsKeyword((yyvsp[-3].string), "module"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    if (cmsysString_strcasecmp((yyvsp[-2].string), "function") != 0 &&
+        cmsysString_strcasecmp((yyvsp[-2].string), "procedure") != 0 &&
+        cmsysString_strcasecmp((yyvsp[-2].string), "subroutine") != 0) {
       cmFortranParser_RuleModule(parser, (yyvsp[-2].string));
-      }
-    else if (cmFortranParserIsKeyword((yyvsp[-3].string), "interface"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, true);
-      }
-    else if (cmFortranParserIsKeyword((yyvsp[-2].string), "interface") &&
-             cmFortranParserIsKeyword((yyvsp[-3].string), "end"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, false);
-      }
-    free((yyvsp[-3].string));
-    free((yyvsp[-2].string));
     }
-#line 1505 "cmFortranParser.cxx" /* yacc.c:1646  */
+    free((yyvsp[-2].string));
+  }
+#line 1565 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
-  case 9:
-#line 155 "cmFortranParser.y" /* yacc.c:1646  */
+  case 7:
+#line 124 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    if (cmFortranParserIsKeyword((yyvsp[-4].string), "use"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
-      }
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, (yyvsp[-4].string));
     free((yyvsp[-4].string));
     free((yyvsp[-2].string));
-    }
-#line 1520 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1576 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
-  case 10:
-#line 166 "cmFortranParser.y" /* yacc.c:1646  */
+  case 8:
+#line 130 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    if (cmFortranParserIsKeyword((yyvsp[-6].string), "use") &&
-        cmFortranParserIsKeyword((yyvsp[-4].string), "non_intrinsic") )
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
-      }
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, (yyvsp[-6].string));
     free((yyvsp[-6].string));
     free((yyvsp[-4].string));
     free((yyvsp[-2].string));
-    }
-#line 1537 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1588 "cmFortranParser.cxx" /* yacc.c:1646  */
+    break;
+
+  case 9:
+#line 137 "cmFortranParser.y" /* yacc.c:1646  */
+    {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, true);
+    free((yyvsp[-2].string));
+  }
+#line 1598 "cmFortranParser.cxx" /* yacc.c:1646  */
+    break;
+
+  case 10:
+#line 142 "cmFortranParser.y" /* yacc.c:1646  */
+    {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, false);
+  }
+#line 1607 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 11:
-#line 179 "cmFortranParser.y" /* yacc.c:1646  */
+#line 146 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    if (cmFortranParserIsKeyword((yyvsp[-3].string), "include"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleInclude(parser, (yyvsp[-2].string));
-      }
-    free((yyvsp[-3].string));
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1552 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1617 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 12:
-#line 190 "cmFortranParser.y" /* yacc.c:1646  */
+#line 151 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleLineDirective(parser, (yyvsp[-2].string));
-    free((yyvsp[-2].string));
+    if (cmsysString_strcasecmp((yyvsp[-4].string), "non_intrinsic") == 0) {
+      cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+      cmFortranParser_RuleUse(parser, (yyvsp[-2].string));
     }
-#line 1563 "cmFortranParser.cxx" /* yacc.c:1646  */
+    free((yyvsp[-4].string));
+    free((yyvsp[-2].string));
+  }
+#line 1630 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 13:
-#line 197 "cmFortranParser.y" /* yacc.c:1646  */
+#line 159 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleInclude(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1574 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1640 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 14:
-#line 204 "cmFortranParser.y" /* yacc.c:1646  */
+#line 164 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleInclude(parser, (yyvsp[-2].string));
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleLineDirective(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1585 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1650 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 15:
-#line 211 "cmFortranParser.y" /* yacc.c:1646  */
+#line 169 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleDefine(parser, (yyvsp[-2].string));
+    cmFortranParser_RuleInclude(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1595 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1660 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 16:
-#line 217 "cmFortranParser.y" /* yacc.c:1646  */
+#line 174 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleUndef(parser, (yyvsp[-2].string));
+    cmFortranParser_RuleInclude(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1605 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1670 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 17:
-#line 223 "cmFortranParser.y" /* yacc.c:1646  */
+#line 179 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleIfdef(parser, (yyvsp[-2].string));
+    cmFortranParser_RuleDefine(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1615 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1680 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 18:
-#line 229 "cmFortranParser.y" /* yacc.c:1646  */
+#line 184 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleIfndef(parser, (yyvsp[-2].string));
+    cmFortranParser_RuleUndef(parser, (yyvsp[-2].string));
     free((yyvsp[-2].string));
-    }
-#line 1625 "cmFortranParser.cxx" /* yacc.c:1646  */
+  }
+#line 1690 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 19:
-#line 235 "cmFortranParser.y" /* yacc.c:1646  */
+#line 189 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleIf(parser);
-    }
-#line 1634 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser_RuleIfdef(parser, (yyvsp[-2].string));
+    free((yyvsp[-2].string));
+  }
+#line 1700 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 20:
-#line 240 "cmFortranParser.y" /* yacc.c:1646  */
+#line 194 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleElif(parser);
-    }
-#line 1643 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser_RuleIfndef(parser, (yyvsp[-2].string));
+    free((yyvsp[-2].string));
+  }
+#line 1710 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 21:
-#line 245 "cmFortranParser.y" /* yacc.c:1646  */
+#line 199 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleElse(parser);
-    }
-#line 1652 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser_RuleIf(parser);
+  }
+#line 1719 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 22:
-#line 250 "cmFortranParser.y" /* yacc.c:1646  */
+#line 203 "cmFortranParser.y" /* yacc.c:1646  */
     {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
-    cmFortranParser_RuleEndif(parser);
-    }
-#line 1661 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser_RuleElif(parser);
+  }
+#line 1728 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 23:
-#line 255 "cmFortranParser.y" /* yacc.c:1646  */
+#line 207 "cmFortranParser.y" /* yacc.c:1646  */
     {
-    free((yyvsp[-3].string));
-    }
-#line 1669 "cmFortranParser.cxx" /* yacc.c:1646  */
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleElse(parser);
+  }
+#line 1737 "cmFortranParser.cxx" /* yacc.c:1646  */
+    break;
+
+  case 24:
+#line 211 "cmFortranParser.y" /* yacc.c:1646  */
+    {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleEndif(parser);
+  }
+#line 1746 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
   case 48:
-#line 277 "cmFortranParser.y" /* yacc.c:1646  */
+#line 233 "cmFortranParser.y" /* yacc.c:1646  */
     { free ((yyvsp[0].string)); }
-#line 1675 "cmFortranParser.cxx" /* yacc.c:1646  */
+#line 1752 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
-  case 49:
-#line 278 "cmFortranParser.y" /* yacc.c:1646  */
+  case 55:
+#line 240 "cmFortranParser.y" /* yacc.c:1646  */
     { free ((yyvsp[0].string)); }
-#line 1681 "cmFortranParser.cxx" /* yacc.c:1646  */
+#line 1758 "cmFortranParser.cxx" /* yacc.c:1646  */
     break;
 
 
-#line 1685 "cmFortranParser.cxx" /* yacc.c:1646  */
+#line 1762 "cmFortranParser.cxx" /* yacc.c:1646  */
       default: break;
     }
   /* User semantic actions sometimes alter yychar, and that requires
@@ -1911,6 +1979,6 @@ yyreturn:
 #endif
   return yyresult;
 }
-#line 286 "cmFortranParser.y" /* yacc.c:1906  */
+#line 251 "cmFortranParser.y" /* yacc.c:1906  */
 
 /* End of grammar */
diff --git a/Source/cmFortranParser.h b/Source/cmFortranParser.h
index 07e1b1c..06985d2 100644
--- a/Source/cmFortranParser.h
+++ b/Source/cmFortranParser.h
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFortranParser_h
 #define cmFortranParser_h
 
 #if !defined(cmFortranLexer_cxx) && !defined(cmFortranParser_cxx)
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 #endif
 
@@ -71,6 +64,7 @@ union cmFortran_yystype_u
 #define YYSTYPE cmFortran_yystype
 #define YYSTYPE_IS_DECLARED 1
 #if !defined(cmFortranLexer_cxx)
+#define YY_NO_UNISTD_H
 #include "cmFortranLexer.h"
 #endif
 #if !defined(cmFortranLexer_cxx)
@@ -115,11 +109,13 @@ struct cmFortranFile
     : File(file)
     , Buffer(buffer)
     , Directory(dir)
+    , LastCharWasNewline(false)
   {
   }
   FILE* File;
   YY_BUFFER_STATE Buffer;
   std::string Directory;
+  bool LastCharWasNewline;
 };
 
 struct cmFortranParser_s
@@ -144,6 +140,9 @@ struct cmFortranParser_s
   // Buffer for string literals.
   std::string TokenString;
 
+  // Error message text if a parser error occurs.
+  std::string Error;
+
   // Flag for whether lexer is reading from inside an interface.
   bool InInterface;
 
diff --git a/Source/cmFortranParser.y b/Source/cmFortranParser.y
index 83f441a..7eb5ef5 100644
--- a/Source/cmFortranParser.y
+++ b/Source/cmFortranParser.y
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*-------------------------------------------------------------------------
   Portions of this source have been derived from makedepf90 version 2.8.8,
 
@@ -52,12 +43,6 @@ static void cmFortran_yyerror(yyscan_t yyscanner, const char* message)
   cmFortranParser_Error(parser, message);
 }
 
-static bool cmFortranParserIsKeyword(const char* word,
-                                            const char* keyword)
-{
-  return cmsysString_strcasecmp(word, keyword) == 0;
-}
-
 /* Disable some warnings in the generated code.  */
 #ifdef _MSC_VER
 # pragma warning (disable: 4102) /* Unused goto label.  */
@@ -91,11 +76,16 @@ static bool cmFortranParserIsKeyword(const char* word,
 %token CPP_IFDEF CPP_IFNDEF CPP_IF CPP_ELSE CPP_ELIF CPP_ENDIF
 %token F90PPR_IFDEF F90PPR_IFNDEF F90PPR_IF
 %token F90PPR_ELSE F90PPR_ELIF F90PPR_ENDIF
-%token COMMA DCOLON
-%token <string> CPP_TOENDL
+%token COMMA COLON DCOLON LPAREN RPAREN
 %token <number> UNTERMINATED_STRING
 %token <string> STRING WORD
 %token <string> CPP_INCLUDE_ANGLE
+%token END
+%token INCLUDE
+%token INTERFACE
+%token MODULE
+%token SUBMODULE
+%token USE
 
 /*-------------------------------------------------------------------------*/
 /* grammar */
@@ -103,161 +93,118 @@ static bool cmFortranParserIsKeyword(const char* word,
 
 code: /* empty */ | code stmt;
 
-stmt: keyword_stmt | assignment_stmt;
-
-assignment_stmt: WORD ASSIGNMENT_OP other EOSTMT    /* Ignore */
-    {
-    free($1);
-    }
-
-keyword_stmt:
-  WORD EOSTMT
-    {
-    if (cmFortranParserIsKeyword($1, "interface"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, true);
-      }
-    free($1);
-    }
-| WORD WORD other EOSTMT
-    {
-    if (cmFortranParserIsKeyword($1, "use"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, $2);
-      }
-    else if (cmFortranParserIsKeyword($1, "module"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleModule(parser, $2);
-      }
-    else if (cmFortranParserIsKeyword($1, "interface"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, true);
-      }
-    else if (cmFortranParserIsKeyword($2, "interface") &&
-             cmFortranParserIsKeyword($1, "end"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_SetInInterface(parser, false);
-      }
-    free($1);
+stmt:
+  INTERFACE EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, true);
+  }
+| USE WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, $2);
     free($2);
+  }
+| MODULE WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    if (cmsysString_strcasecmp($2, "function") != 0 &&
+        cmsysString_strcasecmp($2, "procedure") != 0 &&
+        cmsysString_strcasecmp($2, "subroutine") != 0) {
+      cmFortranParser_RuleModule(parser, $2);
     }
-| WORD DCOLON WORD other EOSTMT
-    {
-    if (cmFortranParserIsKeyword($1, "use"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, $3);
-      }
-    free($1);
+    free($2);
+  }
+| SUBMODULE LPAREN WORD RPAREN WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, $3);
     free($3);
-    }
-| WORD COMMA WORD DCOLON WORD other EOSTMT
-    {
-    if (cmFortranParserIsKeyword($1, "use") &&
-        cmFortranParserIsKeyword($3, "non_intrinsic") )
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleUse(parser, $5);
-      }
-    free($1);
+    free($5);
+  }
+| SUBMODULE LPAREN WORD COLON WORD RPAREN WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, $3);
     free($3);
     free($5);
-    }
-| WORD STRING other EOSTMT /* Ignore */
-    {
-    if (cmFortranParserIsKeyword($1, "include"))
-      {
-      cmFortranParser* parser =
-        cmFortran_yyget_extra(yyscanner);
-      cmFortranParser_RuleInclude(parser, $2);
-      }
-    free($1);
+    free($7);
+  }
+| INTERFACE WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, true);
     free($2);
+  }
+| END INTERFACE other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_SetInInterface(parser, false);
+  }
+| USE DCOLON WORD other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleUse(parser, $3);
+    free($3);
+  }
+| USE COMMA WORD DCOLON WORD other EOSTMT {
+    if (cmsysString_strcasecmp($3, "non_intrinsic") == 0) {
+      cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+      cmFortranParser_RuleUse(parser, $5);
     }
-| CPP_LINE_DIRECTIVE STRING other EOSTMT
-    {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
+    free($3);
+    free($5);
+  }
+| INCLUDE STRING other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
+    cmFortranParser_RuleInclude(parser, $2);
+    free($2);
+  }
+| CPP_LINE_DIRECTIVE STRING other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleLineDirective(parser, $2);
     free($2);
-    }
-| CPP_INCLUDE_ANGLE other EOSTMT
-    {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
+  }
+| CPP_INCLUDE_ANGLE other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleInclude(parser, $1);
     free($1);
-    }
-| include STRING other EOSTMT
-    {
-    cmFortranParser* parser =
-      cmFortran_yyget_extra(yyscanner);
+  }
+| include STRING other EOSTMT {
+    cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleInclude(parser, $2);
     free($2);
-    }
-| define WORD other EOSTMT
-    {
+  }
+| define WORD other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleDefine(parser, $2);
     free($2);
-    }
-| undef WORD other EOSTMT
-    {
+  }
+| undef WORD other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleUndef(parser, $2);
     free($2);
-    }
-| ifdef WORD other EOSTMT
-    {
+  }
+| ifdef WORD other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleIfdef(parser, $2);
     free($2);
-    }
-| ifndef WORD other EOSTMT
-    {
+  }
+| ifndef WORD other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleIfndef(parser, $2);
     free($2);
-    }
-| if other EOSTMT
-    {
+  }
+| if other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleIf(parser);
-    }
-| elif other EOSTMT
-    {
+  }
+| elif other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleElif(parser);
-    }
-| else other EOSTMT
-    {
+  }
+| else other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleElse(parser);
-    }
-| endif other EOSTMT
-    {
+  }
+| endif other EOSTMT {
     cmFortranParser* parser = cmFortran_yyget_extra(yyscanner);
     cmFortranParser_RuleEndif(parser);
-    }
-| WORD GARBAGE other EOSTMT             /* Ignore */
-    {
-    free($1);
-    }
-| GARBAGE other EOSTMT
+  }
 | EOSTMT
-| error
+| error EOSTMT /* tolerate unknown statements until their end */
 ;
 
 
@@ -275,10 +222,19 @@ other: /* empty */ | other misc_code ;
 
 misc_code:
   WORD                { free ($1); }
+| END
+| INCLUDE
+| INTERFACE
+| MODULE
+| SUBMODULE
+| USE
 | STRING              { free ($1); }
 | GARBAGE
 | ASSIGNMENT_OP
+| COLON
 | DCOLON
+| LPAREN
+| RPAREN
 | COMMA
 | UNTERMINATED_STRING
 ;
diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx
index 934e928..23f881a 100644
--- a/Source/cmFortranParserImpl.cxx
+++ b/Source/cmFortranParserImpl.cxx
@@ -1,18 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFortranParser.h"
-
+#include "cmFortranLexer.h"
 #include "cmSystemTools.h"
+
 #include <assert.h>
+#include <cmConfigure.h>
+#include <set>
+#include <stack>
+#include <stdio.h>
+#include <string>
+#include <vector>
 
 bool cmFortranParser_s::FindIncludeFile(const char* dir,
                                         const char* includeName,
@@ -22,29 +20,27 @@ bool cmFortranParser_s::FindIncludeFile(const char* dir,
   if (cmSystemTools::FileIsFullPath(includeName)) {
     fileName = includeName;
     return cmSystemTools::FileExists(fileName.c_str(), true);
-  } else {
-    // Check for the file in the directory containing the including
-    // file.
-    std::string fullName = dir;
+  }
+  // Check for the file in the directory containing the including
+  // file.
+  std::string fullName = dir;
+  fullName += "/";
+  fullName += includeName;
+  if (cmSystemTools::FileExists(fullName.c_str(), true)) {
+    fileName = fullName;
+    return true;
+  }
+
+  // Search the include path for the file.
+  for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
+       i != this->IncludePath.end(); ++i) {
+    fullName = *i;
     fullName += "/";
     fullName += includeName;
     if (cmSystemTools::FileExists(fullName.c_str(), true)) {
       fileName = fullName;
       return true;
     }
-
-    // Search the include path for the file.
-    for (std::vector<std::string>::const_iterator i =
-           this->IncludePath.begin();
-         i != this->IncludePath.end(); ++i) {
-      fullName = *i;
-      fullName += "/";
-      fullName += includeName;
-      if (cmSystemTools::FileExists(fullName.c_str(), true)) {
-        fileName = fullName;
-        return true;
-      }
-    }
   }
   return false;
 }
@@ -65,7 +61,8 @@ cmFortranParser_s::cmFortranParser_s(std::vector<std::string> const& includes,
 
   // Create a dummy buffer that is never read but is the fallback
   // buffer when the last file is popped off the stack.
-  YY_BUFFER_STATE buffer = cmFortran_yy_create_buffer(0, 4, this->Scanner);
+  YY_BUFFER_STATE buffer =
+    cmFortran_yy_create_buffer(CM_NULLPTR, 4, this->Scanner);
   cmFortran_yy_switch_to_buffer(buffer, this->Scanner);
 }
 
@@ -83,13 +80,12 @@ bool cmFortranParser_FilePush(cmFortranParser* parser, const char* fname)
     std::string dir = cmSystemTools::GetParentDirectory(fname);
     cmFortranFile f(file, current, dir);
     YY_BUFFER_STATE buffer =
-      cmFortran_yy_create_buffer(0, 16384, parser->Scanner);
+      cmFortran_yy_create_buffer(CM_NULLPTR, 16384, parser->Scanner);
     cmFortran_yy_switch_to_buffer(buffer, parser->Scanner);
     parser->FileStack.push(f);
     return 1;
-  } else {
-    return 0;
   }
+  return 0;
 }
 
 bool cmFortranParser_FilePop(cmFortranParser* parser)
@@ -98,15 +94,14 @@ bool cmFortranParser_FilePop(cmFortranParser* parser)
   // to the next one on the stack.
   if (parser->FileStack.empty()) {
     return 0;
-  } else {
-    cmFortranFile f = parser->FileStack.top();
-    parser->FileStack.pop();
-    fclose(f.File);
-    YY_BUFFER_STATE current = cmFortranLexer_GetCurrentBuffer(parser->Scanner);
-    cmFortran_yy_delete_buffer(current, parser->Scanner);
-    cmFortran_yy_switch_to_buffer(f.Buffer, parser->Scanner);
-    return 1;
   }
+  cmFortranFile f = parser->FileStack.top();
+  parser->FileStack.pop();
+  fclose(f.File);
+  YY_BUFFER_STATE current = cmFortranLexer_GetCurrentBuffer(parser->Scanner);
+  cmFortran_yy_delete_buffer(current, parser->Scanner);
+  cmFortran_yy_switch_to_buffer(f.Buffer, parser->Scanner);
+  return 1;
 }
 
 int cmFortranParser_Input(cmFortranParser* parser, char* buffer,
@@ -115,8 +110,19 @@ int cmFortranParser_Input(cmFortranParser* parser, char* buffer,
   // Read from the file on top of the stack.  If the stack is empty,
   // the end of the translation unit has been reached.
   if (!parser->FileStack.empty()) {
-    FILE* file = parser->FileStack.top().File;
-    return (int)fread(buffer, 1, bufferSize, file);
+    cmFortranFile& ff = parser->FileStack.top();
+    FILE* file = ff.File;
+    size_t n = fread(buffer, 1, bufferSize, file);
+    if (n > 0) {
+      ff.LastCharWasNewline = buffer[n - 1] == '\n';
+    } else if (!ff.LastCharWasNewline) {
+      // The file ended without a newline.  Inject one so
+      // that the file always ends in an end-of-statement.
+      buffer[0] = '\n';
+      n = 1;
+      ff.LastCharWasNewline = true;
+    }
+    return (int)n;
   }
   return 0;
 }
@@ -160,11 +166,9 @@ int cmFortranParser_GetOldStartcond(cmFortranParser* parser)
   return parser->OldStartcond;
 }
 
-void cmFortranParser_Error(cmFortranParser*, const char*)
+void cmFortranParser_Error(cmFortranParser* parser, const char* msg)
 {
-  // If there is a parser error just ignore it.  The source will not
-  // compile and the user will edit it.  Then dependencies will have
-  // to be regenerated anyway.
+  parser->Error = msg ? msg : "unknown error";
 }
 
 void cmFortranParser_RuleUse(cmFortranParser* parser, const char* name)
diff --git a/Source/cmFortranParserTokens.h b/Source/cmFortranParserTokens.h
index ac49840..18b9e0a 100644
--- a/Source/cmFortranParserTokens.h
+++ b/Source/cmFortranParserTokens.h
@@ -1,8 +1,8 @@
-/* A Bison parser, made by GNU Bison 3.0.2.  */
+/* A Bison parser, made by GNU Bison 3.0.4.  */
 
 /* Bison interface for Yacc-like parsers in C
 
-   Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
+   Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -69,12 +69,20 @@ extern int cmFortran_yydebug;
     F90PPR_ELIF = 279,
     F90PPR_ENDIF = 280,
     COMMA = 281,
-    DCOLON = 282,
-    CPP_TOENDL = 283,
-    UNTERMINATED_STRING = 284,
-    STRING = 285,
-    WORD = 286,
-    CPP_INCLUDE_ANGLE = 287
+    COLON = 282,
+    DCOLON = 283,
+    LPAREN = 284,
+    RPAREN = 285,
+    UNTERMINATED_STRING = 286,
+    STRING = 287,
+    WORD = 288,
+    CPP_INCLUDE_ANGLE = 289,
+    END = 290,
+    INCLUDE = 291,
+    INTERFACE = 292,
+    MODULE = 293,
+    SUBMODULE = 294,
+    USE = 295
   };
 #endif
 /* Tokens.  */
@@ -102,24 +110,34 @@ extern int cmFortran_yydebug;
 #define F90PPR_ELIF 279
 #define F90PPR_ENDIF 280
 #define COMMA 281
-#define DCOLON 282
-#define CPP_TOENDL 283
-#define UNTERMINATED_STRING 284
-#define STRING 285
-#define WORD 286
-#define CPP_INCLUDE_ANGLE 287
+#define COLON 282
+#define DCOLON 283
+#define LPAREN 284
+#define RPAREN 285
+#define UNTERMINATED_STRING 286
+#define STRING 287
+#define WORD 288
+#define CPP_INCLUDE_ANGLE 289
+#define END 290
+#define INCLUDE 291
+#define INTERFACE 292
+#define MODULE 293
+#define SUBMODULE 294
+#define USE 295
 
 /* Value type.  */
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE YYSTYPE;
+
 union YYSTYPE
 {
-#line 81 "cmFortranParser.y" /* yacc.c:1909  */
+#line 75 "cmFortranParser.y" /* yacc.c:1909  */
 
   char* string;
 
-#line 122 "cmFortranParserTokens.h" /* yacc.c:1909  */
+#line 138 "cmFortranParserTokens.h" /* yacc.c:1909  */
 };
+
+typedef union YYSTYPE YYSTYPE;
 # define YYSTYPE_IS_TRIVIAL 1
 # define YYSTYPE_IS_DECLARED 1
 #endif
diff --git a/Source/cmFunctionBlocker.h b/Source/cmFunctionBlocker.h
index c7e3b71..388115d 100644
--- a/Source/cmFunctionBlocker.h
+++ b/Source/cmFunctionBlocker.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFunctionBlocker_h
 #define cmFunctionBlocker_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include "cmExecutionStatus.h"
diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx
index de9887e..99d883a 100644
--- a/Source/cmFunctionCommand.cxx
+++ b/Source/cmFunctionCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFunctionCommand.h"
 
 #include "cmake.h"
@@ -20,7 +11,7 @@ public:
   cmFunctionHelperCommand() {}
 
   ///! clean up any memory allocated by the function
-  ~cmFunctionHelperCommand() {}
+  ~cmFunctionHelperCommand() CM_OVERRIDE {}
 
   /**
    * This is used to avoid including this command
@@ -28,12 +19,12 @@ public:
    * cmMacroHelperCommand and cmFunctionHelperCommand
    * which cannot provide appropriate documentation.
    */
-  virtual bool ShouldAppearInDocumentation() const { return false; }
+  bool ShouldAppearInDocumentation() const CM_OVERRIDE { return false; }
 
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmFunctionHelperCommand* newC = new cmFunctionHelperCommand;
     // we must copy when we clone
@@ -47,16 +38,17 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -64,7 +56,7 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return this->Args[0]; }
+  std::string GetName() const CM_OVERRIDE { return this->Args[0]; }
 
   cmTypeMacro(cmFunctionHelperCommand, cmCommand);
 
@@ -168,10 +160,9 @@ bool cmFunctionFunctionBlocker::IsFunctionBlocked(
       // remove the function blocker now that the function is defined
       mf.RemoveFunctionBlocker(this, lff);
       return true;
-    } else {
-      // decrement for each nested function that ends
-      this->Depth--;
     }
+    // decrement for each nested function that ends
+    this->Depth--;
   }
 
   // if it wasn't an endfunction and we are not executing then we must be
@@ -201,7 +192,7 @@ bool cmFunctionFunctionBlocker::ShouldRemove(const cmListFileFunction& lff,
 bool cmFunctionCommand::InitialPass(std::vector<std::string> const& args,
                                     cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h
index 08f7f0f..277708b 100644
--- a/Source/cmFunctionCommand.h
+++ b/Source/cmFunctionCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmFunctionCommand_h
 #define cmFunctionCommand_h
 
@@ -20,10 +11,10 @@ class cmFunctionFunctionBlocker : public cmFunctionBlocker
 {
 public:
   cmFunctionFunctionBlocker() { this->Depth = 0; }
-  virtual ~cmFunctionFunctionBlocker() {}
-  virtual bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
-                                 cmExecutionStatus&);
-  virtual bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf);
+  ~cmFunctionFunctionBlocker() CM_OVERRIDE {}
+  bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
+                         cmExecutionStatus&) CM_OVERRIDE;
+  bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE;
 
   std::vector<std::string> Args;
   std::vector<cmListFileFunction> Functions;
@@ -37,24 +28,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmFunctionCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmFunctionCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "function"; }
+  std::string GetName() const CM_OVERRIDE { return "function"; }
 
   cmTypeMacro(cmFunctionCommand, cmCommand);
 };
diff --git a/Source/cmGeneratedFileStream.cxx b/Source/cmGeneratedFileStream.cxx
index 2c05913..02717a4 100644
--- a/Source/cmGeneratedFileStream.cxx
+++ b/Source/cmGeneratedFileStream.cxx
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratedFileStream.h"
 
 #include "cmSystemTools.h"
 
+#include <stdio.h>
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include <cm_zlib.h>
 #endif
@@ -42,7 +35,7 @@ cmGeneratedFileStream::~cmGeneratedFileStream()
   // stream will be destroyed which will close the temporary file.
   // Finally the base destructor will be called to replace the
   // destination file.
-  this->Okay = (*this) ? true : false;
+  this->Okay = !this->fail();
 }
 
 cmGeneratedFileStream& cmGeneratedFileStream::Open(const char* name,
@@ -56,7 +49,7 @@ cmGeneratedFileStream& cmGeneratedFileStream::Open(const char* name,
     this->Stream::open(this->TempName.c_str(),
                        std::ios::out | std::ios::binary);
   } else {
-    this->Stream::open(this->TempName.c_str(), std::ios::out);
+    this->Stream::open(this->TempName.c_str());
   }
 
   // Check if the file opened.
@@ -71,7 +64,7 @@ cmGeneratedFileStream& cmGeneratedFileStream::Open(const char* name,
 bool cmGeneratedFileStream::Close()
 {
   // Save whether the temporary output file is valid before closing.
-  this->Okay = (*this) ? true : false;
+  this->Okay = !this->fail();
 
   // Close the temporary output file.
   this->Stream::close();
diff --git a/Source/cmGeneratedFileStream.h b/Source/cmGeneratedFileStream.h
index a2de5bc..515954c 100644
--- a/Source/cmGeneratedFileStream.h
+++ b/Source/cmGeneratedFileStream.h
@@ -1,20 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratedFileStream_h
 #define cmGeneratedFileStream_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include <cmsys/FStream.hxx>
+#include <string>
 
 // This is the first base class of cmGeneratedFileStream.  It will be
 // created before and destroyed after the ofstream portion and can
@@ -99,7 +91,7 @@ public:
    * file was successfully written before allowing the original to be
    * replaced.
    */
-  ~cmGeneratedFileStream();
+  ~cmGeneratedFileStream() CM_OVERRIDE;
 
   /**
    * Open an output file by name.  This should be used only with a
diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx
index 53243b8..34f763c 100644
--- a/Source/cmGeneratorExpression.cxx
+++ b/Source/cmGeneratorExpression.cxx
@@ -1,24 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpression.h"
 
 #include "assert.h"
 #include "cmAlgorithms.h"
-#include "cmSystemTools.h"
-
-#include "cmGeneratorExpressionDAGChecker.h"
+#include "cmGeneratorExpressionContext.h"
 #include "cmGeneratorExpressionEvaluator.h"
 #include "cmGeneratorExpressionLexer.h"
 #include "cmGeneratorExpressionParser.h"
+#include "cmSystemTools.h"
+
+#include <cmsys/RegularExpression.hxx>
+#include <utility>
 
 cmGeneratorExpression::cmGeneratorExpression(
   const cmListFileBacktrace& backtrace)
@@ -26,14 +19,14 @@ cmGeneratorExpression::cmGeneratorExpression(
 {
 }
 
-cmsys::auto_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
+CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
   std::string const& input)
 {
-  return cmsys::auto_ptr<cmCompiledGeneratorExpression>(
+  return CM_AUTO_PTR<cmCompiledGeneratorExpression>(
     new cmCompiledGeneratorExpression(this->Backtrace, input));
 }
 
-cmsys::auto_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
+CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
   const char* input)
 {
   return this->Parse(std::string(input ? input : ""));
@@ -352,7 +345,8 @@ std::string cmGeneratorExpression::Preprocess(const std::string& input,
 {
   if (context == StripAllGeneratorExpressions) {
     return stripAllGeneratorExpressions(input);
-  } else if (context == BuildInterface || context == InstallInterface) {
+  }
+  if (context == BuildInterface || context == InstallInterface) {
     return stripExportInterface(input, context, resolveRelative);
   }
 
diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h
index 71fbba3..8f82a6b 100644
--- a/Source/cmGeneratorExpression.h
+++ b/Source/cmGeneratorExpression.h
@@ -1,34 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpression_h
 #define cmGeneratorExpression_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include "cmListFileCache.h"
 
-#include <cmsys/RegularExpression.hxx>
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
+class cmCompiledGeneratorExpression;
 class cmGeneratorTarget;
 class cmLocalGenerator;
-class cmListFileBacktrace;
-
-struct cmGeneratorExpressionEvaluator;
 struct cmGeneratorExpressionContext;
 struct cmGeneratorExpressionDAGChecker;
-
-class cmCompiledGeneratorExpression;
+struct cmGeneratorExpressionEvaluator;
 
 /** \class cmGeneratorExpression
  * \brief Evaluate generate-time query expression syntax.
@@ -47,9 +37,8 @@ public:
     cmListFileBacktrace const& backtrace = cmListFileBacktrace());
   ~cmGeneratorExpression();
 
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> Parse(
-    std::string const& input);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> Parse(const char* input);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(std::string const& input);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(const char* input);
 
   enum PreprocessContext
   {
@@ -81,12 +70,12 @@ private:
 class cmCompiledGeneratorExpression
 {
 public:
-  const char* Evaluate(cmLocalGenerator* lg, const std::string& config,
-                       bool quiet = false,
-                       cmGeneratorTarget const* headTarget = 0,
-                       cmGeneratorTarget const* currentTarget = 0,
-                       cmGeneratorExpressionDAGChecker* dagChecker = 0,
-                       std::string const& language = std::string()) const;
+  const char* Evaluate(
+    cmLocalGenerator* lg, const std::string& config, bool quiet = false,
+    cmGeneratorTarget const* headTarget = CM_NULLPTR,
+    cmGeneratorTarget const* currentTarget = CM_NULLPTR,
+    cmGeneratorExpressionDAGChecker* dagChecker = CM_NULLPTR,
+    std::string const& language = std::string()) const;
   const char* Evaluate(cmLocalGenerator* lg, const std::string& config,
                        bool quiet, cmGeneratorTarget const* headTarget,
                        cmGeneratorExpressionDAGChecker* dagChecker,
diff --git a/Source/cmGeneratorExpressionContext.cxx b/Source/cmGeneratorExpressionContext.cxx
index 8da6b50..a6dde5d 100644
--- a/Source/cmGeneratorExpressionContext.cxx
+++ b/Source/cmGeneratorExpressionContext.cxx
@@ -1,19 +1,7 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionContext.h"
 
-#include "cmGeneratorTarget.h"
-
 cmGeneratorExpressionContext::cmGeneratorExpressionContext(
   cmLocalGenerator* lg, std::string const& config, bool quiet,
   cmGeneratorTarget const* headTarget, const cmGeneratorTarget* currentTarget,
diff --git a/Source/cmGeneratorExpressionContext.h b/Source/cmGeneratorExpressionContext.h
index cff7289..cf292dc 100644
--- a/Source/cmGeneratorExpressionContext.h
+++ b/Source/cmGeneratorExpressionContext.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionContext_h
 #define cmGeneratorExpressionContext_h
 
diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx
index c700156..aff1ecd 100644
--- a/Source/cmGeneratorExpressionDAGChecker.cxx
+++ b/Source/cmGeneratorExpressionDAGChecker.cxx
@@ -1,19 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionDAGChecker.h"
 
 #include "cmAlgorithms.h"
+#include "cmGeneratorExpressionContext.h"
+#include "cmGeneratorExpressionEvaluator.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalGenerator.h"
+#include "cmake.h"
+
+#include <sstream>
+#include <string.h>
+#include <utility>
 
 cmGeneratorExpressionDAGChecker::cmGeneratorExpressionDAGChecker(
   const cmListFileBacktrace& backtrace, const std::string& target,
@@ -198,7 +196,7 @@ enum TransitiveProperty
 };
 
 template <TransitiveProperty>
-bool additionalTest(const char* const)
+bool additionalTest(const char* const /*unused*/)
 {
   return false;
 }
diff --git a/Source/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h
index 28ca824..8f10259 100644
--- a/Source/cmGeneratorExpressionDAGChecker.h
+++ b/Source/cmGeneratorExpressionDAGChecker.h
@@ -1,20 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionDAGChecker_h
 #define cmGeneratorExpressionDAGChecker_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
+
+#include "cmListFileCache.h"
+
+#include <map>
+#include <set>
+#include <string>
 
-#include "cmGeneratorExpressionEvaluator.h"
+struct GeneratorExpressionContent;
+struct cmGeneratorExpressionContext;
 
 #define CM_SELECT_BOTH(F, A1, A2) F(A1, A2)
 #define CM_SELECT_FIRST(F, A1, A2) F(A1)
@@ -63,7 +61,7 @@ struct cmGeneratorExpressionDAGChecker
   void ReportError(cmGeneratorExpressionContext* context,
                    const std::string& expr);
 
-  bool EvaluatingLinkLibraries(const char* tgt = 0);
+  bool EvaluatingLinkLibraries(const char* tgt = CM_NULLPTR);
 
 #define DECLARE_TRANSITIVE_PROPERTY_METHOD(METHOD) bool METHOD() const;
 
diff --git a/Source/cmGeneratorExpressionEvaluationFile.cxx b/Source/cmGeneratorExpressionEvaluationFile.cxx
index 5b48eea..c6c4c3a 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.cxx
+++ b/Source/cmGeneratorExpressionEvaluationFile.cxx
@@ -1,31 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionEvaluationFile.h"
 
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
+#include "cmListFileCache.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include <cmsys/FStream.hxx>
+#include "cmSystemTools.h"
+#include "cmake.h"
 
-#include <assert.h>
+#include <cmConfigure.h>
+#include <cmsys/FStream.hxx>
+#include <sstream>
+#include <utility>
 
 cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile(
   const std::string& input,
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> outputFileExpr,
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> condition,
-  bool inputIsContent)
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent)
   : Input(input)
   , OutputFileExpr(outputFileExpr)
   , Condition(condition)
@@ -40,8 +34,8 @@ void cmGeneratorExpressionEvaluationFile::Generate(
 {
   std::string rawCondition = this->Condition->GetInput();
   if (!rawCondition.empty()) {
-    std::string condResult =
-      this->Condition->Evaluate(lg, config, false, 0, 0, 0, lang);
+    std::string condResult = this->Condition->Evaluate(
+      lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
     if (condResult == "0") {
       return;
     }
@@ -56,10 +50,10 @@ void cmGeneratorExpressionEvaluationFile::Generate(
     }
   }
 
-  const std::string outputFileName =
-    this->OutputFileExpr->Evaluate(lg, config, false, 0, 0, 0, lang);
-  const std::string outputContent =
-    inputExpression->Evaluate(lg, config, false, 0, 0, 0, lang);
+  const std::string outputFileName = this->OutputFileExpr->Evaluate(
+    lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
+  const std::string outputContent = inputExpression->Evaluate(
+    lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
 
   std::map<std::string, std::string>::iterator it =
     outputFiles.find(outputFileName);
@@ -97,8 +91,8 @@ void cmGeneratorExpressionEvaluationFile::CreateOutputFile(
 
   for (std::vector<std::string>::const_iterator le = enabledLanguages.begin();
        le != enabledLanguages.end(); ++le) {
-    std::string name =
-      this->OutputFileExpr->Evaluate(lg, config, false, 0, 0, 0, *le);
+    std::string name = this->OutputFileExpr->Evaluate(
+      lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, *le);
     cmSourceFile* sf = lg->GetMakefile()->GetOrCreateSource(name);
     sf->SetProperty("GENERATED", "1");
 
@@ -135,7 +129,7 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg)
 
   cmListFileBacktrace lfbt = this->OutputFileExpr->GetBacktrace();
   cmGeneratorExpression contentGE(lfbt);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> inputExpression =
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> inputExpression =
     contentGE.Parse(inputContent);
 
   std::map<std::string, std::string> outputFiles;
diff --git a/Source/cmGeneratorExpressionEvaluationFile.h b/Source/cmGeneratorExpressionEvaluationFile.h
index bfd6add..d597270 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.h
+++ b/Source/cmGeneratorExpressionEvaluationFile.h
@@ -1,21 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionEvaluationFile_h
 #define cmGeneratorExpressionEvaluationFile_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmGeneratorExpression.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
+#include <map>
+#include <string>
 #include <sys/types.h>
+#include <vector>
 
 class cmLocalGenerator;
 
@@ -24,9 +20,8 @@ class cmGeneratorExpressionEvaluationFile
 public:
   cmGeneratorExpressionEvaluationFile(
     const std::string& input,
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> outputFileExpr,
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> condition,
-    bool inputIsContent);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent);
 
   void Generate(cmLocalGenerator* lg);
 
@@ -42,8 +37,8 @@ private:
 
 private:
   const std::string Input;
-  const cmsys::auto_ptr<cmCompiledGeneratorExpression> OutputFileExpr;
-  const cmsys::auto_ptr<cmCompiledGeneratorExpression> Condition;
+  const CM_AUTO_PTR<cmCompiledGeneratorExpression> OutputFileExpr;
+  const CM_AUTO_PTR<cmCompiledGeneratorExpression> Condition;
   std::vector<std::string> Files;
   const bool InputIsContent;
 };
diff --git a/Source/cmGeneratorExpressionEvaluator.cxx b/Source/cmGeneratorExpressionEvaluator.cxx
index 66437eb..6ce4a8e 100644
--- a/Source/cmGeneratorExpressionEvaluator.cxx
+++ b/Source/cmGeneratorExpressionEvaluator.cxx
@@ -1,32 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionEvaluator.h"
 
 #include "cmAlgorithms.h"
-#include "cmGeneratorExpression.h"
-#include "cmGeneratorExpressionDAGChecker.h"
-#include "cmGeneratorExpressionParser.h"
-#include "cmGlobalGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
-#include "cmSourceFile.h"
-
-#include <cmsys/String.h>
-
-#include <assert.h>
-#include <errno.h>
-
+#include "cmGeneratorExpressionContext.h"
 #include "cmGeneratorExpressionNode.h"
 
+#include <algorithm>
+#include <sstream>
+
 GeneratorExpressionContent::GeneratorExpressionContent(
   const char* startContent, size_t length)
   : StartContent(startContent)
@@ -154,20 +136,19 @@ std::string GeneratorExpressionContent::EvaluateParameters(
           node, identifier, context, dagChecker, pit);
         parameters.push_back(lastParam);
         return std::string();
-      } else {
-        std::string parameter;
-        std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it =
-          pit->begin();
-        const std::vector<cmGeneratorExpressionEvaluator*>::const_iterator
-          end = pit->end();
-        for (; it != end; ++it) {
-          parameter += (*it)->Evaluate(context, dagChecker);
-          if (context->HadError) {
-            return std::string();
-          }
+      }
+      std::string parameter;
+      std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it =
+        pit->begin();
+      const std::vector<cmGeneratorExpressionEvaluator*>::const_iterator end =
+        pit->end();
+      for (; it != end; ++it) {
+        parameter += (*it)->Evaluate(context, dagChecker);
+        if (context->HadError) {
+          return std::string();
         }
-        parameters.push_back(parameter);
       }
+      parameters.push_back(parameter);
     }
   }
 
diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h
index 7ca62c5..122e9cf 100644
--- a/Source/cmGeneratorExpressionEvaluator.h
+++ b/Source/cmGeneratorExpressionEvaluator.h
@@ -1,24 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionEvaluator_h
 #define cmGeneratorExpressionEvaluator_h
 
-#include "cmGeneratorExpressionContext.h"
-
-#include "cmListFileCache.h"
+#include <cmConfigure.h>
 
+#include <stddef.h>
 #include <string>
 #include <vector>
 
+struct cmGeneratorExpressionContext;
 struct cmGeneratorExpressionDAGChecker;
 struct cmGeneratorExpressionNode;
 
@@ -52,12 +43,15 @@ struct TextContent : public cmGeneratorExpressionEvaluator
   }
 
   std::string Evaluate(cmGeneratorExpressionContext*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE
   {
     return std::string(this->Content, this->Length);
   }
 
-  Type GetType() const { return cmGeneratorExpressionEvaluator::Text; }
+  Type GetType() const CM_OVERRIDE
+  {
+    return cmGeneratorExpressionEvaluator::Text;
+  }
 
   void Extend(size_t length) { this->Length += length; }
 
@@ -82,14 +76,17 @@ struct GeneratorExpressionContent : public cmGeneratorExpressionEvaluator
     this->ParamChildren = parameters;
   }
 
-  Type GetType() const { return cmGeneratorExpressionEvaluator::Generator; }
+  Type GetType() const CM_OVERRIDE
+  {
+    return cmGeneratorExpressionEvaluator::Generator;
+  }
 
   std::string Evaluate(cmGeneratorExpressionContext* context,
-                       cmGeneratorExpressionDAGChecker*) const;
+                       cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE;
 
   std::string GetOriginalExpression() const;
 
-  ~GeneratorExpressionContent();
+  ~GeneratorExpressionContent() CM_OVERRIDE;
 
 private:
   std::string EvaluateParameters(const cmGeneratorExpressionNode* node,
diff --git a/Source/cmGeneratorExpressionLexer.cxx b/Source/cmGeneratorExpressionLexer.cxx
index 5a4eccc..931fd4d 100644
--- a/Source/cmGeneratorExpressionLexer.cxx
+++ b/Source/cmGeneratorExpressionLexer.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionLexer.h"
 
 cmGeneratorExpressionLexer::cmGeneratorExpressionLexer()
diff --git a/Source/cmGeneratorExpressionLexer.h b/Source/cmGeneratorExpressionLexer.h
index 72ad731..cac255d 100644
--- a/Source/cmGeneratorExpressionLexer.h
+++ b/Source/cmGeneratorExpressionLexer.h
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionLexer_h
 #define cmGeneratorExpressionLexer_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
+#include <stddef.h>
+#include <string>
 #include <vector>
 
 struct cmGeneratorExpressionToken
diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx
index e750551..f866605 100644
--- a/Source/cmGeneratorExpressionNode.cxx
+++ b/Source/cmGeneratorExpressionNode.cxx
@@ -1,21 +1,38 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionNode.h"
 
 #include "cmAlgorithms.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorExpressionContext.h"
+#include "cmGeneratorExpressionDAGChecker.h"
+#include "cmGeneratorExpressionEvaluator.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
+#include <algorithm>
+#include <assert.h>
+#include <cmConfigure.h>
+#include <cmsys/RegularExpression.hxx>
+#include <cmsys/String.h>
+#include <errno.h>
+#include <map>
+#include <set>
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
 
 std::string cmGeneratorExpressionNode::EvaluateDependentExpression(
   std::string const& prop, cmLocalGenerator* lg,
@@ -24,7 +41,7 @@ std::string cmGeneratorExpressionNode::EvaluateDependentExpression(
   cmGeneratorExpressionDAGChecker* dagChecker)
 {
   cmGeneratorExpression ge(context->Backtrace);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
   cge->SetEvaluateForBuildsystem(context->EvaluateForBuildsystem);
   std::string result =
     cge->Evaluate(lg, context->Config, context->Quiet, headTarget,
@@ -42,14 +59,15 @@ static const struct ZeroNode : public cmGeneratorExpressionNode
 {
   ZeroNode() {}
 
-  virtual bool GeneratesContent() const { return false; }
+  bool GeneratesContent() const CM_OVERRIDE { return false; }
 
-  virtual bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
-  std::string Evaluate(const std::vector<std::string>&,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return std::string();
   }
@@ -59,12 +77,13 @@ static const struct OneNode : public cmGeneratorExpressionNode
 {
   OneNode() {}
 
-  virtual bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return parameters.front();
   }
@@ -90,7 +109,8 @@ static const struct ZeroNode installInterfaceNode;
       for (; it != end; ++it) {                                               \
         if (*it == #FAILURE_VALUE) {                                          \
           return #FAILURE_VALUE;                                              \
-        } else if (*it != #SUCCESS_VALUE) {                                   \
+        }                                                                     \
+        if (*it != #SUCCESS_VALUE) {                                          \
           reportError(context, content->GetOriginalExpression(),              \
                       "Parameters to $<" #OP                                  \
                       "> must resolve to either '0' or '1'.");                \
@@ -113,7 +133,8 @@ static const struct NotNode : public cmGeneratorExpressionNode
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     if (*parameters.begin() != "0" && *parameters.begin() != "1") {
       reportError(
@@ -129,12 +150,13 @@ static const struct BoolNode : public cmGeneratorExpressionNode
 {
   BoolNode() {}
 
-  virtual int NumExpectedParameters() const { return 1; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 1; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return !cmSystemTools::IsOff(parameters.begin()->c_str()) ? "1" : "0";
   }
@@ -144,12 +166,13 @@ static const struct StrEqualNode : public cmGeneratorExpressionNode
 {
   StrEqualNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return *parameters.begin() == parameters[1] ? "1" : "0";
   }
@@ -159,12 +182,13 @@ static const struct EqualNode : public cmGeneratorExpressionNode
 {
   EqualNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     char* pEnd;
 
@@ -236,12 +260,13 @@ static const struct LowerCaseNode : public cmGeneratorExpressionNode
 {
   LowerCaseNode() {}
 
-  bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::LowerCase(parameters.front());
   }
@@ -251,12 +276,13 @@ static const struct UpperCaseNode : public cmGeneratorExpressionNode
 {
   UpperCaseNode() {}
 
-  bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::UpperCase(parameters.front());
   }
@@ -266,12 +292,13 @@ static const struct MakeCIdentifierNode : public cmGeneratorExpressionNode
 {
   MakeCIdentifierNode() {}
 
-  bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::MakeCidentifier(parameters.front());
   }
@@ -281,12 +308,13 @@ static const struct Angle_RNode : public cmGeneratorExpressionNode
 {
   Angle_RNode() {}
 
-  virtual int NumExpectedParameters() const { return 0; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 0; }
 
-  std::string Evaluate(const std::vector<std::string>&,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return ">";
   }
@@ -296,12 +324,13 @@ static const struct CommaNode : public cmGeneratorExpressionNode
 {
   CommaNode() {}
 
-  virtual int NumExpectedParameters() const { return 0; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 0; }
 
-  std::string Evaluate(const std::vector<std::string>&,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return ",";
   }
@@ -311,12 +340,13 @@ static const struct SemicolonNode : public cmGeneratorExpressionNode
 {
   SemicolonNode() {}
 
-  virtual int NumExpectedParameters() const { return 0; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 0; }
 
-  std::string Evaluate(const std::vector<std::string>&,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return ";";
   }
@@ -326,12 +356,12 @@ struct CompilerIdNode : public cmGeneratorExpressionNode
 {
   CompilerIdNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrZeroParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
 
   std::string EvaluateWithLanguage(const std::vector<std::string>& parameters,
                                    cmGeneratorExpressionContext* context,
                                    const GeneratorExpressionContent* content,
-                                   cmGeneratorExpressionDAGChecker*,
+                                   cmGeneratorExpressionDAGChecker* /*unused*/,
                                    const std::string& lang) const
   {
     const char* compilerId = context->LG->GetMakefile()->GetSafeDefinition(
@@ -381,6 +411,7 @@ static const struct CCompilerIdNode : public CompilerIdNode
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     if (!context->HeadTarget) {
       reportError(
@@ -402,6 +433,7 @@ static const struct CXXCompilerIdNode : public CompilerIdNode
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     if (!context->HeadTarget) {
       reportError(
@@ -419,12 +451,12 @@ struct CompilerVersionNode : public cmGeneratorExpressionNode
 {
   CompilerVersionNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrZeroParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
 
   std::string EvaluateWithLanguage(const std::vector<std::string>& parameters,
                                    cmGeneratorExpressionContext* context,
                                    const GeneratorExpressionContent* content,
-                                   cmGeneratorExpressionDAGChecker*,
+                                   cmGeneratorExpressionDAGChecker* /*unused*/,
                                    const std::string& lang) const
   {
     const char* compilerVersion =
@@ -460,6 +492,7 @@ static const struct CCompilerVersionNode : public CompilerVersionNode
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     if (!context->HeadTarget) {
       reportError(
@@ -481,6 +514,7 @@ static const struct CxxCompilerVersionNode : public CompilerVersionNode
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     if (!context->HeadTarget) {
       reportError(
@@ -498,12 +532,13 @@ struct PlatformIdNode : public cmGeneratorExpressionNode
 {
   PlatformIdNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrZeroParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     const char* platformId =
       context->LG->GetMakefile()->GetSafeDefinition("CMAKE_SYSTEM_NAME");
@@ -526,12 +561,13 @@ static const struct VersionGreaterNode : public cmGeneratorExpressionNode
 {
   VersionGreaterNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER,
                                          parameters.front().c_str(),
@@ -541,16 +577,37 @@ static const struct VersionGreaterNode : public cmGeneratorExpressionNode
   }
 } versionGreaterNode;
 
+static const struct VersionGreaterEqNode : public cmGeneratorExpressionNode
+{
+  VersionGreaterEqNode() {}
+
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+
+  std::string Evaluate(const std::vector<std::string>& parameters,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
+  {
+    return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
+                                         parameters.front().c_str(),
+                                         parameters[1].c_str())
+      ? "1"
+      : "0";
+  }
+} versionGreaterEqNode;
+
 static const struct VersionLessNode : public cmGeneratorExpressionNode
 {
   VersionLessNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
                                          parameters.front().c_str(),
@@ -560,16 +617,37 @@ static const struct VersionLessNode : public cmGeneratorExpressionNode
   }
 } versionLessNode;
 
+static const struct VersionLessEqNode : public cmGeneratorExpressionNode
+{
+  VersionLessEqNode() {}
+
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+
+  std::string Evaluate(const std::vector<std::string>& parameters,
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
+  {
+    return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS_EQUAL,
+                                         parameters.front().c_str(),
+                                         parameters[1].c_str())
+      ? "1"
+      : "0";
+  }
+} versionLessEqNode;
+
 static const struct VersionEqualNode : public cmGeneratorExpressionNode
 {
   VersionEqualNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL,
                                          parameters.front().c_str(),
@@ -584,14 +662,20 @@ static const struct LinkOnlyNode : public cmGeneratorExpressionNode
   LinkOnlyNode() {}
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
+                       cmGeneratorExpressionContext* context,
+                       const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
+    if (!dagChecker) {
+      reportError(context, content->GetOriginalExpression(),
+                  "$<LINK_ONLY:...> may only be used for linking");
+      return std::string();
+    }
     if (!dagChecker->GetTransitivePropertiesOnly()) {
       return parameters.front();
     }
-    return "";
+    return std::string();
   }
 } linkOnlyNode;
 
@@ -599,12 +683,13 @@ static const struct ConfigurationNode : public cmGeneratorExpressionNode
 {
   ConfigurationNode() {}
 
-  virtual int NumExpectedParameters() const { return 0; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 0; }
 
-  std::string Evaluate(const std::vector<std::string>&,
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
                        cmGeneratorExpressionContext* context,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     context->HadContextSensitiveCondition = true;
     return context->Config;
@@ -615,15 +700,17 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode
 {
   ConfigurationTestNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrZeroParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     if (parameters.empty()) {
-      return configurationNode.Evaluate(parameters, context, content, 0);
+      return configurationNode.Evaluate(parameters, context, content,
+                                        CM_NULLPTR);
     }
     static cmsys::RegularExpression configValidator("^[A-Za-z0-9_]*$");
     if (!configValidator.find(*parameters.begin())) {
@@ -642,8 +729,8 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode
     }
 
     if (context->CurrentTarget && context->CurrentTarget->IsImported()) {
-      const char* loc = 0;
-      const char* imp = 0;
+      const char* loc = CM_NULLPTR;
+      const char* imp = CM_NULLPTR;
       std::string suffix;
       if (context->CurrentTarget->Target->GetMappedConfig(
             context->Config, &loc, &imp, suffix)) {
@@ -673,14 +760,15 @@ static const struct JoinNode : public cmGeneratorExpressionNode
 {
   JoinNode() {}
 
-  virtual int NumExpectedParameters() const { return 2; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 2; }
 
-  virtual bool AcceptsArbitraryContentParameter() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     std::vector<std::string> list;
     cmSystemTools::ExpandListArgument(parameters.front(), list);
@@ -692,12 +780,13 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode
 {
   CompileLanguageNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrZeroParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     if (context->Language.empty()) {
       reportError(
@@ -724,7 +813,8 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode
                   "$<COMPILE_LANGUAGE:...> may not be used with Visual Studio "
                   "generators.");
       return std::string();
-    } else if (genName.find("Xcode") != std::string::npos) {
+    }
+    if (genName.find("Xcode") != std::string::npos) {
       if (dagChecker && (dagChecker->EvaluatingCompileDefinitions() ||
                          dagChecker->EvaluatingIncludeDirectories())) {
         reportError(
@@ -753,7 +843,7 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode
 #define TRANSITIVE_PROPERTY_NAME(PROPERTY) , "INTERFACE_" #PROPERTY
 
 static const char* targetPropertyTransitiveWhitelist[] = {
-  0 CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(TRANSITIVE_PROPERTY_NAME)
+  CM_NULLPTR CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(TRANSITIVE_PROPERTY_NAME)
 };
 
 #undef TRANSITIVE_PROPERTY_NAME
@@ -795,12 +885,13 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode
   TargetPropertyNode() {}
 
   // This node handles errors on parameter count itself.
-  virtual int NumExpectedParameters() const { return OneOrMoreParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagCheckerParent) const
+    CM_OVERRIDE
   {
     if (parameters.size() != 1 && parameters.size() != 2) {
       reportError(
@@ -1087,20 +1178,21 @@ static const struct TargetNameNode : public cmGeneratorExpressionNode
 {
   TargetNameNode() {}
 
-  virtual bool GeneratesContent() const { return true; }
+  bool GeneratesContent() const CM_OVERRIDE { return true; }
 
-  virtual bool AcceptsArbitraryContentParameter() const { return true; }
-  virtual bool RequiresLiteralInput() const { return true; }
+  bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+  bool RequiresLiteralInput() const CM_OVERRIDE { return true; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
-                       cmGeneratorExpressionContext*,
-                       const GeneratorExpressionContent*,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionContext* /*context*/,
+                       const GeneratorExpressionContent* /*content*/,
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     return parameters.front();
   }
 
-  virtual int NumExpectedParameters() const { return 1; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 1; }
 
 } targetNameNode;
 
@@ -1111,7 +1203,8 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     if (!context->EvaluateForBuildsystem) {
       std::ostringstream e;
@@ -1179,12 +1272,13 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
 {
   CompileFeaturesNode() {}
 
-  virtual int NumExpectedParameters() const { return OneOrMoreParameters; }
+  int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     cmGeneratorTarget const* target = context->HeadTarget;
     if (!target) {
@@ -1263,10 +1357,10 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
 } compileFeaturesNode;
 
 static const char* targetPolicyWhitelist[] = {
-  0
+  CM_NULLPTR
 #define TARGET_POLICY_STRING(POLICY) , #POLICY
 
-  CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING)
+    CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING)
 
 #undef TARGET_POLICY_STRING
 };
@@ -1306,12 +1400,13 @@ static const struct TargetPolicyNode : public cmGeneratorExpressionNode
 {
   TargetPolicyNode() {}
 
-  virtual int NumExpectedParameters() const { return 1; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 1; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     if (!context->HeadTarget) {
       reportError(
@@ -1365,13 +1460,14 @@ static const struct InstallPrefixNode : public cmGeneratorExpressionNode
 {
   InstallPrefixNode() {}
 
-  virtual bool GeneratesContent() const { return true; }
-  virtual int NumExpectedParameters() const { return 0; }
+  bool GeneratesContent() const CM_OVERRIDE { return true; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 0; }
 
-  std::string Evaluate(const std::vector<std::string>&,
+  std::string Evaluate(const std::vector<std::string>& /*parameters*/,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     reportError(context, content->GetOriginalExpression(),
                 "INSTALL_PREFIX is a marker for install(EXPORT) only.  It "
@@ -1381,13 +1477,12 @@ static const struct InstallPrefixNode : public cmGeneratorExpressionNode
 
 } installPrefixNode;
 
-class ArtifactNameTag;
+class ArtifactDirTag;
 class ArtifactLinkerTag;
-class ArtifactSonameTag;
-class ArtifactPdbTag;
-
+class ArtifactNameTag;
 class ArtifactPathTag;
-class ArtifactDirTag;
+class ArtifactPdbTag;
+class ArtifactSonameTag;
 
 template <typename ArtifactT>
 struct TargetFilesystemArtifactResultCreator
@@ -1488,7 +1583,7 @@ struct TargetFilesystemArtifactResultCreator<ArtifactNameTag>
 {
   static std::string Create(cmGeneratorTarget* target,
                             cmGeneratorExpressionContext* context,
-                            const GeneratorExpressionContent*)
+                            const GeneratorExpressionContent* /*unused*/)
   {
     return target->GetFullPath(context->Config, false, true);
   }
@@ -1529,12 +1624,13 @@ struct TargetFilesystemArtifact : public cmGeneratorExpressionNode
 {
   TargetFilesystemArtifact() {}
 
-  virtual int NumExpectedParameters() const { return 1; }
+  int NumExpectedParameters() const CM_OVERRIDE { return 1; }
 
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
                        cmGeneratorExpressionDAGChecker* dagChecker) const
+    CM_OVERRIDE
   {
     // Lookup the referenced target.
     std::string name = *parameters.begin();
@@ -1606,7 +1702,8 @@ static const struct ShellPathNode : public cmGeneratorExpressionNode
   std::string Evaluate(const std::vector<std::string>& parameters,
                        cmGeneratorExpressionContext* context,
                        const GeneratorExpressionContent* content,
-                       cmGeneratorExpressionDAGChecker*) const
+                       cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
+    CM_OVERRIDE
   {
     if (!cmSystemTools::FileIsFullPath(parameters.front())) {
       reportError(context, content->GetOriginalExpression(),
@@ -1632,7 +1729,9 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode(
     nodeMap["C_COMPILER_ID"] = &cCompilerIdNode;
     nodeMap["CXX_COMPILER_ID"] = &cxxCompilerIdNode;
     nodeMap["VERSION_GREATER"] = &versionGreaterNode;
+    nodeMap["VERSION_GREATER_EQUAL"] = &versionGreaterEqNode;
     nodeMap["VERSION_LESS"] = &versionLessNode;
+    nodeMap["VERSION_LESS_EQUAL"] = &versionLessEqNode;
     nodeMap["VERSION_EQUAL"] = &versionEqualNode;
     nodeMap["C_COMPILER_VERSION"] = &cCompilerVersionNode;
     nodeMap["CXX_COMPILER_VERSION"] = &cxxCompilerVersionNode;
@@ -1675,7 +1774,7 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode(
   }
   NodeMap::const_iterator i = nodeMap.find(identifier);
   if (i == nodeMap.end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return i->second;
 }
diff --git a/Source/cmGeneratorExpressionNode.h b/Source/cmGeneratorExpressionNode.h
index 3ee57eb..ecf745e 100644
--- a/Source/cmGeneratorExpressionNode.h
+++ b/Source/cmGeneratorExpressionNode.h
@@ -1,31 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionNode_h
 #define cmGeneratorExpressionNode_h
 
-#include "cmGeneratorExpression.h"
-
-#include "cmGeneratorExpressionDAGChecker.h"
-#include "cmGeneratorExpressionEvaluator.h"
-#include "cmGeneratorExpressionParser.h"
-#include "cmLocalGenerator.h"
-#include "cmSourceFile.h"
-
-#include <cmsys/String.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include <assert.h>
-#include <errno.h>
+#include <string>
+#include <vector>
 
-#include "cmListFileCache.h"
+class cmGeneratorTarget;
+class cmLocalGenerator;
+struct GeneratorExpressionContent;
+struct cmGeneratorExpressionContext;
+struct cmGeneratorExpressionDAGChecker;
 
 struct cmGeneratorExpressionNode
 {
diff --git a/Source/cmGeneratorExpressionParser.cxx b/Source/cmGeneratorExpressionParser.cxx
index f853f8d..3b56416 100644
--- a/Source/cmGeneratorExpressionParser.cxx
+++ b/Source/cmGeneratorExpressionParser.cxx
@@ -1,20 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionParser.h"
 
 #include "cmGeneratorExpressionEvaluator.h"
 
-#include "assert.h"
+#include <assert.h>
+#include <stddef.h>
 
 cmGeneratorExpressionParser::cmGeneratorExpressionParser(
   const std::vector<cmGeneratorExpressionToken>& tokens)
diff --git a/Source/cmGeneratorExpressionParser.h b/Source/cmGeneratorExpressionParser.h
index b0e9ea4..e30cb20 100644
--- a/Source/cmGeneratorExpressionParser.h
+++ b/Source/cmGeneratorExpressionParser.h
@@ -1,23 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorExpressionParser_h
 #define cmGeneratorExpressionParser_h
 
-#include "cmGeneratorExpressionLexer.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include <set>
 #include <vector>
 
-#include "cmListFileCache.h"
+#include "cmGeneratorExpressionLexer.h"
 
 struct cmGeneratorExpressionEvaluator;
 
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index 3856091..e8d66a2 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -1,33 +1,41 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorTarget.h"
 
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
+#include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
+#include "cmCustomCommandLines.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorExpressionDAGChecker.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmPropertyMap.h"
 #include "cmSourceFile.h"
+#include "cmSourceFileLocation.h"
+#include "cmSystemTools.h"
 #include "cmTarget.h"
+#include "cmTargetLinkLibraryType.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
-#include <queue>
-
-#include "assert.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
 #include <errno.h>
-
-#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <iterator>
+#include <queue>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if defined(CMake_HAVE_CXX_UNORDERED_SET)
+#include <unordered_set>
+#define UNORDERED_SET std::unordered_set
+#elif defined(CMAKE_BUILD_WITH_CMAKE)
 #include <cmsys/hash_set.hxx>
 #define UNORDERED_SET cmsys::hash_set
 #else
@@ -39,13 +47,13 @@ class cmGeneratorTarget::TargetPropertyEntry
   static cmLinkImplItem NoLinkImplItem;
 
 public:
-  TargetPropertyEntry(cmsys::auto_ptr<cmCompiledGeneratorExpression> cge,
+  TargetPropertyEntry(CM_AUTO_PTR<cmCompiledGeneratorExpression> cge,
                       cmLinkImplItem const& item = NoLinkImplItem)
     : ge(cge)
     , LinkImplItem(item)
   {
   }
-  const cmsys::auto_ptr<cmCompiledGeneratorExpression> ge;
+  const CM_AUTO_PTR<cmCompiledGeneratorExpression> ge;
   cmLinkImplItem const& LinkImplItem;
 };
 cmLinkImplItem cmGeneratorTarget::TargetPropertyEntry::NoLinkImplItem;
@@ -125,7 +133,7 @@ template <bool>
 struct DoAccept
 {
   template <typename T>
-  static void Do(T&, cmSourceFile*)
+  static void Do(T& /*unused*/, cmSourceFile* /*unused*/)
   {
   }
 };
@@ -250,7 +258,7 @@ void CreatePropertyGeneratorExpressions(
   for (std::vector<std::string>::const_iterator it = entries.begin();
        it != entries.end(); ++it, ++btIt) {
     cmGeneratorExpression ge(*btIt);
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*it);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*it);
     cge->SetEvaluateForBuildsystem(evaluateForBuildsystem);
     items.push_back(new cmGeneratorTarget::TargetPropertyEntry(cge));
   }
@@ -258,6 +266,7 @@ void CreatePropertyGeneratorExpressions(
 
 cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
   : Target(t)
+  , FortranModuleDirectoryCreated(false)
   , SourceFileFlagsConstructed(false)
   , PolicyWarnedCMP0022(false)
   , DebugIncludesDone(false)
@@ -309,7 +318,6 @@ cmGeneratorTarget::~cmGeneratorTarget()
   cmDeleteAll(this->CompileDefinitionsEntries);
   cmDeleteAll(this->SourceEntries);
   cmDeleteAll(this->LinkInformation);
-  this->LinkInformation.clear();
 }
 
 cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
@@ -357,10 +365,9 @@ const char* cmGeneratorTarget::GetOutputTargetType(bool implib) const
         if (implib) {
           // A DLL import library is treated as an archive target.
           return "ARCHIVE";
-        } else {
-          // A DLL shared library is treated as a runtime target.
-          return "RUNTIME";
         }
+        // A DLL shared library is treated as a runtime target.
+        return "RUNTIME";
       } else {
         // For non-DLL platforms shared libraries are treated as
         // library targets.
@@ -439,7 +446,7 @@ std::string cmGeneratorTarget::GetOutputName(const std::string& config,
 
     // Now evaluate genex and update the previously-prepared map entry.
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outName);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outName);
     i->second = cge->Evaluate(this->LocalGenerator, config);
   } else if (i->second.empty()) {
     // An empty map entry indicates we have been called recursively
@@ -452,31 +459,28 @@ std::string cmGeneratorTarget::GetOutputName(const std::string& config,
   return i->second;
 }
 
-void cmGeneratorTarget::AddSource(const std::string& src)
+void cmGeneratorTarget::AddSourceCommon(const std::string& src)
 {
-  this->Target->AddSource(src);
   cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
   cmGeneratorExpression ge(lfbt);
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(src);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src);
   cge->SetEvaluateForBuildsystem(true);
   this->SourceEntries.push_back(new TargetPropertyEntry(cge));
   this->SourceFilesMap.clear();
   this->LinkImplementationLanguageIsContextDependent = true;
 }
 
+void cmGeneratorTarget::AddSource(const std::string& src)
+{
+  this->Target->AddSource(src);
+  this->AddSourceCommon(src);
+}
+
 void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
 {
   this->Target->AddTracedSources(srcs);
   if (!srcs.empty()) {
-    std::string srcFiles = cmJoin(srcs, ";");
-    this->SourceFilesMap.clear();
-    this->LinkImplementationLanguageIsContextDependent = true;
-    cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
-    cmGeneratorExpression ge(lfbt);
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(srcFiles);
-    cge->SetEvaluateForBuildsystem(true);
-    this->SourceEntries.push_back(
-      new cmGeneratorTarget::TargetPropertyEntry(cge));
+    this->AddSourceCommon(cmJoin(srcs, ";"));
   }
 }
 
@@ -487,7 +491,7 @@ std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
   if (i != this->SourceDepends.end()) {
     return &i->second.Depends;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 static void handleSystemIncludesDep(
@@ -798,7 +802,7 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory(
 
   if (iter == this->SystemIncludesCache.end()) {
     cmGeneratorExpressionDAGChecker dagChecker(
-      this->GetName(), "SYSTEM_INCLUDE_DIRECTORIES", 0, 0);
+      this->GetName(), "SYSTEM_INCLUDE_DIRECTORIES", CM_NULLPTR, CM_NULLPTR);
 
     bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
 
@@ -823,14 +827,10 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory(
                               &dagChecker, result, excludeImported);
     }
 
-    std::set<std::string> unique;
-    for (std::vector<std::string>::iterator li = result.begin();
-         li != result.end(); ++li) {
-      cmSystemTools::ConvertToUnixSlashes(*li);
-      unique.insert(*li);
-    }
-    result.clear();
-    result.insert(result.end(), unique.begin(), unique.end());
+    std::for_each(result.begin(), result.end(),
+                  cmSystemTools::ConvertToUnixSlashes);
+    std::sort(result.begin(), result.end());
+    result.erase(std::unique(result.begin(), result.end()), result.end());
 
     IncludeCacheType::value_type entry(config_upper, result);
     iter = this->SystemIncludesCache.insert(entry).first;
@@ -858,7 +858,7 @@ static void AddInterfaceEntries(
       if (it->Target) {
         std::string genex = "$<TARGET_PROPERTY:" + *it + "," + prop + ">";
         cmGeneratorExpression ge(it->Backtrace);
-        cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
+        CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
         cge->SetEvaluateForBuildsystem(true);
         entries.push_back(
           new cmGeneratorTarget::TargetPropertyEntry(cge, *it));
@@ -994,7 +994,8 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files,
     this->DebugSourcesDone = true;
   }
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), "SOURCES", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), "SOURCES",
+                                             CM_NULLPTR, CM_NULLPTR);
 
   UNORDERED_SET<std::string> uniqueSrcs;
   bool contextDependentDirectSources =
@@ -1152,7 +1153,28 @@ bool cmGeneratorTarget::NeedRelinkBeforeInstall(
   // If either a build or install tree rpath is set then the rpath
   // will likely change between the build tree and install tree and
   // this target must be relinked.
-  return this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH();
+  bool have_rpath =
+    this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH();
+  bool is_ninja =
+    this->LocalGenerator->GetGlobalGenerator()->GetName() == "Ninja";
+
+  if (have_rpath && is_ninja) {
+    std::ostringstream w;
+    /* clang-format off */
+    w <<
+      "The install of the " << this->GetName() << " target requires "
+      "changing an RPATH from the build tree, but this is not supported "
+      "with the Ninja generator unless on an ELF-based platform.  The "
+      "CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
+      "relinking step."
+      ;
+    /* clang-format on */
+
+    cmake* cm = this->LocalGenerator->GetCMakeInstance();
+    cm->IssueMessage(cmake::FATAL_ERROR, w.str(), this->GetBacktrace());
+  }
+
+  return have_rpath;
 }
 
 bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const
@@ -1270,11 +1292,11 @@ bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
 
   if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
     std::ostringstream w;
-    w << "Attempting to use";
+    w << "Attempting to use ";
     if (macosx_rpath) {
-      w << " MACOSX_RPATH";
+      w << "MACOSX_RPATH";
     } else {
-      w << " @rpath";
+      w << "@rpath";
     }
     w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
     w << "  This could be because you are using a Mac OS X version";
@@ -1306,11 +1328,7 @@ bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
       this->GetName());
   }
 
-  if (cmp0042 == cmPolicies::NEW) {
-    return true;
-  }
-
-  return false;
+  return cmp0042 == cmPolicies::NEW;
 }
 
 std::string cmGeneratorTarget::GetSOName(const std::string& config) const
@@ -1323,37 +1341,40 @@ std::string cmGeneratorTarget::GetSOName(const std::string& config) const
         // The imported library has no builtin soname so the name
         // searched at runtime will be just the filename.
         return cmSystemTools::GetFilenameName(info->Location);
-      } else {
-        // Use the soname given if any.
-        if (info->SOName.find("@rpath/") == 0) {
-          return info->SOName.substr(6);
-        }
-        return info->SOName;
       }
-    } else {
-      return "";
+      // Use the soname given if any.
+      if (info->SOName.find("@rpath/") == 0) {
+        return info->SOName.substr(6);
+      }
+      return info->SOName;
     }
-  } else {
-    // Compute the soname that will be built.
-    std::string name;
-    std::string soName;
-    std::string realName;
-    std::string impName;
-    std::string pdbName;
-    this->GetLibraryNames(name, soName, realName, impName, pdbName, config);
-    return soName;
+    return "";
   }
+  // Compute the soname that will be built.
+  std::string name;
+  std::string soName;
+  std::string realName;
+  std::string impName;
+  std::string pdbName;
+  this->GetLibraryNames(name, soName, realName, impName, pdbName, config);
+  return soName;
 }
 
 std::string cmGeneratorTarget::GetAppBundleDirectory(const std::string& config,
                                                      bool contentOnly) const
 {
   std::string fpath = this->GetFullName(config, false);
-  fpath += ".app";
+  fpath += ".";
+  const char* ext = this->GetProperty("BUNDLE_EXTENSION");
+  if (!ext) {
+    ext = "app";
+  }
+  fpath += ext;
   if (!this->Makefile->PlatformIsAppleIos()) {
     fpath += "/Contents";
-    if (!contentOnly)
+    if (!contentOnly) {
       fpath += "/MacOS";
+    }
   }
   return fpath;
 }
@@ -1381,8 +1402,9 @@ std::string cmGeneratorTarget::GetCFBundleDirectory(const std::string& config,
   fpath += ext;
   if (!this->Makefile->PlatformIsAppleIos()) {
     fpath += "/Contents";
-    if (!contentOnly)
+    if (!contentOnly) {
       fpath += "/MacOS";
+    }
   }
   return fpath;
 }
@@ -1392,7 +1414,12 @@ std::string cmGeneratorTarget::GetFrameworkDirectory(const std::string& config,
 {
   std::string fpath;
   fpath += this->GetOutputName(config, false);
-  fpath += ".framework";
+  fpath += ".";
+  const char* ext = this->GetProperty("BUNDLE_EXTENSION");
+  if (!ext) {
+    ext = "framework";
+  }
+  fpath += ext;
   if (!rootDir && !this->Makefile->PlatformIsAppleIos()) {
     fpath += "/Versions/";
     fpath += this->GetFrameworkVersion();
@@ -1405,9 +1432,8 @@ std::string cmGeneratorTarget::GetFullName(const std::string& config,
 {
   if (this->IsImported()) {
     return this->GetFullNameImported(config, implib);
-  } else {
-    return this->GetFullNameInternal(config, implib);
   }
+  return this->GetFullNameInternal(config, implib);
 }
 
 std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
@@ -1431,9 +1457,8 @@ std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
     }
     dir += "/";
     return dir;
-  } else {
-    return "";
   }
+  return "";
 }
 
 std::string cmGeneratorTarget::GetInstallNameDirForInstallTree() const
@@ -1455,9 +1480,8 @@ std::string cmGeneratorTarget::GetInstallNameDirForInstallTree() const
       }
     }
     return dir;
-  } else {
-    return "";
   }
+  return "";
 }
 
 cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
@@ -1503,9 +1527,8 @@ const char* cmGeneratorTarget::GetExportMacro() const
       this->ExportMacro = cmSystemTools::MakeCidentifier(in);
     }
     return this->ExportMacro.c_str();
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 class cmTargetCollectLinkLanguages
@@ -1529,7 +1552,7 @@ public:
       if (item.find("::") != std::string::npos) {
         bool noMessage = false;
         cmake::MessageType messageType = cmake::FATAL_ERROR;
-        std::stringstream e;
+        std::ostringstream e;
         switch (this->Target->GetLocalGenerator()->GetPolicyStatus(
           cmPolicies::CMP0028)) {
           case cmPolicies::WARN: {
@@ -1629,8 +1652,9 @@ public:
   {
     if (this->Preferred.empty()) {
       return "";
-    } else if (this->Preferred.size() > 1) {
-      std::stringstream e;
+    }
+    if (this->Preferred.size() > 1) {
+      std::ostringstream e;
       e << "Target " << this->Target->GetName()
         << " contains multiple languages with the highest linker preference"
         << " (" << this->Preference << "):\n";
@@ -1748,7 +1772,7 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
 {
   // There is no compile information for imported targets.
   if (this->IsImported()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   if (this->GetType() > cmState::OBJECT_LIBRARY) {
@@ -1757,7 +1781,7 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
     msg += " which has type ";
     msg += cmState::GetTargetTypeName(this->GetType());
     this->LocalGenerator->IssueMessage(cmake::INTERNAL_ERROR, msg);
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Lookup/compute/cache the compile information for this configuration.
@@ -1786,7 +1810,7 @@ cmSourceFile const* cmGeneratorTarget::GetModuleDefinitionFile(
     return data.front();
   }
 
-  return 0;
+  return CM_NULLPTR;
 }
 
 bool cmGeneratorTarget::IsDLLPlatform() const
@@ -1839,8 +1863,8 @@ void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
   }
   cmGeneratorExpression ge;
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             "AUTOUIC_OPTIONS", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(
+    this->GetName(), "AUTOUIC_OPTIONS", CM_NULLPTR, CM_NULLPTR);
   cmSystemTools::ExpandListArgument(
     ge.Parse(prop)->Evaluate(this->LocalGenerator, config, false, this,
                              &dagChecker),
@@ -1925,7 +1949,7 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target)
   this->Makefile = target->Target->GetMakefile();
   this->LocalGenerator = target->GetLocalGenerator();
   this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
-  this->CurrentEntry = 0;
+  this->CurrentEntry = CM_NULLPTR;
 
   // Queue all the source files already specified for the target.
   if (target->GetType() != cmState::INTERFACE_LIBRARY) {
@@ -2000,7 +2024,7 @@ void cmTargetTraceDependencies::Trace()
       this->CheckCustomCommand(*cc);
     }
   }
-  this->CurrentEntry = 0;
+  this->CurrentEntry = CM_NULLPTR;
 
   this->GeneratorTarget->AddTracedSources(this->NewSources);
 }
@@ -2116,8 +2140,7 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
     // Check for target references in generator expressions.
     for (cmCustomCommandLine::const_iterator cli = cit->begin();
          cli != cit->end(); ++cli) {
-      const cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-        ge.Parse(*cli);
+      const CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*cli);
       cge->Evaluate(this->GeneratorTarget->GetLocalGenerator(), "", true);
       std::set<cmGeneratorTarget*> geTargets = cge->GetTargets();
       targets.insert(geTargets.begin(), geTargets.end());
@@ -2200,7 +2223,7 @@ std::string cmGeneratorTarget::GetCompilePDBDirectory(
 void cmGeneratorTarget::GetAppleArchs(const std::string& config,
                                       std::vector<std::string>& archVec) const
 {
-  const char* archs = 0;
+  const char* archs = CM_NULLPTR;
   if (!config.empty()) {
     std::string defVarName = "OSX_ARCHITECTURES_";
     defVarName += cmSystemTools::UpperCase(config);
@@ -2358,8 +2381,8 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
   std::vector<std::string> includes;
   UNORDERED_SET<std::string> uniqueIncludes;
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             "INCLUDE_DIRECTORIES", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(
+    this->GetName(), "INCLUDE_DIRECTORIES", CM_NULLPTR, CM_NULLPTR);
 
   std::vector<std::string> debugProperties;
   const char* debugProp =
@@ -2402,7 +2425,7 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
       libDir = frameworkCheck.match(1);
 
       cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+      CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
         ge.Parse(libDir.c_str());
       linkInterfaceIncludeDirectoriesEntries.push_back(
         new cmGeneratorTarget::TargetPropertyEntry(cge));
@@ -2485,8 +2508,8 @@ void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result,
 {
   UNORDERED_SET<std::string> uniqueOptions;
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             "COMPILE_OPTIONS", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(
+    this->GetName(), "COMPILE_OPTIONS", CM_NULLPTR, CM_NULLPTR);
 
   std::vector<std::string> debugProperties;
   const char* debugProp =
@@ -2537,8 +2560,8 @@ void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result,
 {
   UNORDERED_SET<std::string> uniqueFeatures;
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             "COMPILE_FEATURES", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(
+    this->GetName(), "COMPILE_FEATURES", CM_NULLPTR, CM_NULLPTR);
 
   std::vector<std::string> debugProperties;
   const char* debugProp =
@@ -2587,8 +2610,8 @@ void cmGeneratorTarget::GetCompileDefinitions(
 {
   UNORDERED_SET<std::string> uniqueOptions;
 
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             "COMPILE_DEFINITIONS", 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(
+    this->GetName(), "COMPILE_DEFINITIONS", CM_NULLPTR, CM_NULLPTR);
 
   std::vector<std::string> debugProperties;
   const char* debugProp =
@@ -2626,7 +2649,7 @@ void cmGeneratorTarget::GetCompileDefinitions(
         }
         case cmPolicies::OLD: {
           cmGeneratorExpression ge;
-          cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+          CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
             ge.Parse(configProp);
           linkInterfaceCompileDefinitionsEntries.push_back(
             new cmGeneratorTarget::TargetPropertyEntry(cge));
@@ -2711,9 +2734,8 @@ std::string cmGeneratorTarget::GetFullPath(const std::string& config,
 {
   if (this->IsImported()) {
     return this->Target->ImportedGetFullPath(config, implib);
-  } else {
-    return this->NormalGetFullPath(config, implib, realname);
   }
+  return this->NormalGetFullPath(config, implib, realname);
 }
 
 std::string cmGeneratorTarget::NormalGetFullPath(const std::string& config,
@@ -2758,16 +2780,15 @@ std::string cmGeneratorTarget::NormalGetRealName(
     std::string pdbName;
     this->GetExecutableNames(name, realName, impName, pdbName, config);
     return realName;
-  } else {
-    // Compute the real name that will be built.
-    std::string name;
-    std::string soName;
-    std::string realName;
-    std::string impName;
-    std::string pdbName;
-    this->GetLibraryNames(name, soName, realName, impName, pdbName, config);
-    return realName;
   }
+  // Compute the real name that will be built.
+  std::string name;
+  std::string soName;
+  std::string realName;
+  std::string impName;
+  std::string pdbName;
+  this->GetLibraryNames(name, soName, realName, impName, pdbName, config);
+  return realName;
 }
 
 void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName,
@@ -2794,8 +2815,8 @@ void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName,
       this->IsFrameworkOnApple()) {
     // Versioning is supported only for shared libraries and modules,
     // and then only when the platform supports an soname flag.
-    version = 0;
-    soversion = 0;
+    version = CM_NULLPTR;
+    soversion = CM_NULLPTR;
   }
   if (version && !soversion) {
     // The soversion must be set if the library version is set.  Use
@@ -2869,7 +2890,7 @@ void cmGeneratorTarget::GetExecutableNames(std::string& name,
   const char* version = this->GetProperty("VERSION");
   if (this->GetType() != cmState::EXECUTABLE ||
       this->Makefile->IsOn("XCODE")) {
-    version = 0;
+    version = CM_NULLPTR;
   }
 #endif
 
@@ -2969,7 +2990,7 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
                                      : this->GetProperty("PREFIX"));
   const char* targetSuffix = (implib ? this->GetProperty("IMPORT_SUFFIX")
                                      : this->GetProperty("SUFFIX"));
-  const char* configPostfix = 0;
+  const char* configPostfix = CM_NULLPTR;
   if (!config.empty()) {
     std::string configProp = cmSystemTools::UpperCase(config);
     configProp += "_POSTFIX";
@@ -2977,7 +2998,7 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
     // Mac application bundles and frameworks have no postfix.
     if (configPostfix &&
         (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
-      configPostfix = 0;
+      configPostfix = CM_NULLPTR;
     }
   }
   const char* prefixVar = this->Target->GetPrefixVariableInternal(implib);
@@ -3009,16 +3030,22 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
   std::string fw_prefix;
   if (this->IsFrameworkOnApple()) {
     fw_prefix = this->GetOutputName(config, false);
-    fw_prefix += ".framework/";
+    fw_prefix += ".";
+    const char* ext = this->GetProperty("BUNDLE_EXTENSION");
+    if (!ext) {
+      ext = "framework";
+    }
+    fw_prefix += ext;
+    fw_prefix += "/";
     targetPrefix = fw_prefix.c_str();
-    targetSuffix = 0;
+    targetSuffix = CM_NULLPTR;
   }
 
   if (this->IsCFBundleOnApple()) {
     fw_prefix = this->GetCFBundleDirectory(config, false);
     fw_prefix += "/";
     targetPrefix = fw_prefix.c_str();
-    targetSuffix = 0;
+    targetSuffix = CM_NULLPTR;
   }
 
   // Begin the final name with the prefix.
@@ -3253,7 +3280,8 @@ template <>
 bool getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
                                        const std::string& prop,
                                        const std::string& config,
-                                       CompatibleType, bool*)
+                                       CompatibleType /*unused*/,
+                                       bool* /*unused*/)
 {
   return tgt->GetLinkInterfaceDependentBoolProperty(prop, config);
 }
@@ -3262,12 +3290,13 @@ template <>
 const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
                                               const std::string& prop,
                                               const std::string& config,
-                                              CompatibleType t, const char**)
+                                              CompatibleType t,
+                                              const char** /*unused*/)
 {
   switch (t) {
     case BoolType:
       assert(0 && "String compatibility check function called for boolean");
-      return 0;
+      return CM_NULLPTR;
     case StringType:
       return tgt->GetLinkInterfaceDependentStringProperty(prop, config);
     case NumberMinType:
@@ -3276,7 +3305,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
       return tgt->GetLinkInterfaceDependentNumberMaxProperty(prop, config);
   }
   assert(0 && "Unreachable!");
-  return 0;
+  return CM_NULLPTR;
 }
 
 template <typename PropertyType>
@@ -3285,7 +3314,7 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender,
                               const std::string& propName,
                               std::set<std::string>& emitted,
                               const std::string& config, CompatibleType t,
-                              PropertyType*)
+                              PropertyType* /*unused*/)
 {
   const char* prop = dependee->GetProperty(propName);
   if (!prop) {
@@ -3314,7 +3343,7 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender,
     }
     if (emitted.insert(*pi).second) {
       getLinkInterfaceDependentProperty<PropertyType>(depender, *pi, config, t,
-                                                      0);
+                                                      CM_NULLPTR);
       if (cmSystemTools::GetErrorOccuredFlag()) {
         return;
       }
@@ -3340,11 +3369,13 @@ static std::string intersect(const std::set<std::string>& s1,
 {
   std::string result;
   result = intersect(s1, s2);
-  if (!result.empty())
+  if (!result.empty()) {
     return result;
+  }
   result = intersect(s1, s3);
-  if (!result.empty())
+  if (!result.empty()) {
     return result;
+  }
   return intersect(s2, s3);
 }
 
@@ -3355,14 +3386,17 @@ static std::string intersect(const std::set<std::string>& s1,
 {
   std::string result;
   result = intersect(s1, s2);
-  if (!result.empty())
+  if (!result.empty()) {
     return result;
+  }
   result = intersect(s1, s3);
-  if (!result.empty())
+  if (!result.empty()) {
     return result;
+  }
   result = intersect(s1, s4);
-  if (!result.empty())
+  if (!result.empty()) {
     return result;
+  }
   return intersect(s2, s3, s4);
 }
 
@@ -3387,24 +3421,25 @@ void cmGeneratorTarget::CheckPropertyCompatibility(
     }
 
     checkPropertyConsistency<bool>(this, li->Target, strBool, emittedBools,
-                                   config, BoolType, 0);
+                                   config, BoolType, CM_NULLPTR);
     if (cmSystemTools::GetErrorOccuredFlag()) {
       return;
     }
-    checkPropertyConsistency<const char*>(
-      this, li->Target, strString, emittedStrings, config, StringType, 0);
+    checkPropertyConsistency<const char*>(this, li->Target, strString,
+                                          emittedStrings, config, StringType,
+                                          CM_NULLPTR);
     if (cmSystemTools::GetErrorOccuredFlag()) {
       return;
     }
     checkPropertyConsistency<const char*>(this, li->Target, strNumMin,
                                           emittedMinNumbers, config,
-                                          NumberMinType, 0);
+                                          NumberMinType, CM_NULLPTR);
     if (cmSystemTools::GetErrorOccuredFlag()) {
       return;
     }
     checkPropertyConsistency<const char*>(this, li->Target, strNumMax,
                                           emittedMaxNumbers, config,
-                                          NumberMaxType, 0);
+                                          NumberMaxType, CM_NULLPTR);
     if (cmSystemTools::GetErrorOccuredFlag()) {
       return;
     }
@@ -3512,12 +3547,12 @@ std::string valueAsString<const char*>(const char* value)
 template <typename PropertyType>
 PropertyType impliedValue(PropertyType);
 template <>
-bool impliedValue<bool>(bool)
+bool impliedValue<bool>(bool /*unused*/)
 {
   return false;
 }
 template <>
-const char* impliedValue<const char*>(const char*)
+const char* impliedValue<const char*>(const char* /*unused*/)
 {
   return "";
 }
@@ -3528,7 +3563,8 @@ std::pair<bool, PropertyType> consistentProperty(PropertyType lhs,
                                                  CompatibleType t);
 
 template <>
-std::pair<bool, bool> consistentProperty(bool lhs, bool rhs, CompatibleType)
+std::pair<bool, bool> consistentProperty(bool lhs, bool rhs,
+                                         CompatibleType /*unused*/)
 {
   return std::make_pair(lhs == rhs, lhs);
 }
@@ -3537,7 +3573,7 @@ std::pair<bool, const char*> consistentStringProperty(const char* lhs,
                                                       const char* rhs)
 {
   const bool b = strcmp(lhs, rhs) == 0;
-  return std::make_pair(b, b ? lhs : 0);
+  return std::make_pair(b, b ? lhs : CM_NULLPTR);
 }
 
 std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
@@ -3546,7 +3582,7 @@ std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
 {
   char* pEnd;
 
-  const char* const null_ptr = 0;
+  const char* const null_ptr = CM_NULLPTR;
 
   long lnum = strtol(lhs, &pEnd, 0);
   if (pEnd == lhs || *pEnd != '\0' || errno == ERANGE) {
@@ -3560,9 +3596,8 @@ std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
 
   if (t == NumberMaxType) {
     return std::make_pair(true, std::max(lnum, rnum) == lnum ? lhs : rhs);
-  } else {
-    return std::make_pair(true, std::min(lnum, rnum) == lnum ? lhs : rhs);
   }
+  return std::make_pair(true, std::min(lnum, rnum) == lnum ? lhs : rhs);
 }
 
 template <>
@@ -3580,7 +3615,7 @@ std::pair<bool, const char*> consistentProperty(const char* lhs,
     return std::make_pair(true, lhs);
   }
 
-  const char* const null_ptr = 0;
+  const char* const null_ptr = CM_NULLPTR;
 
   switch (t) {
     case BoolType:
@@ -3602,7 +3637,7 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt,
                                                  const std::string& config,
                                                  const char* defaultValue,
                                                  CompatibleType t,
-                                                 PropertyType*)
+                                                 PropertyType* /*unused*/)
 {
   PropertyType propContent = getTypedProperty<PropertyType>(tgt, p);
   std::vector<std::string> headPropKeys = tgt->GetPropertyKeys();
@@ -3751,28 +3786,28 @@ bool cmGeneratorTarget::GetLinkInterfaceDependentBoolProperty(
   const std::string& p, const std::string& config) const
 {
   return checkInterfacePropertyCompatibility<bool>(this, p, config, "FALSE",
-                                                   BoolType, 0);
+                                                   BoolType, CM_NULLPTR);
 }
 
 const char* cmGeneratorTarget::GetLinkInterfaceDependentStringProperty(
   const std::string& p, const std::string& config) const
 {
   return checkInterfacePropertyCompatibility<const char*>(
-    this, p, config, "empty", StringType, 0);
+    this, p, config, "empty", StringType, CM_NULLPTR);
 }
 
 const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMinProperty(
   const std::string& p, const std::string& config) const
 {
   return checkInterfacePropertyCompatibility<const char*>(
-    this, p, config, "empty", NumberMinType, 0);
+    this, p, config, "empty", NumberMinType, CM_NULLPTR);
 }
 
 const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMaxProperty(
   const std::string& p, const std::string& config) const
 {
   return checkInterfacePropertyCompatibility<const char*>(
-    this, p, config, "empty", NumberMaxType, 0);
+    this, p, config, "empty", NumberMaxType, CM_NULLPTR);
 }
 
 cmComputeLinkInformation* cmGeneratorTarget::GetLinkInformation(
@@ -3787,7 +3822,7 @@ cmComputeLinkInformation* cmGeneratorTarget::GetLinkInformation(
       new cmComputeLinkInformation(this, config);
     if (!info || !info->Compute()) {
       delete info;
-      info = 0;
+      info = CM_NULLPTR;
     }
 
     // Store the information for this configuration.
@@ -3839,17 +3874,63 @@ void cmGeneratorTarget::GetTargetVersion(bool soversion, int& major,
   }
 }
 
+std::string cmGeneratorTarget::GetFortranModuleDirectory(
+  std::string const& working_dir) const
+{
+  if (!this->FortranModuleDirectoryCreated) {
+    this->FortranModuleDirectory = true;
+    this->FortranModuleDirectory =
+      this->CreateFortranModuleDirectory(working_dir);
+  }
+
+  return this->FortranModuleDirectory;
+}
+
+std::string cmGeneratorTarget::CreateFortranModuleDirectory(
+  std::string const& working_dir) const
+{
+  std::string mod_dir;
+  std::string target_mod_dir;
+  if (const char* prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
+    target_mod_dir = prop;
+  } else {
+    std::string const& default_mod_dir =
+      this->LocalGenerator->GetCurrentBinaryDirectory();
+    if (default_mod_dir != working_dir) {
+      target_mod_dir = default_mod_dir;
+    }
+  }
+  const char* moddir_flag =
+    this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
+  if (!target_mod_dir.empty() && moddir_flag) {
+    // Compute the full path to the module directory.
+    if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
+      // Already a full path.
+      mod_dir = target_mod_dir;
+    } else {
+      // Interpret relative to the current output directory.
+      mod_dir = this->LocalGenerator->GetCurrentBinaryDirectory();
+      mod_dir += "/";
+      mod_dir += target_mod_dir;
+    }
+
+    // Make sure the module output directory exists.
+    cmSystemTools::MakeDirectory(mod_dir);
+  }
+  return mod_dir;
+}
+
 std::string cmGeneratorTarget::GetFrameworkVersion() const
 {
   assert(this->GetType() != cmState::INTERFACE_LIBRARY);
 
   if (const char* fversion = this->GetProperty("FRAMEWORK_VERSION")) {
     return fversion;
-  } else if (const char* tversion = this->GetProperty("VERSION")) {
+  }
+  if (const char* tversion = this->GetProperty("VERSION")) {
     return tversion;
-  } else {
-    return "A";
   }
+  return "A";
 }
 
 void cmGeneratorTarget::ComputeVersionedName(std::string& vName,
@@ -3930,14 +4011,15 @@ void cmGeneratorTarget::ExpandLinkItems(
   std::vector<cmLinkItem>& items, bool& hadHeadSensitiveCondition) const
 {
   cmGeneratorExpression ge;
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), prop, 0, 0);
+  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), prop, CM_NULLPTR,
+                                             CM_NULLPTR);
   // The $<LINK_ONLY> expression may be in a link interface to specify private
   // link dependencies that are otherwise excluded from usage requirements.
   if (usage_requirements_only) {
     dagChecker.SetTransitivePropertiesOnly();
   }
   std::vector<std::string> libs;
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(value);
   cmSystemTools::ExpandListArgument(cge->Evaluate(this->LocalGenerator, config,
                                                   false, headTarget, this,
                                                   &dagChecker),
@@ -3958,7 +4040,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
   // export symbols.
   if (this->GetType() == cmState::EXECUTABLE &&
       !this->IsExecutableWithExports()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Lookup any existing link interface for this configuration.
@@ -3982,7 +4064,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
     }
   }
 
-  return iface.Exists ? &iface : 0;
+  return iface.Exists ? &iface : CM_NULLPTR;
 }
 
 void cmGeneratorTarget::ComputeLinkInterface(
@@ -4074,7 +4156,7 @@ const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
   // export symbols.
   if (this->GetType() == cmState::EXECUTABLE &&
       !this->IsExecutableWithExports()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Lookup any existing link interface for this configuration.
@@ -4097,7 +4179,7 @@ const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
                                         usage_requirements_only);
   }
 
-  return iface.Exists ? &iface : 0;
+  return iface.Exists ? &iface : CM_NULLPTR;
 }
 
 std::string cmGeneratorTarget::GetDirectory(const std::string& config,
@@ -4107,7 +4189,8 @@ std::string cmGeneratorTarget::GetDirectory(const std::string& config,
     // Return the directory from which the target is imported.
     return cmSystemTools::GetFilenamePath(
       this->Target->ImportedGetFullPath(config, implib));
-  } else if (OutputInfo const* info = this->GetOutputInfo(config)) {
+  }
+  if (OutputInfo const* info = this->GetOutputInfo(config)) {
     // Return the directory in which the target will be built.
     return implib ? info->ImpDir : info->OutDir;
   }
@@ -4126,7 +4209,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
 {
   // There is no output information for imported targets.
   if (this->IsImported()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Only libraries and executables have well-defined output files.
@@ -4136,7 +4219,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
     msg += " which has type ";
     msg += cmState::GetTargetTypeName(this->GetType());
     this->LocalGenerator->IssueMessage(cmake::INTERNAL_ERROR, msg);
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Lookup/compute/cache the output information for this configuration.
@@ -4167,7 +4250,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
       cmake::FATAL_ERROR,
       "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
       this->GetBacktrace());
-    return 0;
+    return CM_NULLPTR;
   }
   return &i->second;
 }
@@ -4181,7 +4264,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
   // Look for a target property defining the target output directory
   // based on the target type.
   std::string targetTypeName = this->GetOutputTargetType(implib);
-  const char* propertyName = 0;
+  const char* propertyName = CM_NULLPTR;
   std::string propertyNameStr = targetTypeName;
   if (!propertyNameStr.empty()) {
     propertyNameStr += "_OUTPUT_DIRECTORY";
@@ -4190,7 +4273,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
 
   // Check for a per-configuration output directory target property.
   std::string configUpper = cmSystemTools::UpperCase(conf);
-  const char* configProp = 0;
+  const char* configProp = CM_NULLPTR;
   std::string configPropStr = targetTypeName;
   if (!configPropStr.empty()) {
     configPropStr += "_OUTPUT_DIRECTORY_";
@@ -4202,8 +4285,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
   if (const char* config_outdir = this->GetProperty(configProp)) {
     // Use the user-specified per-configuration output directory.
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-      ge.Parse(config_outdir);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(config_outdir);
     out = cge->Evaluate(this->LocalGenerator, config);
 
     // Skip per-configuration subdirectory.
@@ -4211,7 +4293,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
   } else if (const char* outdir = this->GetProperty(propertyName)) {
     // Use the user-specified output directory.
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outdir);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outdir);
     out = cge->Evaluate(this->LocalGenerator, config);
 
     // Skip per-configuration subdirectory if the value contained a
@@ -4258,7 +4340,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
 {
   // Look for a target property defining the target output directory
   // based on the target type.
-  const char* propertyName = 0;
+  const char* propertyName = CM_NULLPTR;
   std::string propertyNameStr = kind;
   if (!propertyNameStr.empty()) {
     propertyNameStr += "_OUTPUT_DIRECTORY";
@@ -4268,7 +4350,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
 
   // Check for a per-configuration output directory target property.
   std::string configUpper = cmSystemTools::UpperCase(conf);
-  const char* configProp = 0;
+  const char* configProp = CM_NULLPTR;
   std::string configPropStr = kind;
   if (!configPropStr.empty()) {
     configPropStr += "_OUTPUT_DIRECTORY_";
@@ -4326,7 +4408,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
 
   // An explicit list of interface libraries may be set for shared
   // libraries and executables that export symbols.
-  const char* explicitLibraries = 0;
+  const char* explicitLibraries = CM_NULLPTR;
   std::string linkIfaceProp;
   if (this->GetPolicyStatusCMP0022() != cmPolicies::OLD &&
       this->GetPolicyStatusCMP0022() != cmPolicies::WARN) {
@@ -4452,7 +4534,7 @@ const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface(
 {
   cmGeneratorTarget::ImportInfo const* info = this->GetImportInfo(config);
   if (!info) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   std::string CONFIG = cmSystemTools::UpperCase(config);
@@ -4488,7 +4570,7 @@ cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
 {
   // There is no imported information for non-imported targets.
   if (!this->IsImported()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Lookup/compute/cache the import information for this
@@ -4514,7 +4596,7 @@ cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
   // If the location is empty then the target is not available for
   // this configuration.
   if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Return the import information.
@@ -4531,8 +4613,8 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
   // Initialize members.
   info.NoSOName = false;
 
-  const char* loc = 0;
-  const char* imp = 0;
+  const char* loc = CM_NULLPTR;
+  const char* imp = CM_NULLPTR;
   std::string suffix;
   if (!this->Target->GetMappedConfig(desired_config, &loc, &imp, suffix)) {
     return;
@@ -4674,7 +4756,7 @@ const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation(
 {
   // There is no link implementation for imported targets.
   if (this->IsImported()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   std::string CONFIG = cmSystemTools::UpperCase(config);
@@ -4903,7 +4985,7 @@ cmGeneratorTarget::GetLinkImplementationLibrariesInternal(
 {
   // There is no link implementation for imported targets.
   if (this->IsImported()) {
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Populate the link implementation libraries for this configuration.
@@ -4943,10 +5025,10 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
                                      end = entryRange.end();
        le != end; ++le, ++btIt) {
     std::vector<std::string> llibs;
-    cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                               "LINK_LIBRARIES", 0, 0);
+    cmGeneratorExpressionDAGChecker dagChecker(
+      this->GetName(), "LINK_LIBRARIES", CM_NULLPTR, CM_NULLPTR);
     cmGeneratorExpression ge(*btIt);
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> const cge = ge.Parse(*le);
     std::string const evaluated =
       cge->Evaluate(this->LocalGenerator, config, false, head, &dagChecker);
     cmSystemTools::ExpandListArgument(evaluated, llibs);
@@ -5037,7 +5119,7 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink(
   // within the project.
   if (tgt && tgt->GetType() == cmState::EXECUTABLE &&
       !tgt->IsExecutableWithExports()) {
-    tgt = 0;
+    tgt = CM_NULLPTR;
   }
 
   if (tgt && tgt->GetType() == cmState::OBJECT_LIBRARY) {
@@ -5051,7 +5133,7 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink(
          "with the ENABLE_EXPORTS property set.";
     cmake* cm = this->LocalGenerator->GetCMakeInstance();
     cm->IssueMessage(cmake::FATAL_ERROR, e.str(), this->GetBacktrace());
-    tgt = 0;
+    tgt = CM_NULLPTR;
   }
 
   return tgt;
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index 63208bc..68ffd5c 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -1,26 +1,28 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGeneratorTarget_h
 #define cmGeneratorTarget_h
 
+#include <cmConfigure.h>
+
 #include "cmLinkItem.h"
+#include "cmListFileCache.h"
+#include "cmPolicies.h"
+#include "cmState.h"
 
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+class cmComputeLinkInformation;
 class cmCustomCommand;
 class cmGlobalGenerator;
 class cmLocalGenerator;
 class cmMakefile;
 class cmSourceFile;
 class cmTarget;
-class cmComputeLinkInformation;
 
 class cmGeneratorTarget
 {
@@ -215,7 +217,7 @@ public:
                                        bool contentOnly = true) const;
 
   /** @return the mac content directory for this target. */
-  std::string GetMacContentDirectory(const std::string& config = 0,
+  std::string GetMacContentDirectory(const std::string& config = CM_NULLPTR,
                                      bool implib = false) const;
 
   cmTarget* Target;
@@ -402,7 +404,7 @@ public:
   {
     SourceFileFlags()
       : Type(SourceFileTypeNormal)
-      , MacFolder(0)
+      , MacFolder(CM_NULLPTR)
     {
     }
     SourceFileFlags(SourceFileFlags const& r)
@@ -453,7 +455,7 @@ public:
   /** Convert the given GNU import library name (.dll.a) to a name with a new
       extension (.lib or ${CMAKE_IMPORT_LIBRARY_SUFFIX}).  */
   bool GetImplibGNUtoMS(std::string const& gnuName, std::string& out,
-                        const char* newExt = 0) const;
+                        const char* newExt = CM_NULLPTR) const;
 
   bool IsExecutableWithExports() const;
 
@@ -526,7 +528,16 @@ public:
   void GetTargetVersion(bool soversion, int& major, int& minor,
                         int& patch) const;
 
+  std::string GetFortranModuleDirectory(std::string const& working_dir) const;
+
 private:
+  void AddSourceCommon(const std::string& src);
+
+  std::string CreateFortranModuleDirectory(
+    std::string const& working_dir) const;
+  mutable bool FortranModuleDirectoryCreated;
+  mutable std::string FortranModuleDirectory;
+
   friend class cmTargetTraceDependencies;
   struct SourceEntry
   {
diff --git a/Source/cmGetCMakePropertyCommand.cxx b/Source/cmGetCMakePropertyCommand.cxx
index 331aab9..11373b7 100644
--- a/Source/cmGetCMakePropertyCommand.cxx
+++ b/Source/cmGetCMakePropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetCMakePropertyCommand.h"
 
 #include "cmAlgorithms.h"
@@ -42,7 +33,7 @@ bool cmGetCMakePropertyCommand::InitialPass(
       this->Makefile->GetGlobalGenerator()->GetInstallComponents();
     output = cmJoin(*components, ";");
   } else {
-    const char* prop = 0;
+    const char* prop = CM_NULLPTR;
     if (!args[1].empty()) {
       prop = this->Makefile->GetState()->GetGlobalProperty(args[1]);
     }
diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h
index fd247e8..644db33 100644
--- a/Source/cmGetCMakePropertyCommand.h
+++ b/Source/cmGetCMakePropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetCMakePropertyCommand_h
 #define cmGetCMakePropertyCommand_h
 
@@ -17,24 +8,24 @@
 class cmGetCMakePropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmGetCMakePropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetCMakePropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_cmake_property"; }
+  std::string GetName() const CM_OVERRIDE { return "get_cmake_property"; }
 
   cmTypeMacro(cmGetCMakePropertyCommand, cmCommand);
 };
diff --git a/Source/cmGetDirectoryPropertyCommand.cxx b/Source/cmGetDirectoryPropertyCommand.cxx
index 1b5bcc9..8ebad4e 100644
--- a/Source/cmGetDirectoryPropertyCommand.cxx
+++ b/Source/cmGetDirectoryPropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetDirectoryPropertyCommand.h"
 
 #include "cmake.h"
@@ -73,7 +64,7 @@ bool cmGetDirectoryPropertyCommand::InitialPass(
     return true;
   }
 
-  const char* prop = 0;
+  const char* prop = CM_NULLPTR;
   if (!i->empty()) {
     if (*i == "DEFINITIONS") {
       switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0059)) {
diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h
index 97394ec..c6d9329 100644
--- a/Source/cmGetDirectoryPropertyCommand.h
+++ b/Source/cmGetDirectoryPropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetDirectoryPropertyCommand_h
 #define cmGetDirectoryPropertyCommand_h
 
@@ -17,24 +8,24 @@
 class cmGetDirectoryPropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmGetDirectoryPropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetDirectoryPropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_directory_property"; }
+  std::string GetName() const CM_OVERRIDE { return "get_directory_property"; }
 
   cmTypeMacro(cmGetDirectoryPropertyCommand, cmCommand);
 
diff --git a/Source/cmGetFilenameComponentCommand.cxx b/Source/cmGetFilenameComponentCommand.cxx
index 1830b0c..05dbfb4 100644
--- a/Source/cmGetFilenameComponentCommand.cxx
+++ b/Source/cmGetFilenameComponentCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetFilenameComponentCommand.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h
index a114b3d..32096d1 100644
--- a/Source/cmGetFilenameComponentCommand.h
+++ b/Source/cmGetFilenameComponentCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetFilenameComponentCommand_h
 #define cmGetFilenameComponentCommand_h
 
@@ -26,24 +17,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmGetFilenameComponentCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetFilenameComponentCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_filename_component"; }
+  std::string GetName() const CM_OVERRIDE { return "get_filename_component"; }
 
   cmTypeMacro(cmGetFilenameComponentCommand, cmCommand);
 };
diff --git a/Source/cmGetPropertyCommand.cxx b/Source/cmGetPropertyCommand.cxx
index 06f7504..ba03568 100644
--- a/Source/cmGetPropertyCommand.cxx
+++ b/Source/cmGetPropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetPropertyCommand.h"
 
 #include "cmGlobalGenerator.h"
@@ -248,24 +239,21 @@ bool cmGetPropertyCommand::HandleTargetMode()
     return false;
   }
 
-  if (this->PropertyName == "ALIASED_TARGET") {
-    if (this->Makefile->IsAlias(this->Name)) {
-      if (cmTarget* target = this->Makefile->FindTargetToUse(this->Name)) {
+  if (cmTarget* target = this->Makefile->FindTargetToUse(this->Name)) {
+    if (this->PropertyName == "ALIASED_TARGET") {
+      if (this->Makefile->IsAlias(this->Name)) {
         return this->StoreResult(target->GetName().c_str());
       }
+      return this->StoreResult(CM_NULLPTR);
     }
-    return this->StoreResult((this->Variable + "-NOTFOUND").c_str());
-  }
-  if (cmTarget* target = this->Makefile->FindTargetToUse(this->Name)) {
     return this->StoreResult(
       target->GetProperty(this->PropertyName, this->Makefile));
-  } else {
-    std::ostringstream e;
-    e << "could not find TARGET " << this->Name
-      << ".  Perhaps it has not yet been created.";
-    this->SetError(e.str());
-    return false;
   }
+  std::ostringstream e;
+  e << "could not find TARGET " << this->Name
+    << ".  Perhaps it has not yet been created.";
+  this->SetError(e.str());
+  return false;
 }
 
 bool cmGetPropertyCommand::HandleSourceMode()
@@ -278,13 +266,11 @@ bool cmGetPropertyCommand::HandleSourceMode()
   // Get the source file.
   if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(this->Name)) {
     return this->StoreResult(sf->GetPropertyForUser(this->PropertyName));
-  } else {
-    std::ostringstream e;
-    e << "given SOURCE name that could not be found or created: "
-      << this->Name;
-    this->SetError(e.str());
-    return false;
   }
+  std::ostringstream e;
+  e << "given SOURCE name that could not be found or created: " << this->Name;
+  this->SetError(e.str());
+  return false;
 }
 
 bool cmGetPropertyCommand::HandleTestMode()
@@ -323,7 +309,7 @@ bool cmGetPropertyCommand::HandleCacheMode()
     return false;
   }
 
-  const char* value = 0;
+  const char* value = CM_NULLPTR;
   if (this->Makefile->GetState()->GetCacheEntryValue(this->Name)) {
     value = this->Makefile->GetState()->GetCacheEntryProperty(
       this->Name, this->PropertyName);
@@ -347,12 +333,10 @@ bool cmGetPropertyCommand::HandleInstallMode()
     std::string value;
     bool isSet = file->GetProperty(this->PropertyName, value);
 
-    return this->StoreResult(isSet ? value.c_str() : 0);
-  } else {
-    std::ostringstream e;
-    e << "given INSTALL name that could not be found or created: "
-      << this->Name;
-    this->SetError(e.str());
-    return false;
+    return this->StoreResult(isSet ? value.c_str() : CM_NULLPTR);
   }
+  std::ostringstream e;
+  e << "given INSTALL name that could not be found or created: " << this->Name;
+  this->SetError(e.str());
+  return false;
 }
diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h
index aeed01d..ee61416 100644
--- a/Source/cmGetPropertyCommand.h
+++ b/Source/cmGetPropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetPropertyCommand_h
 #define cmGetPropertyCommand_h
 
@@ -19,24 +10,24 @@ class cmGetPropertyCommand : public cmCommand
 public:
   cmGetPropertyCommand();
 
-  virtual cmCommand* Clone() { return new cmGetPropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetPropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_property"; }
+  std::string GetName() const CM_OVERRIDE { return "get_property"; }
 
   cmTypeMacro(cmGetPropertyCommand, cmCommand);
 
diff --git a/Source/cmGetSourceFilePropertyCommand.cxx b/Source/cmGetSourceFilePropertyCommand.cxx
index e64befe..43f9256 100644
--- a/Source/cmGetSourceFilePropertyCommand.cxx
+++ b/Source/cmGetSourceFilePropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetSourceFilePropertyCommand.h"
 
 #include "cmSourceFile.h"
@@ -34,7 +25,7 @@ bool cmGetSourceFilePropertyCommand::InitialPass(
       this->Makefile->AddDefinition(var, sf->GetLanguage().c_str());
       return true;
     }
-    const char* prop = 0;
+    const char* prop = CM_NULLPTR;
     if (!args[2].empty()) {
       prop = sf->GetPropertyForUser(args[2]);
     }
diff --git a/Source/cmGetSourceFilePropertyCommand.h b/Source/cmGetSourceFilePropertyCommand.h
index 06f582f..184b3ce 100644
--- a/Source/cmGetSourceFilePropertyCommand.h
+++ b/Source/cmGetSourceFilePropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetSourceFilePropertyCommand_h
 #define cmGetSourceFilePropertyCommand_h
 
@@ -17,19 +8,22 @@
 class cmGetSourceFilePropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmGetSourceFilePropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetSourceFilePropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_source_file_property"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "get_source_file_property";
+  }
 
   cmTypeMacro(cmGetSourceFilePropertyCommand, cmCommand);
 };
diff --git a/Source/cmGetTargetPropertyCommand.cxx b/Source/cmGetTargetPropertyCommand.cxx
index dded9f7..fe09442 100644
--- a/Source/cmGetTargetPropertyCommand.cxx
+++ b/Source/cmGetTargetPropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetTargetPropertyCommand.h"
 
 // cmSetTargetPropertyCommand
@@ -24,22 +15,18 @@ bool cmGetTargetPropertyCommand::InitialPass(
   std::string prop;
   bool prop_exists = false;
 
-  if (args[2] == "ALIASED_TARGET") {
-    if (this->Makefile->IsAlias(targetName)) {
-      if (cmTarget* target = this->Makefile->FindTargetToUse(targetName)) {
-        prop = target->GetName();
+  if (cmTarget* tgt = this->Makefile->FindTargetToUse(targetName)) {
+    if (args[2] == "ALIASED_TARGET") {
+      if (this->Makefile->IsAlias(targetName)) {
+        prop = tgt->GetName();
+        prop_exists = true;
+      }
+    } else if (!args[2].empty()) {
+      const char* prop_cstr = tgt->GetProperty(args[2], this->Makefile);
+      if (prop_cstr) {
+        prop = prop_cstr;
         prop_exists = true;
       }
-    }
-  } else if (cmTarget* tgt = this->Makefile->FindTargetToUse(targetName)) {
-    cmTarget& target = *tgt;
-    const char* prop_cstr = 0;
-    if (!args[2].empty()) {
-      prop_cstr = target.GetProperty(args[2], this->Makefile);
-    }
-    if (prop_cstr) {
-      prop = prop_cstr;
-      prop_exists = true;
     }
   } else {
     bool issueMessage = false;
diff --git a/Source/cmGetTargetPropertyCommand.h b/Source/cmGetTargetPropertyCommand.h
index 9a1e18e..f16dea7 100644
--- a/Source/cmGetTargetPropertyCommand.h
+++ b/Source/cmGetTargetPropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetTargetPropertyCommand_h
 #define cmGetTargetPropertyCommand_h
 
@@ -17,19 +8,19 @@
 class cmGetTargetPropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmGetTargetPropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetTargetPropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_target_property"; }
+  std::string GetName() const CM_OVERRIDE { return "get_target_property"; }
 
   cmTypeMacro(cmGetTargetPropertyCommand, cmCommand);
 };
diff --git a/Source/cmGetTestPropertyCommand.cxx b/Source/cmGetTestPropertyCommand.cxx
index 6599021..4a445dc 100644
--- a/Source/cmGetTestPropertyCommand.cxx
+++ b/Source/cmGetTestPropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetTestPropertyCommand.h"
 
 #include "cmTest.h"
@@ -27,7 +18,7 @@ bool cmGetTestPropertyCommand::InitialPass(
   std::string var = args[2];
   cmTest* test = this->Makefile->GetTest(testName);
   if (test) {
-    const char* prop = 0;
+    const char* prop = CM_NULLPTR;
     if (!args[1].empty()) {
       prop = test->GetProperty(args[1]);
     }
diff --git a/Source/cmGetTestPropertyCommand.h b/Source/cmGetTestPropertyCommand.h
index fc281c4..527ee1a 100644
--- a/Source/cmGetTestPropertyCommand.h
+++ b/Source/cmGetTestPropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGetTestPropertyCommand_h
 #define cmGetTestPropertyCommand_h
 
@@ -17,19 +8,19 @@
 class cmGetTestPropertyCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmGetTestPropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmGetTestPropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "get_test_property"; }
+  std::string GetName() const CM_OVERRIDE { return "get_test_property"; }
 
   cmTypeMacro(cmGetTestPropertyCommand, cmCommand);
 };
diff --git a/Source/cmGhsMultiGpj.cxx b/Source/cmGhsMultiGpj.cxx
index ca88578..f58cfc1 100644
--- a/Source/cmGhsMultiGpj.cxx
+++ b/Source/cmGhsMultiGpj.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGhsMultiGpj.h"
 
 #include "cmGeneratedFileStream.h"
diff --git a/Source/cmGhsMultiGpj.h b/Source/cmGhsMultiGpj.h
index b388455..793d471 100644
--- a/Source/cmGhsMultiGpj.h
+++ b/Source/cmGhsMultiGpj.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGhsMultiGpj_h
 #define cmGhsMultiGpj_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmGeneratedFileStream;
diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx
index 8565fdb..959dfdb 100644
--- a/Source/cmGhsMultiTargetGenerator.cxx
+++ b/Source/cmGhsMultiTargetGenerator.cxx
@@ -1,17 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGhsMultiTargetGenerator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGhsMultiGenerator.h"
 #include "cmLocalGhsMultiGenerator.h"
 #include "cmMakefile.h"
@@ -371,7 +363,7 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLibraries(
     bool useWatcomQuote =
       this->Makefile->IsOn(createRule + "_USE_WATCOM_QUOTE");
     this->LocalGenerator->GetTargetFlags(
-      linkLibraries, flags, linkFlags, frameworkPath, linkPath,
+      config, linkLibraries, flags, linkFlags, frameworkPath, linkPath,
       this->GeneratorTarget, useWatcomQuote);
     linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
 
diff --git a/Source/cmGhsMultiTargetGenerator.h b/Source/cmGhsMultiTargetGenerator.h
index 92a1109..2cdf68e 100644
--- a/Source/cmGhsMultiTargetGenerator.h
+++ b/Source/cmGhsMultiTargetGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGhsMultiTargetGenerator_h
 #define cmGhsMultiTargetGenerator_h
 
@@ -16,13 +7,13 @@
 
 #include "cmTarget.h"
 
+class cmCustomCommand;
 class cmGeneratedFileStream;
+class cmGeneratorTarget;
 class cmGlobalGhsMultiGenerator;
 class cmLocalGhsMultiGenerator;
 class cmMakefile;
 class cmSourceFile;
-class cmGeneratedFileStream;
-class cmCustomCommand;
 
 class cmGhsMultiTargetGenerator
 {
diff --git a/Source/cmGlobalBorlandMakefileGenerator.cxx b/Source/cmGlobalBorlandMakefileGenerator.cxx
index 0f4de73..5a2150d 100644
--- a/Source/cmGlobalBorlandMakefileGenerator.cxx
+++ b/Source/cmGlobalBorlandMakefileGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalBorlandMakefileGenerator.h"
 
 #include "cmLocalUnixMakefileGenerator3.h"
diff --git a/Source/cmGlobalBorlandMakefileGenerator.h b/Source/cmGlobalBorlandMakefileGenerator.h
index 4e10f10..5578d76 100644
--- a/Source/cmGlobalBorlandMakefileGenerator.h
+++ b/Source/cmGlobalBorlandMakefileGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalBorlandMakefileGenerator_h
 #define cmGlobalBorlandMakefileGenerator_h
 
diff --git a/Source/cmGlobalCommonGenerator.cxx b/Source/cmGlobalCommonGenerator.cxx
index 900b08e..3b7de4b 100644
--- a/Source/cmGlobalCommonGenerator.cxx
+++ b/Source/cmGlobalCommonGenerator.cxx
@@ -1,16 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalCommonGenerator.h"
 
+class cmake;
+
 cmGlobalCommonGenerator::cmGlobalCommonGenerator(cmake* cm)
   : cmGlobalGenerator(cm)
 {
diff --git a/Source/cmGlobalCommonGenerator.h b/Source/cmGlobalCommonGenerator.h
index 7bb0e55..e8e6ad9 100644
--- a/Source/cmGlobalCommonGenerator.h
+++ b/Source/cmGlobalCommonGenerator.h
@@ -1,19 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalCommonGenerator_h
 #define cmGlobalCommonGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmGlobalGenerator.h"
 
+class cmake;
+
 /** \class cmGlobalCommonGenerator
  * \brief Common infrastructure for Makefile and Ninja global generators.
  */
@@ -21,7 +16,7 @@ class cmGlobalCommonGenerator : public cmGlobalGenerator
 {
 public:
   cmGlobalCommonGenerator(cmake* cm);
-  ~cmGlobalCommonGenerator();
+  ~cmGlobalCommonGenerator() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index a1764a3..7132ade 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #include "windows.h" // this must be first to define GetCurrentDirectory
 #if defined(_MSC_VER) && _MSC_VER >= 1800
@@ -21,6 +12,8 @@
 #include "cmAlgorithms.h"
 #include "cmCPackPropertiesGenerator.h"
 #include "cmComputeTargetDepends.h"
+#include "cmCustomCommand.h"
+#include "cmCustomCommandLines.h"
 #include "cmExportBuildFileGenerator.h"
 #include "cmExternalMakefileProjectGenerator.h"
 #include "cmGeneratedFileStream.h"
@@ -29,25 +22,31 @@
 #include "cmInstallGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmPolicies.h"
 #include "cmQtAutoGeneratorInitializer.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
-#include "cmTargetExport.h"
 #include "cmVersion.h"
 #include "cmake.h"
 
+#include <algorithm>
+#include <assert.h>
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#include "cm_jsoncpp_value.h"
-#include "cm_jsoncpp_writer.h"
+#include <cm_jsoncpp_value.h>
+#include <cm_jsoncpp_writer.h>
 #include <cmsys/MD5.h>
 #endif
 
-#include <stdlib.h> // required for atof
-
-#include <assert.h>
+class cmInstalledFile;
 
 bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
                                                   cmTarget const* t2) const
@@ -81,11 +80,12 @@ cmGlobalGenerator::cmGlobalGenerator(cmake* cm)
   // how long to let try compiles run
   this->TryCompileTimeout = 0;
 
-  this->ExtraGenerator = 0;
-  this->CurrentMakefile = 0;
-  this->TryCompileOuterMakefile = 0;
+  this->ExtraGenerator = CM_NULLPTR;
+  this->CurrentMakefile = CM_NULLPTR;
+  this->TryCompileOuterMakefile = CM_NULLPTR;
 
   this->ConfigureDoneCMP0026AndCMP0024 = false;
+  this->FirstTimeProgress = 0.0f;
 
   cm->GetState()->SetMinGWMake(false);
   cm->GetState()->SetMSYSShell(false);
@@ -180,8 +180,7 @@ void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang,
   } else {
     path = name;
   }
-  if ((path.empty() || !cmSystemTools::FileExists(path.c_str())) &&
-      (optional == false)) {
+  if (!optional && (path.empty() || !cmSystemTools::FileExists(path))) {
     return;
   }
   const char* cname =
@@ -243,7 +242,7 @@ bool cmGlobalGenerator::GenerateImportFile(const std::string& file)
     }
 
     delete it->second;
-    it->second = 0;
+    it->second = CM_NULLPTR;
     this->BuildExportSets.erase(it);
     return result;
   }
@@ -311,6 +310,12 @@ void cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
   }
 }
 
+bool cmGlobalGenerator::CheckLanguages(
+  std::vector<std::string> const& /* languages */, cmMakefile* /* mf */) const
+{
+  return true;
+}
+
 // enable the given language
 //
 // The following files are loaded in this order:
@@ -420,6 +425,10 @@ void cmGlobalGenerator::EnableLanguage(
   // find and make sure CMAKE_MAKE_PROGRAM is defined
   this->FindMakeProgram(mf);
 
+  if (!this->CheckLanguages(languages, mf)) {
+    return;
+  }
+
   // try and load the CMakeSystem.cmake if it is there
   std::string fpath = rootBin;
   bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
@@ -998,6 +1007,25 @@ void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
   }
 }
 
+const char* cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
+{
+  assert(!this->Makefiles.empty());
+  return this->Makefiles[0]->GetDefinition(name);
+}
+
+bool cmGlobalGenerator::GlobalSettingIsOn(std::string const& name) const
+{
+  assert(!this->Makefiles.empty());
+  return this->Makefiles[0]->IsOn(name);
+}
+
+const char* cmGlobalGenerator::GetSafeGlobalSetting(
+  std::string const& name) const
+{
+  assert(!this->Makefiles.empty());
+  return this->Makefiles[0]->GetSafeDefinition(name);
+}
+
 bool cmGlobalGenerator::IgnoreFile(const char* ext) const
 {
   if (!this->GetLanguageFromExtension(ext).empty()) {
@@ -1041,6 +1069,7 @@ void cmGlobalGenerator::Configure()
 
   cmMakefile* dirMf = new cmMakefile(this, snapshot);
   this->Makefiles.push_back(dirMf);
+  this->IndexMakefile(dirMf);
 
   this->BinaryDirectories.insert(
     this->CMakeInstance->GetHomeOutputDirectory());
@@ -1053,16 +1082,16 @@ void cmGlobalGenerator::Configure()
   this->ConfigureDoneCMP0026AndCMP0024 = true;
 
   // Put a copy of each global target in every directory.
-  cmTargets globalTargets;
-  this->CreateDefaultGlobalTargets(&globalTargets);
+  std::vector<GlobalTargetInfo> globalTargets;
+  this->CreateDefaultGlobalTargets(globalTargets);
 
   for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
     cmMakefile* mf = this->Makefiles[i];
     cmTargets* targets = &(mf->GetTargets());
-    cmTargets::iterator tit;
-    for (tit = globalTargets.begin(); tit != globalTargets.end(); ++tit) {
-      (*targets)[tit->first] = tit->second;
-      (*targets)[tit->first].SetMakefile(mf);
+    for (std::vector<GlobalTargetInfo>::iterator gti = globalTargets.begin();
+         gti != globalTargets.end(); ++gti) {
+      targets->insert(
+        cmTargets::value_type(gti->Name, this->CreateGlobalTarget(*gti, mf)));
     }
   }
 
@@ -1082,7 +1111,7 @@ void cmGlobalGenerator::Configure()
     std::ostringstream msg;
     if (cmSystemTools::GetErrorOccuredFlag()) {
       msg << "Configuring incomplete, errors occurred!";
-      const char* logs[] = { "CMakeOutput.log", "CMakeError.log", 0 };
+      const char* logs[] = { "CMakeOutput.log", "CMakeError.log", CM_NULLPTR };
       for (const char** log = logs; *log; ++log) {
         std::string f = this->CMakeInstance->GetHomeOutputDirectory();
         f += this->CMakeInstance->GetCMakeFilesDirectory();
@@ -1129,7 +1158,7 @@ cmExportBuildFileGenerator* cmGlobalGenerator::GetExportedTargetsFile(
 {
   std::map<std::string, cmExportBuildFileGenerator*>::const_iterator it =
     this->BuildExportSets.find(filename);
-  return it == this->BuildExportSets.end() ? 0 : it->second;
+  return it == this->BuildExportSets.end() ? CM_NULLPTR : it->second;
 }
 
 void cmGlobalGenerator::AddCMP0042WarnTarget(const std::string& target)
@@ -1270,7 +1299,7 @@ void cmGlobalGenerator::Generate()
       "Generating", (static_cast<float>(i) + 1.0f) /
         static_cast<float>(this->LocalGenerators.size()));
   }
-  this->SetCurrentMakefile(0);
+  this->SetCurrentMakefile(CM_NULLPTR);
 
   if (!this->GenerateCPackPropertiesFile()) {
     this->GetCMakeInstance()->IssueMessage(
@@ -1292,7 +1321,7 @@ void cmGlobalGenerator::Generate()
 
   this->WriteSummary();
 
-  if (this->ExtraGenerator != 0) {
+  if (this->ExtraGenerator != CM_NULLPTR) {
     this->ExtraGenerator->Generate();
   }
 
@@ -1510,13 +1539,15 @@ void cmGlobalGenerator::ClearGeneratorMembers()
   this->TargetDependencies.clear();
   this->TargetSearchIndex.clear();
   this->GeneratorTargetSearchIndex.clear();
+  this->MakefileSearchIndex.clear();
   this->ProjectMap.clear();
   this->RuleHashes.clear();
   this->DirectoryContentMap.clear();
   this->BinaryDirectories.clear();
 }
 
-void cmGlobalGenerator::ComputeTargetObjectDirectory(cmGeneratorTarget*) const
+void cmGlobalGenerator::ComputeTargetObjectDirectory(
+  cmGeneratorTarget* /*unused*/) const
 {
 }
 
@@ -1645,15 +1676,17 @@ int cmGlobalGenerator::TryCompile(const std::string& srcdir,
 }
 
 void cmGlobalGenerator::GenerateBuildCommand(
-  std::vector<std::string>& makeCommand, const std::string&,
-  const std::string&, const std::string&, const std::string&,
-  const std::string&, bool, bool, std::vector<std::string> const&)
+  std::vector<std::string>& makeCommand, const std::string& /*unused*/,
+  const std::string& /*unused*/, const std::string& /*unused*/,
+  const std::string& /*unused*/, const std::string& /*unused*/,
+  bool /*unused*/, bool /*unused*/, std::vector<std::string> const& /*unused*/)
 {
   makeCommand.push_back(
     "cmGlobalGenerator::GenerateBuildCommand not implemented");
 }
 
-int cmGlobalGenerator::Build(const std::string&, const std::string& bindir,
+int cmGlobalGenerator::Build(const std::string& /*unused*/,
+                             const std::string& bindir,
                              const std::string& projectName,
                              const std::string& target, std::string& output,
                              const std::string& makeCommandCSTR,
@@ -1699,7 +1732,8 @@ int cmGlobalGenerator::Build(const std::string&, const std::string& bindir,
     output += "\n";
 
     if (!cmSystemTools::RunSingleCommand(cleanCommand, outputPtr, outputPtr,
-                                         &retVal, 0, outputflag, timeout)) {
+                                         &retVal, CM_NULLPTR, outputflag,
+                                         timeout)) {
       cmSystemTools::SetRunCommandHideConsole(hideconsole);
       cmSystemTools::Error("Generator: execution of make clean failed.");
       output += *outputPtr;
@@ -1719,7 +1753,8 @@ int cmGlobalGenerator::Build(const std::string&, const std::string& bindir,
   output += "\n";
 
   if (!cmSystemTools::RunSingleCommand(makeCommand, outputPtr, outputPtr,
-                                       &retVal, 0, outputflag, timeout)) {
+                                       &retVal, CM_NULLPTR, outputflag,
+                                       timeout)) {
     cmSystemTools::SetRunCommandHideConsole(hideconsole);
     cmSystemTools::Error(
       "Generator: execution of make failed. Make command was: ",
@@ -1782,6 +1817,7 @@ std::string cmGlobalGenerator::GenerateCMakeBuildCommand(
 void cmGlobalGenerator::AddMakefile(cmMakefile* mf)
 {
   this->Makefiles.push_back(mf);
+  this->IndexMakefile(mf);
 
   // update progress
   // estimate how many lg there will be
@@ -1939,14 +1975,11 @@ void cmGlobalGenerator::FillProjectMap()
 
 cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const
 {
-  for (std::vector<cmMakefile*>::const_iterator it = this->Makefiles.begin();
-       it != this->Makefiles.end(); ++it) {
-    std::string sd = (*it)->GetCurrentSourceDirectory();
-    if (sd == start_dir) {
-      return *it;
-    }
+  MakefileMap::const_iterator i = this->MakefileSearchIndex.find(start_dir);
+  if (i != this->MakefileSearchIndex.end()) {
+    return i->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 ///! Find a local generator by its startdirectory
@@ -1961,7 +1994,7 @@ cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator(
       return *it;
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmGlobalGenerator::AddAlias(const std::string& name,
@@ -1989,13 +2022,24 @@ void cmGlobalGenerator::IndexGeneratorTarget(cmGeneratorTarget* gt)
   }
 }
 
+void cmGlobalGenerator::IndexMakefile(cmMakefile* mf)
+{
+  // FIXME: add_subdirectory supports multiple build directories
+  // sharing the same source directory.  We currently index only the
+  // first one, because that is what FindMakefile has always returned.
+  // All of its callers will need to be modified to support looking
+  // up directories by build directory path.
+  this->MakefileSearchIndex.insert(
+    MakefileMap::value_type(mf->GetCurrentSourceDirectory(), mf));
+}
+
 cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const
 {
   TargetMap::const_iterator i = this->TargetSearchIndex.find(name);
   if (i != this->TargetSearchIndex.end()) {
     return i->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
@@ -2006,7 +2050,7 @@ cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
   if (i != this->GeneratorTargetSearchIndex.end()) {
     return i->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmTarget* cmGlobalGenerator::FindTarget(const std::string& name,
@@ -2057,15 +2101,27 @@ inline std::string removeQuotes(const std::string& s)
   return s;
 }
 
-void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
+void cmGlobalGenerator::CreateDefaultGlobalTargets(
+  std::vector<GlobalTargetInfo>& targets)
+{
+  this->AddGlobalTarget_Package(targets);
+  this->AddGlobalTarget_PackageSource(targets);
+  this->AddGlobalTarget_Test(targets);
+  this->AddGlobalTarget_EditCache(targets);
+  this->AddGlobalTarget_RebuildCache(targets);
+  this->AddGlobalTarget_Install(targets);
+}
+
+void cmGlobalGenerator::AddGlobalTarget_Package(
+  std::vector<GlobalTargetInfo>& targets)
 {
   cmMakefile* mf = this->Makefiles[0];
   const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
-
-  // CPack
-  std::string workingDir = mf->GetCurrentBinaryDirectory();
-  cmCustomCommandLines cpackCommandLines;
-  std::vector<std::string> depends;
+  GlobalTargetInfo gti;
+  gti.Name = this->GetPackageTargetName();
+  gti.Message = "Run CPack packaging tool...";
+  gti.UsesTerminal = true;
+  gti.WorkingDir = mf->GetCurrentBinaryDirectory();
   cmCustomCommandLine singleLine;
   singleLine.push_back(cmSystemTools::GetCPackCommand());
   if (cmakeCfgIntDir && *cmakeCfgIntDir && cmakeCfgIntDir[0] != '.') {
@@ -2074,55 +2130,61 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
   }
   singleLine.push_back("--config");
   std::string configFile = mf->GetCurrentBinaryDirectory();
-  ;
   configFile += "/CPackConfig.cmake";
   std::string relConfigFile = "./CPackConfig.cmake";
   singleLine.push_back(relConfigFile);
-  cpackCommandLines.push_back(singleLine);
+  gti.CommandLines.push_back(singleLine);
   if (this->GetPreinstallTargetName()) {
-    depends.push_back(this->GetPreinstallTargetName());
+    gti.Depends.push_back(this->GetPreinstallTargetName());
   } else {
     const char* noPackageAll =
       mf->GetDefinition("CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY");
     if (!noPackageAll || cmSystemTools::IsOff(noPackageAll)) {
-      depends.push_back(this->GetAllTargetName());
+      gti.Depends.push_back(this->GetAllTargetName());
     }
   }
   if (cmSystemTools::FileExists(configFile.c_str())) {
-    (*targets)[this->GetPackageTargetName()] = this->CreateGlobalTarget(
-      this->GetPackageTargetName(), "Run CPack packaging tool...",
-      &cpackCommandLines, depends, workingDir.c_str(), /*uses_terminal*/ true);
+    targets.push_back(gti);
   }
-  // CPack source
+}
+
+void cmGlobalGenerator::AddGlobalTarget_PackageSource(
+  std::vector<GlobalTargetInfo>& targets)
+{
+  cmMakefile* mf = this->Makefiles[0];
   const char* packageSourceTargetName = this->GetPackageSourceTargetName();
   if (packageSourceTargetName) {
-    cpackCommandLines.erase(cpackCommandLines.begin(),
-                            cpackCommandLines.end());
-    singleLine.erase(singleLine.begin(), singleLine.end());
-    depends.erase(depends.begin(), depends.end());
+    GlobalTargetInfo gti;
+    gti.Name = packageSourceTargetName;
+    gti.Message = "Run CPack packaging tool for source...";
+    gti.WorkingDir = mf->GetCurrentBinaryDirectory();
+    gti.UsesTerminal = true;
+    cmCustomCommandLine singleLine;
     singleLine.push_back(cmSystemTools::GetCPackCommand());
     singleLine.push_back("--config");
-    configFile = mf->GetCurrentBinaryDirectory();
-    ;
+    std::string configFile = mf->GetCurrentBinaryDirectory();
     configFile += "/CPackSourceConfig.cmake";
-    relConfigFile = "./CPackSourceConfig.cmake";
+    std::string relConfigFile = "./CPackSourceConfig.cmake";
     singleLine.push_back(relConfigFile);
     if (cmSystemTools::FileExists(configFile.c_str())) {
       singleLine.push_back(configFile);
-      cpackCommandLines.push_back(singleLine);
-      (*targets)[packageSourceTargetName] = this->CreateGlobalTarget(
-        packageSourceTargetName, "Run CPack packaging tool for source...",
-        &cpackCommandLines, depends, workingDir.c_str(),
-        /*uses_terminal*/ true);
+      gti.CommandLines.push_back(singleLine);
+      targets.push_back(gti);
     }
   }
+}
 
-  // Test
+void cmGlobalGenerator::AddGlobalTarget_Test(
+  std::vector<GlobalTargetInfo>& targets)
+{
+  cmMakefile* mf = this->Makefiles[0];
+  const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
   if (mf->IsOn("CMAKE_TESTING_ENABLED")) {
-    cpackCommandLines.erase(cpackCommandLines.begin(),
-                            cpackCommandLines.end());
-    singleLine.erase(singleLine.begin(), singleLine.end());
-    depends.erase(depends.begin(), depends.end());
+    GlobalTargetInfo gti;
+    gti.Name = this->GetTestTargetName();
+    gti.Message = "Running tests...";
+    gti.UsesTerminal = true;
+    cmCustomCommandLine singleLine;
     singleLine.push_back(cmSystemTools::GetCTestCommand());
     singleLine.push_back("--force-new-ctest-process");
     if (cmakeCfgIntDir && *cmakeCfgIntDir && cmakeCfgIntDir[0] != '.') {
@@ -2133,20 +2195,19 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
     {
       singleLine.push_back("$(ARGS)");
     }
-    cpackCommandLines.push_back(singleLine);
-    (*targets)[this->GetTestTargetName()] =
-      this->CreateGlobalTarget(this->GetTestTargetName(), "Running tests...",
-                               &cpackCommandLines, depends, 0,
-                               /*uses_terminal*/ true);
+    gti.CommandLines.push_back(singleLine);
+    targets.push_back(gti);
   }
+}
 
-  // Edit Cache
+void cmGlobalGenerator::AddGlobalTarget_EditCache(
+  std::vector<GlobalTargetInfo>& targets)
+{
   const char* editCacheTargetName = this->GetEditCacheTargetName();
   if (editCacheTargetName) {
-    cpackCommandLines.erase(cpackCommandLines.begin(),
-                            cpackCommandLines.end());
-    singleLine.erase(singleLine.begin(), singleLine.end());
-    depends.erase(depends.begin(), depends.end());
+    GlobalTargetInfo gti;
+    gti.Name = editCacheTargetName;
+    cmCustomCommandLine singleLine;
 
     // Use generator preference for the edit_cache rule if it is defined.
     std::string edit_cmd = this->GetEditCacheCommand();
@@ -2154,50 +2215,55 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
       singleLine.push_back(edit_cmd);
       singleLine.push_back("-H$(CMAKE_SOURCE_DIR)");
       singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
-      cpackCommandLines.push_back(singleLine);
-      (*targets)[editCacheTargetName] = this->CreateGlobalTarget(
-        editCacheTargetName, "Running CMake cache editor...",
-        &cpackCommandLines, depends, 0, /*uses_terminal*/ true);
+      gti.Message = "Running CMake cache editor...";
+      gti.UsesTerminal = true;
+      gti.CommandLines.push_back(singleLine);
     } else {
       singleLine.push_back(cmSystemTools::GetCMakeCommand());
       singleLine.push_back("-E");
       singleLine.push_back("echo");
       singleLine.push_back("No interactive CMake dialog available.");
-      cpackCommandLines.push_back(singleLine);
-      (*targets)[editCacheTargetName] = this->CreateGlobalTarget(
-        editCacheTargetName, "No interactive CMake dialog available...",
-        &cpackCommandLines, depends, 0, /*uses_terminal*/ false);
+      gti.Message = "No interactive CMake dialog available...";
+      gti.UsesTerminal = false;
+      gti.CommandLines.push_back(singleLine);
     }
+
+    targets.push_back(gti);
   }
+}
 
-  // Rebuild Cache
+void cmGlobalGenerator::AddGlobalTarget_RebuildCache(
+  std::vector<GlobalTargetInfo>& targets)
+{
   const char* rebuildCacheTargetName = this->GetRebuildCacheTargetName();
   if (rebuildCacheTargetName) {
-    cpackCommandLines.erase(cpackCommandLines.begin(),
-                            cpackCommandLines.end());
-    singleLine.erase(singleLine.begin(), singleLine.end());
-    depends.erase(depends.begin(), depends.end());
+    GlobalTargetInfo gti;
+    gti.Name = rebuildCacheTargetName;
+    gti.Message = "Running CMake to regenerate build system...";
+    gti.UsesTerminal = true;
+    cmCustomCommandLine singleLine;
     singleLine.push_back(cmSystemTools::GetCMakeCommand());
     singleLine.push_back("-H$(CMAKE_SOURCE_DIR)");
     singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
-    cpackCommandLines.push_back(singleLine);
-    (*targets)[rebuildCacheTargetName] = this->CreateGlobalTarget(
-      rebuildCacheTargetName, "Running CMake to regenerate build system...",
-      &cpackCommandLines, depends, 0, /*uses_terminal*/ true);
+    gti.CommandLines.push_back(singleLine);
+    targets.push_back(gti);
   }
+}
 
-  // Install
+void cmGlobalGenerator::AddGlobalTarget_Install(
+  std::vector<GlobalTargetInfo>& targets)
+{
+  cmMakefile* mf = this->Makefiles[0];
+  const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
   bool skipInstallRules = mf->IsOn("CMAKE_SKIP_INSTALL_RULES");
   if (this->InstallTargetEnabled && skipInstallRules) {
-    mf->IssueMessage(cmake::WARNING,
-                     "CMAKE_SKIP_INSTALL_RULES was enabled even though "
-                     "installation rules have been specified");
+    this->CMakeInstance->IssueMessage(
+      cmake::WARNING, "CMAKE_SKIP_INSTALL_RULES was enabled even though "
+                      "installation rules have been specified",
+      mf->GetBacktrace());
   } else if (this->InstallTargetEnabled && !skipInstallRules) {
     if (!cmakeCfgIntDir || !*cmakeCfgIntDir || cmakeCfgIntDir[0] == '.') {
       std::set<std::string>* componentsSet = &this->InstallComponents;
-      cpackCommandLines.erase(cpackCommandLines.begin(),
-                              cpackCommandLines.end());
-      depends.erase(depends.begin(), depends.end());
       std::ostringstream ostr;
       if (!componentsSet->empty()) {
         ostr << "Available install components are: ";
@@ -2205,23 +2271,25 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
       } else {
         ostr << "Only default component available";
       }
-      singleLine.push_back(ostr.str());
-      (*targets)["list_install_components"] = this->CreateGlobalTarget(
-        "list_install_components", ostr.str().c_str(), &cpackCommandLines,
-        depends, 0, /*uses_terminal*/ false);
+      GlobalTargetInfo gti;
+      gti.Name = "list_install_components";
+      gti.Message = ostr.str();
+      gti.UsesTerminal = false;
+      targets.push_back(gti);
     }
     std::string cmd = cmSystemTools::GetCMakeCommand();
-    cpackCommandLines.erase(cpackCommandLines.begin(),
-                            cpackCommandLines.end());
-    singleLine.erase(singleLine.begin(), singleLine.end());
-    depends.erase(depends.begin(), depends.end());
+    GlobalTargetInfo gti;
+    gti.Name = this->GetInstallTargetName();
+    gti.Message = "Install the project...";
+    gti.UsesTerminal = true;
+    cmCustomCommandLine singleLine;
     if (this->GetPreinstallTargetName()) {
-      depends.push_back(this->GetPreinstallTargetName());
+      gti.Depends.push_back(this->GetPreinstallTargetName());
     } else {
       const char* noall =
         mf->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
       if (!noall || cmSystemTools::IsOff(noall)) {
-        depends.push_back(this->GetAllTargetName());
+        gti.Depends.push_back(this->GetAllTargetName());
       }
     }
     if (mf->GetDefinition("CMake_BINARY_DIR") &&
@@ -2246,40 +2314,39 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets)
     }
     singleLine.push_back("-P");
     singleLine.push_back("cmake_install.cmake");
-    cpackCommandLines.push_back(singleLine);
-    (*targets)[this->GetInstallTargetName()] = this->CreateGlobalTarget(
-      this->GetInstallTargetName(), "Install the project...",
-      &cpackCommandLines, depends, 0, /*uses_terminal*/ true);
+    gti.CommandLines.push_back(singleLine);
+    targets.push_back(gti);
 
     // install_local
     if (const char* install_local = this->GetInstallLocalTargetName()) {
+      gti.Name = install_local;
+      gti.Message = "Installing only the local directory...";
+      gti.UsesTerminal = true;
+      gti.CommandLines.clear();
+
       cmCustomCommandLine localCmdLine = singleLine;
 
       localCmdLine.insert(localCmdLine.begin() + 1,
                           "-DCMAKE_INSTALL_LOCAL_ONLY=1");
-      cpackCommandLines.erase(cpackCommandLines.begin(),
-                              cpackCommandLines.end());
-      cpackCommandLines.push_back(localCmdLine);
 
-      (*targets)[install_local] = this->CreateGlobalTarget(
-        install_local, "Installing only the local directory...",
-        &cpackCommandLines, depends, 0, /*uses_terminal*/ true);
+      gti.CommandLines.push_back(localCmdLine);
+      targets.push_back(gti);
     }
 
     // install_strip
     const char* install_strip = this->GetInstallStripTargetName();
-    if ((install_strip != 0) && (mf->IsSet("CMAKE_STRIP"))) {
+    if ((install_strip != CM_NULLPTR) && (mf->IsSet("CMAKE_STRIP"))) {
+      gti.Name = install_strip;
+      gti.Message = "Installing the project stripped...";
+      gti.UsesTerminal = true;
+      gti.CommandLines.clear();
+
       cmCustomCommandLine stripCmdLine = singleLine;
 
       stripCmdLine.insert(stripCmdLine.begin() + 1,
                           "-DCMAKE_INSTALL_DO_STRIP=1");
-      cpackCommandLines.erase(cpackCommandLines.begin(),
-                              cpackCommandLines.end());
-      cpackCommandLines.push_back(stripCmdLine);
-
-      (*targets)[install_strip] = this->CreateGlobalTarget(
-        install_strip, "Installing the project stripped...",
-        &cpackCommandLines, depends, 0, /*uses_terminal*/ true);
+      gti.CommandLines.push_back(stripCmdLine);
+      targets.push_back(gti);
     }
   }
 }
@@ -2313,27 +2380,27 @@ bool cmGlobalGenerator::UseFolderProperty()
   return false;
 }
 
-cmTarget cmGlobalGenerator::CreateGlobalTarget(
-  const std::string& name, const char* message,
-  const cmCustomCommandLines* commandLines, std::vector<std::string> depends,
-  const char* workingDirectory, bool uses_terminal)
+cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
+                                               cmMakefile* mf)
 {
   // Package
-  cmTarget target;
-  target.SetType(cmState::GLOBAL_TARGET, name);
+  cmTarget target(gti.Name, cmState::GLOBAL_TARGET, cmTarget::VisibilityNormal,
+                  mf);
   target.SetProperty("EXCLUDE_FROM_ALL", "TRUE");
 
   std::vector<std::string> no_outputs;
   std::vector<std::string> no_byproducts;
   std::vector<std::string> no_depends;
   // Store the custom command in the target.
-  cmCustomCommand cc(0, no_outputs, no_byproducts, no_depends, *commandLines,
-                     0, workingDirectory);
-  cc.SetUsesTerminal(uses_terminal);
+  cmCustomCommand cc(CM_NULLPTR, no_outputs, no_byproducts, no_depends,
+                     gti.CommandLines, CM_NULLPTR, gti.WorkingDir.c_str());
+  cc.SetUsesTerminal(gti.UsesTerminal);
   target.AddPostBuildCommand(cc);
-  target.SetProperty("EchoString", message);
-  std::vector<std::string>::iterator dit;
-  for (dit = depends.begin(); dit != depends.end(); ++dit) {
+  if (!gti.Message.empty()) {
+    target.SetProperty("EchoString", gti.Message.c_str());
+  }
+  for (std::vector<std::string>::const_iterator dit = gti.Depends.begin();
+       dit != gti.Depends.end(); ++dit) {
     target.AddUtility(*dit);
   }
 
@@ -2370,10 +2437,10 @@ std::string cmGlobalGenerator::GetSharedLibFlagsForLanguage(
   return "";
 }
 
-void cmGlobalGenerator::AppendDirectoryForConfig(const std::string&,
-                                                 const std::string&,
-                                                 const std::string&,
-                                                 std::string&)
+void cmGlobalGenerator::AppendDirectoryForConfig(const std::string& /*unused*/,
+                                                 const std::string& /*unused*/,
+                                                 const std::string& /*unused*/,
+                                                 std::string& /*unused*/)
 {
   // Subclasses that support multiple configurations should implement
   // this method to append the subdirectory for the given build
@@ -2406,7 +2473,7 @@ void cmGlobalGenerator::SetExternalMakefileProjectGenerator(
   cmExternalMakefileProjectGenerator* extraGenerator)
 {
   this->ExtraGenerator = extraGenerator;
-  if (this->ExtraGenerator != 0) {
+  if (this->ExtraGenerator != CM_NULLPTR) {
     this->ExtraGenerator->SetGlobalGenerator(this);
   }
 }
@@ -2542,8 +2609,8 @@ void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
 
   // Shorten the output name (in expected use case).
   cmOutputConverter converter(this->GetMakefiles()[0]->GetStateSnapshot());
-  std::string fname =
-    converter.Convert(outputs[0], cmOutputConverter::HOME_OUTPUT);
+  std::string fname = converter.ConvertToRelativePath(
+    this->GetMakefiles()[0]->GetState()->GetBinaryDirectory(), outputs[0]);
 
   // Associate the hash with this output.
   this->RuleHashes[fname] = hash;
@@ -2571,7 +2638,7 @@ void cmGlobalGenerator::CheckRuleHashes(std::string const& pfile,
 #if defined(_WIN32) || defined(__CYGWIN__)
   cmsys::ifstream fin(pfile.c_str(), std::ios::in | std::ios::binary);
 #else
-  cmsys::ifstream fin(pfile.c_str(), std::ios::in);
+  cmsys::ifstream fin(pfile.c_str());
 #endif
   if (!fin) {
     return;
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index 2575911..add2b92 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -1,46 +1,40 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalGenerator_h
 #define cmGlobalGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include "cmExportSetMap.h" // For cmExportSetMap
-#include "cmGeneratorExpression.h"
-#include "cmGeneratorTarget.h"
+#include "cmExportSetMap.h"
 #include "cmState.h"
-#include "cmSystemTools.h"  // for cmSystemTools::OutputOption
-#include "cmTarget.h"       // For cmTargets
-#include "cmTargetDepend.h" // For cmTargetDependSet
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetDepend.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmFileLockPool.h"
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 #include <unordered_map>
 #else
 #include <cmsys/hash_map.hxx>
 #endif
 #endif
 
-class cmake;
+class cmCustomCommandLines;
+class cmSourceFile;
+class cmExportBuildFileGenerator;
+class cmExternalMakefileProjectGenerator;
 class cmGeneratorTarget;
-class cmMakefile;
 class cmLocalGenerator;
-class cmExternalMakefileProjectGenerator;
-class cmTarget;
-class cmInstallTargetGenerator;
-class cmInstallFilesGenerator;
-class cmExportBuildFileGenerator;
+class cmMakefile;
+class cmake;
 
 /** \class cmGlobalGenerator
  * \brief Responsible for overseeing the generation process for the entire tree
@@ -200,6 +194,10 @@ public:
 
   cmExportSetMap& GetExportSets() { return this->ExportSets; }
 
+  const char* GetGlobalSetting(std::string const& name) const;
+  bool GlobalSettingIsOn(std::string const& name) const;
+  const char* GetSafeGlobalSetting(std::string const& name) const;
+
   /** Add a file to the manifest of generated targets for a configuration.  */
   void AddToManifest(std::string const& f);
 
@@ -277,15 +275,15 @@ public:
 
   virtual const char* GetAllTargetName() const { return "ALL_BUILD"; }
   virtual const char* GetInstallTargetName() const { return "INSTALL"; }
-  virtual const char* GetInstallLocalTargetName() const { return 0; }
-  virtual const char* GetInstallStripTargetName() const { return 0; }
-  virtual const char* GetPreinstallTargetName() const { return 0; }
+  virtual const char* GetInstallLocalTargetName() const { return CM_NULLPTR; }
+  virtual const char* GetInstallStripTargetName() const { return CM_NULLPTR; }
+  virtual const char* GetPreinstallTargetName() const { return CM_NULLPTR; }
   virtual const char* GetTestTargetName() const { return "RUN_TESTS"; }
   virtual const char* GetPackageTargetName() const { return "PACKAGE"; }
-  virtual const char* GetPackageSourceTargetName() const { return 0; }
-  virtual const char* GetEditCacheTargetName() const { return 0; }
-  virtual const char* GetRebuildCacheTargetName() const { return 0; }
-  virtual const char* GetCleanTargetName() const { return 0; }
+  virtual const char* GetPackageSourceTargetName() const { return CM_NULLPTR; }
+  virtual const char* GetEditCacheTargetName() const { return CM_NULLPTR; }
+  virtual const char* GetRebuildCacheTargetName() const { return CM_NULLPTR; }
+  virtual const char* GetCleanTargetName() const { return CM_NULLPTR; }
 
   // Lookup edit_cache target command preferred by this generator.
   virtual std::string GetEditCacheCommand() const { return ""; }
@@ -319,7 +317,7 @@ public:
 
   /** Return true if the generated build tree may contain multiple builds.
       i.e. "Can I build Debug and Release in the same tree?" */
-  virtual bool IsMultiConfig() { return false; }
+  virtual bool IsMultiConfig() const { return false; }
 
   std::string GetSharedLibFlagsForLanguage(std::string const& lang) const;
 
@@ -377,6 +375,8 @@ protected:
   void SetLanguageEnabledFlag(const std::string& l, cmMakefile* mf);
   void SetLanguageEnabledMaps(const std::string& l, cmMakefile* mf);
   void FillExtensionToLanguageMap(const std::string& l, cmMakefile* mf);
+  virtual bool CheckLanguages(std::vector<std::string> const& languages,
+                              cmMakefile* mf) const;
   virtual void PrintCompilerAdvice(std::ostream& os, std::string const& lang,
                                    const char* envVar) const;
 
@@ -398,11 +398,30 @@ protected:
   bool IsExcluded(cmLocalGenerator* root, cmLocalGenerator* gen) const;
   bool IsExcluded(cmLocalGenerator* root, cmGeneratorTarget* target) const;
   virtual void InitializeProgressMarks() {}
-  void CreateDefaultGlobalTargets(cmTargets* targets);
-  cmTarget CreateGlobalTarget(const std::string& name, const char* message,
-                              const cmCustomCommandLines* commandLines,
-                              std::vector<std::string> depends,
-                              const char* workingDir, bool uses_terminal);
+
+  struct GlobalTargetInfo
+  {
+    std::string Name;
+    std::string Message;
+    cmCustomCommandLines CommandLines;
+    std::vector<std::string> Depends;
+    std::string WorkingDir;
+    bool UsesTerminal;
+    GlobalTargetInfo()
+      : UsesTerminal(false)
+    {
+    }
+  };
+
+  void CreateDefaultGlobalTargets(std::vector<GlobalTargetInfo>& targets);
+
+  void AddGlobalTarget_Package(std::vector<GlobalTargetInfo>& targets);
+  void AddGlobalTarget_PackageSource(std::vector<GlobalTargetInfo>& targets);
+  void AddGlobalTarget_Test(std::vector<GlobalTargetInfo>& targets);
+  void AddGlobalTarget_EditCache(std::vector<GlobalTargetInfo>& targets);
+  void AddGlobalTarget_RebuildCache(std::vector<GlobalTargetInfo>& targets);
+  void AddGlobalTarget_Install(std::vector<GlobalTargetInfo>& targets);
+  cmTarget CreateGlobalTarget(GlobalTargetInfo const& gti, cmMakefile* mf);
 
   std::string FindMakeProgramFile;
   std::string ConfiguredFilesPath;
@@ -433,17 +452,20 @@ protected:
 
 private:
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
   typedef std::unordered_map<std::string, cmTarget*> TargetMap;
   typedef std::unordered_map<std::string, cmGeneratorTarget*>
     GeneratorTargetMap;
+  typedef std::unordered_map<std::string, cmMakefile*> MakefileMap;
 #else
   typedef cmsys::hash_map<std::string, cmTarget*> TargetMap;
   typedef cmsys::hash_map<std::string, cmGeneratorTarget*> GeneratorTargetMap;
+  typedef cmsys::hash_map<std::string, cmMakefile*> MakefileMap;
 #endif
 #else
   typedef std::map<std::string, cmTarget*> TargetMap;
   typedef std::map<std::string, cmGeneratorTarget*> GeneratorTargetMap;
+  typedef std::map<std::string, cmMakefile*> MakefileMap;
 #endif
   // Map efficiently from target name to cmTarget instance.
   // Do not use this structure for looping over all targets.
@@ -451,6 +473,11 @@ private:
   TargetMap TargetSearchIndex;
   GeneratorTargetMap GeneratorTargetSearchIndex;
 
+  // Map efficiently from source directory path to cmMakefile instance.
+  // Do not use this structure for looping over all directories.
+  // It may not contain all of them (see note in IndexMakefile method).
+  MakefileMap MakefileSearchIndex;
+
   cmMakefile* TryCompileOuterMakefile;
   // If you add a new map here, make sure it is copied
   // in EnableLanguagesFromGenerator
@@ -503,7 +530,9 @@ private:
 
   void ClearGeneratorMembers();
 
-  virtual const char* GetBuildIgnoreErrorsFlag() const { return 0; }
+  void IndexMakefile(cmMakefile* mf);
+
+  virtual const char* GetBuildIgnoreErrorsFlag() const { return CM_NULLPTR; }
 
   // Cache directory content and target files to be built.
   struct DirectoryContent
diff --git a/Source/cmGlobalGeneratorFactory.h b/Source/cmGlobalGeneratorFactory.h
index 640497a..528e118 100644
--- a/Source/cmGlobalGeneratorFactory.h
+++ b/Source/cmGlobalGeneratorFactory.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalGeneratorFactory_h
 #define cmGlobalGeneratorFactory_h
 
+#include <cmConfigure.h>
+
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmake;
@@ -41,6 +35,9 @@ public:
 
   /** Determine whether or not this generator supports toolsets */
   virtual bool SupportsToolset() const = 0;
+
+  /** Determine whether or not this generator supports platforms */
+  virtual bool SupportsPlatform() const = 0;
 };
 
 template <class T>
@@ -48,28 +45,32 @@ class cmGlobalGeneratorSimpleFactory : public cmGlobalGeneratorFactory
 {
 public:
   /** Create a GlobalGenerator */
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
-    if (name != T::GetActualName())
-      return 0;
+    if (name != T::GetActualName()) {
+      return CM_NULLPTR;
+    }
     return new T(cm);
   }
 
   /** Get the documentation entry for this factory */
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     T::GetDocumentation(entry);
   }
 
   /** Get the names of the current registered generators */
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(T::GetActualName());
   }
 
   /** Determine whether or not this generator supports toolsets */
-  virtual bool SupportsToolset() const { return T::SupportsToolset(); }
+  bool SupportsToolset() const CM_OVERRIDE { return T::SupportsToolset(); }
+
+  /** Determine whether or not this generator supports platforms */
+  bool SupportsPlatform() const CM_OVERRIDE { return T::SupportsPlatform(); }
 };
 
 #endif
diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx
index 0ae913e..0eac338 100644
--- a/Source/cmGlobalGhsMultiGenerator.cxx
+++ b/Source/cmGlobalGhsMultiGenerator.cxx
@@ -1,17 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalGhsMultiGenerator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGhsMultiTargetGenerator.h"
 #include "cmLocalGhsMultiGenerator.h"
 #include "cmMakefile.h"
diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h
index 473d153..27a40ba 100644
--- a/Source/cmGlobalGhsMultiGenerator.h
+++ b/Source/cmGlobalGhsMultiGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGhsMultiGenerator_h
 #define cmGhsMultiGenerator_h
 
@@ -52,6 +43,12 @@ public:
   static bool SupportsToolset() { return false; }
 
   /**
+   * Utilized by the generator factory to determine if this generator
+   * supports platforms.
+   */
+  static bool SupportsPlatform() { return false; }
+
+  /**
   * Try to determine system information such as shared library
   * extension, pthreads, byte order etc.
   */
diff --git a/Source/cmGlobalJOMMakefileGenerator.cxx b/Source/cmGlobalJOMMakefileGenerator.cxx
index 0bdd624..a846773 100644
--- a/Source/cmGlobalJOMMakefileGenerator.cxx
+++ b/Source/cmGlobalJOMMakefileGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalJOMMakefileGenerator.h"
 
 #include "cmLocalUnixMakefileGenerator3.h"
diff --git a/Source/cmGlobalJOMMakefileGenerator.h b/Source/cmGlobalJOMMakefileGenerator.h
index bb2273a..2e8ee29 100644
--- a/Source/cmGlobalJOMMakefileGenerator.h
+++ b/Source/cmGlobalJOMMakefileGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalJOMMakefileGenerator_h
 #define cmGlobalJOMMakefileGenerator_h
 
diff --git a/Source/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx
index 5c1e733..57d9aca 100644
--- a/Source/cmGlobalKdevelopGenerator.cxx
+++ b/Source/cmGlobalKdevelopGenerator.cxx
@@ -1,44 +1,48 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalKdevelopGenerator.h"
 
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
 #include <cmsys/Directory.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/SystemTools.hxx>
+#include <map>
+#include <set>
+#include <string.h>
+#include <utility>
 
-void cmGlobalKdevelopGenerator::GetDocumentation(cmDocumentationEntry& entry,
-                                                 const std::string&) const
+cmGlobalKdevelopGenerator::cmGlobalKdevelopGenerator()
+  : cmExternalMakefileProjectGenerator()
 {
-  entry.Name = this->GetName();
-  entry.Brief = "Generates KDevelop 3 project files.";
 }
 
-cmGlobalKdevelopGenerator::cmGlobalKdevelopGenerator()
-  : cmExternalMakefileProjectGenerator()
+cmExternalMakefileProjectGeneratorFactory*
+cmGlobalKdevelopGenerator::GetFactory()
 {
-  this->SupportedGlobalGenerators.push_back("Unix Makefiles");
+  static cmExternalMakefileProjectGeneratorSimpleFactory<
+    cmGlobalKdevelopGenerator>
+    factory("KDevelop3", "Generates KDevelop 3 project files.");
+
+  if (factory.GetSupportedGlobalGenerators().empty()) {
+    factory.AddSupportedGlobalGenerator("Unix Makefiles");
 #ifdef CMAKE_USE_NINJA
-  this->SupportedGlobalGenerators.push_back("Ninja");
+    factory.AddSupportedGlobalGenerator("Ninja");
 #endif
+
+    factory.Aliases.push_back("KDevelop3");
+  }
+
+  return &factory;
 }
 
 void cmGlobalKdevelopGenerator::Generate()
@@ -111,13 +115,13 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
       // make sure the file is part of this source tree
       if ((tmp[0] != '/') &&
           (strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
-           0)) {
+           CM_NULLPTR)) {
         files.insert(tmp);
         tmp = cmSystemTools::GetFilenameName(tmp);
         // add all files which dont match the default
         // */CMakeLists.txt;*cmake; to the file pattern
         if ((tmp != "CMakeLists.txt") &&
-            (strstr(tmp.c_str(), ".cmake") == 0)) {
+            (strstr(tmp.c_str(), ".cmake") == CM_NULLPTR)) {
           cmakeFilePattern += tmp + ";";
         }
       }
@@ -142,7 +146,7 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
 
         if ((tmp[0] != '/') &&
             (strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
-             0) &&
+             CM_NULLPTR) &&
             (cmSystemTools::GetFilenameExtension(tmp) != ".moc")) {
           files.insert(tmp);
 
@@ -166,7 +170,7 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
         cmSystemTools::ReplaceString(tmp, projectDir.c_str(), "");
         if ((tmp[0] != '/') &&
             (strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
-             0)) {
+             CM_NULLPTR)) {
           files.insert(tmp);
         }
       }
@@ -213,7 +217,7 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
     cmSystemTools::ReplaceString(tmp, projectDir.c_str(), "");
     // only put relative paths
     if (!tmp.empty() && tmp[0] != '/') {
-      fout << tmp.c_str() << "\n";
+      fout << tmp << "\n";
     }
   }
   return true;
@@ -296,12 +300,12 @@ void cmGlobalKdevelopGenerator::MergeProjectFiles(
        it != lines.end(); it++) {
     const char* line = (*it).c_str();
     // skip these tags as they are always replaced
-    if ((strstr(line, "<projectdirectory>") != 0) ||
-        (strstr(line, "<projectmanagement>") != 0) ||
-        (strstr(line, "<absoluteprojectpath>") != 0) ||
-        (strstr(line, "<filelistdirectory>") != 0) ||
-        (strstr(line, "<buildtool>") != 0) ||
-        (strstr(line, "<builddir>") != 0)) {
+    if ((strstr(line, "<projectdirectory>") != CM_NULLPTR) ||
+        (strstr(line, "<projectmanagement>") != CM_NULLPTR) ||
+        (strstr(line, "<absoluteprojectpath>") != CM_NULLPTR) ||
+        (strstr(line, "<filelistdirectory>") != CM_NULLPTR) ||
+        (strstr(line, "<buildtool>") != CM_NULLPTR) ||
+        (strstr(line, "<builddir>") != CM_NULLPTR)) {
       continue;
     }
 
diff --git a/Source/cmGlobalKdevelopGenerator.h b/Source/cmGlobalKdevelopGenerator.h
index 315e38e..8121fa8 100644
--- a/Source/cmGlobalKdevelopGenerator.h
+++ b/Source/cmGlobalKdevelopGenerator.h
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2009 Kitware, Inc.
-  Copyright 2004 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalKdevelopGenerator_h
 #define cmGlobalKdevelopGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmExternalMakefileProjectGenerator.h"
 
+#include <string>
+#include <vector>
+
 class cmLocalGenerator;
 
 /** \class cmGlobalKdevelopGenerator
@@ -33,20 +28,9 @@ class cmGlobalKdevelopGenerator : public cmExternalMakefileProjectGenerator
 public:
   cmGlobalKdevelopGenerator();
 
-  virtual std::string GetName() const
-  {
-    return cmGlobalKdevelopGenerator::GetActualName();
-  }
-  static std::string GetActualName() { return "KDevelop3"; }
-  static cmExternalMakefileProjectGenerator* New()
-  {
-    return new cmGlobalKdevelopGenerator;
-  }
-  /** Get the documentation entry for this generator.  */
-  virtual void GetDocumentation(cmDocumentationEntry& entry,
-                                const std::string& fullName) const;
+  static cmExternalMakefileProjectGeneratorFactory* GetFactory();
 
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
 private:
   /*** Create the foo.kdevelop.filelist file, return false if it doesn't
diff --git a/Source/cmGlobalMSYSMakefileGenerator.cxx b/Source/cmGlobalMSYSMakefileGenerator.cxx
index 6bf178a..6d314d6 100644
--- a/Source/cmGlobalMSYSMakefileGenerator.cxx
+++ b/Source/cmGlobalMSYSMakefileGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalMSYSMakefileGenerator.h"
 
 #include "cmLocalUnixMakefileGenerator3.h"
diff --git a/Source/cmGlobalMSYSMakefileGenerator.h b/Source/cmGlobalMSYSMakefileGenerator.h
index d687d19..23dbc5e 100644
--- a/Source/cmGlobalMSYSMakefileGenerator.h
+++ b/Source/cmGlobalMSYSMakefileGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalMSYSMakefileGenerator_h
 #define cmGlobalMSYSMakefileGenerator_h
 
diff --git a/Source/cmGlobalMinGWMakefileGenerator.cxx b/Source/cmGlobalMinGWMakefileGenerator.cxx
index 05f1b36..d5decfb 100644
--- a/Source/cmGlobalMinGWMakefileGenerator.cxx
+++ b/Source/cmGlobalMinGWMakefileGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalMinGWMakefileGenerator.h"
 
 #include "cmLocalUnixMakefileGenerator3.h"
diff --git a/Source/cmGlobalMinGWMakefileGenerator.h b/Source/cmGlobalMinGWMakefileGenerator.h
index 90cfde7..a994c92 100644
--- a/Source/cmGlobalMinGWMakefileGenerator.h
+++ b/Source/cmGlobalMinGWMakefileGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalMinGWMakefileGenerator_h
 #define cmGlobalMinGWMakefileGenerator_h
 
diff --git a/Source/cmGlobalNMakeMakefileGenerator.cxx b/Source/cmGlobalNMakeMakefileGenerator.cxx
index 605a773..48798fb 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.cxx
+++ b/Source/cmGlobalNMakeMakefileGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalNMakeMakefileGenerator.h"
 
 #include "cmLocalUnixMakefileGenerator3.h"
diff --git a/Source/cmGlobalNMakeMakefileGenerator.h b/Source/cmGlobalNMakeMakefileGenerator.h
index 3ab684e..f169e76 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.h
+++ b/Source/cmGlobalNMakeMakefileGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalNMakeMakefileGenerator_h
 #define cmGlobalNMakeMakefileGenerator_h
 
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index 143ad92..f5a0e68 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -1,28 +1,34 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalNinjaGenerator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
+#include "cmFortranParser.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorExpressionEvaluationFile.h"
 #include "cmGeneratorTarget.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetDepend.h"
 #include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
+#include "cm_jsoncpp_reader.h"
+#include "cm_jsoncpp_writer.h"
 
 #include <algorithm>
-#include <assert.h>
 #include <ctype.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
 
 const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
 const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
@@ -30,8 +36,9 @@ const char* cmGlobalNinjaGenerator::INDENT = "  ";
 
 void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
 {
-  for (int i = 0; i < count; ++i)
+  for (int i = 0; i < count; ++i) {
     os << cmGlobalNinjaGenerator::INDENT;
+  }
 }
 
 void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
@@ -43,8 +50,9 @@ void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
 void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
                                           const std::string& comment)
 {
-  if (comment.empty())
+  if (comment.empty()) {
     return;
+  }
 
   std::string::size_type lpos = 0;
   std::string::size_type rpos;
@@ -91,12 +99,11 @@ std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string& ident,
     names << "ident" << VarNum++;
     vars << names.str() << " = " << ident << "\n";
     return "$" + names.str();
-  } else {
-    std::string result = ident;
-    cmSystemTools::ReplaceString(result, " ", "$ ");
-    cmSystemTools::ReplaceString(result, ":", "$:");
-    return result;
   }
+  std::string result = ident;
+  cmSystemTools::ReplaceString(result, " ", "$ ");
+  cmSystemTools::ReplaceString(result, ":", "$:");
+  return result;
 }
 
 std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
@@ -128,10 +135,10 @@ std::string cmGlobalNinjaGenerator::EncodeDepfileSpace(const std::string& path)
 
 void cmGlobalNinjaGenerator::WriteBuild(
   std::ostream& os, const std::string& comment, const std::string& rule,
-  const cmNinjaDeps& outputs, const cmNinjaDeps& explicitDeps,
-  const cmNinjaDeps& implicitDeps, const cmNinjaDeps& orderOnlyDeps,
-  const cmNinjaVars& variables, const std::string& rspfile, int cmdLineLimit,
-  bool* usedResponseFile)
+  const cmNinjaDeps& outputs, const cmNinjaDeps& implicitOuts,
+  const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps,
+  const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables,
+  const std::string& rspfile, int cmdLineLimit, bool* usedResponseFile)
 {
   // Make sure there is a rule.
   if (rule.empty()) {
@@ -165,16 +172,18 @@ void cmGlobalNinjaGenerator::WriteBuild(
   if (!implicitDeps.empty()) {
     arguments += " |";
     for (cmNinjaDeps::const_iterator i = implicitDeps.begin();
-         i != implicitDeps.end(); ++i)
+         i != implicitDeps.end(); ++i) {
       arguments += " " + EncodeIdent(EncodePath(*i), os);
+    }
   }
 
   // Write order-only dependencies.
   if (!orderOnlyDeps.empty()) {
     arguments += " ||";
     for (cmNinjaDeps::const_iterator i = orderOnlyDeps.begin();
-         i != orderOnlyDeps.end(); ++i)
+         i != orderOnlyDeps.end(); ++i) {
       arguments += " " + EncodeIdent(EncodePath(*i), os);
+    }
   }
 
   arguments += "\n";
@@ -190,6 +199,13 @@ void cmGlobalNinjaGenerator::WriteBuild(
       this->CombinedBuildOutputs.insert(EncodePath(*i));
     }
   }
+  if (!implicitOuts.empty()) {
+    build += " |";
+    for (cmNinjaDeps::const_iterator i = implicitOuts.begin();
+         i != implicitOuts.end(); ++i) {
+      build += " " + EncodeIdent(EncodePath(*i), os);
+    }
+  }
   build += ":";
 
   // Write the rule.
@@ -198,9 +214,10 @@ void cmGlobalNinjaGenerator::WriteBuild(
   // Write the variables bound to this build statement.
   std::ostringstream variable_assignments;
   for (cmNinjaVars::const_iterator i = variables.begin(); i != variables.end();
-       ++i)
+       ++i) {
     cmGlobalNinjaGenerator::WriteVariable(variable_assignments, i->first,
                                           i->second, "", 1);
+  }
 
   // check if a response file rule should be used
   std::string buildstr = build;
@@ -229,7 +246,8 @@ void cmGlobalNinjaGenerator::WritePhonyBuild(
   const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps,
   const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables)
 {
-  this->WriteBuild(os, comment, "phony", outputs, explicitDeps, implicitDeps,
+  this->WriteBuild(os, comment, "phony", outputs,
+                   /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps,
                    orderOnlyDeps, variables);
 }
 
@@ -247,8 +265,8 @@ void cmGlobalNinjaGenerator::AddCustomCommandRule()
 
 void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
   const std::string& command, const std::string& description,
-  const std::string& comment, bool uses_terminal, bool restat,
-  const cmNinjaDeps& outputs, const cmNinjaDeps& deps,
+  const std::string& comment, const std::string& depfile, bool uses_terminal,
+  bool restat, const cmNinjaDeps& outputs, const cmNinjaDeps& deps,
   const cmNinjaDeps& orderOnly)
 {
   std::string cmd = command;
@@ -269,9 +287,12 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
   if (uses_terminal && SupportsConsolePool()) {
     vars["pool"] = "console";
   }
-
+  if (!depfile.empty()) {
+    vars["depfile"] = depfile;
+  }
   this->WriteBuild(*this->BuildFileStream, comment, "CUSTOM_COMMAND", outputs,
-                   deps, cmNinjaDeps(), orderOnly, vars);
+                   /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(),
+                   orderOnly, vars);
 
   if (this->ComputingUnknownDependencies) {
     // we need to track every dependency that comes in, since we are trying
@@ -313,7 +334,8 @@ void cmGlobalNinjaGenerator::WriteMacOSXContentBuild(const std::string& input,
   cmNinjaVars vars;
 
   this->WriteBuild(*this->BuildFileStream, "", "COPY_OSX_CONTENT", outputs,
-                   deps, cmNinjaDeps(), cmNinjaDeps(), cmNinjaVars());
+                   /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(),
+                   cmNinjaDeps(), cmNinjaVars());
 }
 
 void cmGlobalNinjaGenerator::WriteRule(
@@ -430,21 +452,25 @@ void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
   cmGlobalNinjaGenerator::WriteComment(os, comment);
   os << "default";
   for (cmNinjaDeps::const_iterator i = targets.begin(); i != targets.end();
-       ++i)
+       ++i) {
     os << " " << *i;
+  }
   os << "\n";
 }
 
 cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
   : cmGlobalCommonGenerator(cm)
-  , BuildFileStream(0)
-  , RulesFileStream(0)
-  , CompileCommandsStream(0)
+  , BuildFileStream(CM_NULLPTR)
+  , RulesFileStream(CM_NULLPTR)
+  , CompileCommandsStream(CM_NULLPTR)
   , Rules()
   , AllDependencies()
   , UsingGCCOnWindows(false)
   , ComputingUnknownDependencies(false)
   , PolicyCMP0058(cmPolicies::WARN)
+  , NinjaSupportsConsolePool(false)
+  , NinjaSupportsImplicitOuts(false)
+  , NinjaSupportsDyndeps(0)
 {
 #ifdef _WIN32
   cm->GetState()->SetWindowsShell(true);
@@ -487,6 +513,8 @@ void cmGlobalNinjaGenerator::Generate()
   this->OpenBuildFileStream();
   this->OpenRulesFileStream();
 
+  this->TargetDependsClosures.clear();
+
   this->InitOutputPathPrefix();
   this->TargetAll = this->NinjaOutputPath("all");
   this->CMakeCacheFile = this->NinjaOutputPath("CMakeCache.txt");
@@ -507,8 +535,8 @@ void cmGlobalNinjaGenerator::Generate()
   this->WriteBuiltinTargets(*this->BuildFileStream);
 
   if (cmSystemTools::GetErrorOccuredFlag()) {
-    this->RulesFileStream->setstate(std::ios_base::failbit);
-    this->BuildFileStream->setstate(std::ios_base::failbit);
+    this->RulesFileStream->setstate(std::ios::failbit);
+    this->BuildFileStream->setstate(std::ios::failbit);
   }
 
   this->CloseCompileCommandsStream();
@@ -525,18 +553,84 @@ void cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
     command.push_back(this->NinjaCommand);
     command.push_back("--version");
     std::string version;
-    cmSystemTools::RunSingleCommand(command, &version, 0, 0, 0,
-                                    cmSystemTools::OUTPUT_NONE);
+    cmSystemTools::RunSingleCommand(command, &version, CM_NULLPTR, CM_NULLPTR,
+                                    CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
     this->NinjaVersion = cmSystemTools::TrimWhitespace(version);
+    this->CheckNinjaFeatures();
   }
 }
 
+void cmGlobalNinjaGenerator::CheckNinjaFeatures()
+{
+  this->NinjaSupportsConsolePool = !cmSystemTools::VersionCompare(
+    cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
+    RequiredNinjaVersionForConsolePool().c_str());
+  this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare(
+    cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
+    this->RequiredNinjaVersionForImplicitOuts().c_str());
+  {
+    // Our ninja branch adds ".dyndep-#" to its version number,
+    // where '#' is a feature-specific version number.  Extract it.
+    static std::string const k_DYNDEP_ = ".dyndep-";
+    std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
+    if (pos != std::string::npos) {
+      const char* fv = this->NinjaVersion.c_str() + pos + k_DYNDEP_.size();
+      cmSystemTools::StringToULong(fv, &this->NinjaSupportsDyndeps);
+    }
+  }
+}
+
+bool cmGlobalNinjaGenerator::CheckLanguages(
+  std::vector<std::string> const& languages, cmMakefile* mf) const
+{
+  if (std::find(languages.begin(), languages.end(), "Fortran") !=
+      languages.end()) {
+    return this->CheckFortran(mf);
+  }
+  return true;
+}
+
+bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
+{
+  if (this->NinjaSupportsDyndeps == 1) {
+    return true;
+  }
+
+  std::ostringstream e;
+  if (this->NinjaSupportsDyndeps == 0) {
+    /* clang-format off */
+    e <<
+      "The Ninja generator does not support Fortran using Ninja version\n"
+      "  " + this->NinjaVersion + "\n"
+      "due to lack of required features.  "
+      "Kitware has implemented the required features but as of this version "
+      "of CMake they have not been integrated to upstream ninja.  "
+      "Pending integration, Kitware maintains a branch at:\n"
+      "  https://github.com/Kitware/ninja/tree/features-for-fortran#readme\n"
+      "with the required features.  "
+      "One may build ninja from that branch to get support for Fortran."
+      ;
+    /* clang-format on */
+  } else {
+    /* clang-format off */
+    e <<
+      "The Ninja generator in this version of CMake does not support Fortran "
+      "using Ninja version\n"
+      "  " + this->NinjaVersion + "\n"
+      "because its 'dyndep' feature version is " <<
+      this->NinjaSupportsDyndeps << ".  "
+      "This version of CMake is aware only of 'dyndep' feature version 1."
+      ;
+    /* clang-format on */
+  }
+  mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+  cmSystemTools::SetFatalErrorOccured();
+  return false;
+}
+
 void cmGlobalNinjaGenerator::EnableLanguage(
   std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
 {
-  if (std::find(langs.begin(), langs.end(), "Fortran") != langs.end()) {
-    cmSystemTools::Error("The Ninja generator does not support Fortran yet.");
-  }
   this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
   for (std::vector<std::string>::const_iterator l = langs.begin();
        l != langs.end(); ++l) {
@@ -546,11 +640,13 @@ void cmGlobalNinjaGenerator::EnableLanguage(
     this->ResolveLanguageCompiler(*l, mf, optional);
   }
 #ifdef _WIN32
-  if (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
-      strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "GNU") == 0 ||
-      strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "GNU") == 0 ||
-      strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "GNU") == 0 ||
-      strcmp(mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID"), "GNU") == 0) {
+  if (strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") != 0 &&
+      strcmp(mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID"), "MSVC") != 0 &&
+      (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
+       strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "GNU") == 0 ||
+       strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "GNU") == 0 ||
+       strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "Clang") == 0 ||
+       strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "Clang") == 0)) {
     this->UsingGCCOnWindows = true;
   }
 #endif
@@ -670,7 +766,7 @@ void cmGlobalNinjaGenerator::CloseBuildFileStream()
 {
   if (this->BuildFileStream) {
     delete this->BuildFileStream;
-    this->BuildFileStream = 0;
+    this->BuildFileStream = CM_NULLPTR;
   } else {
     cmSystemTools::Error("Build file stream was not open.");
   }
@@ -711,7 +807,7 @@ void cmGlobalNinjaGenerator::CloseRulesFileStream()
 {
   if (this->RulesFileStream) {
     delete this->RulesFileStream;
-    this->RulesFileStream = 0;
+    this->RulesFileStream = CM_NULLPTR;
   } else {
     cmSystemTools::Error("Rules file stream was not open.");
   }
@@ -738,7 +834,8 @@ std::string cmGlobalNinjaGenerator::ConvertToNinjaPath(const std::string& path)
 {
   cmLocalNinjaGenerator* ng =
     static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
-  std::string convPath = ng->Convert(path, cmOutputConverter::HOME_OUTPUT);
+  std::string convPath = ng->ConvertToRelativePath(
+    this->LocalGenerators[0]->GetState()->GetBinaryDirectory(), path);
   convPath = this->NinjaOutputPath(convPath);
 #ifdef _WIN32
   std::replace(convPath.begin(), convPath.end(), '/', '\\');
@@ -751,7 +848,8 @@ std::string cmGlobalNinjaGenerator::ConvertToNinjaFolderRule(
 {
   cmLocalNinjaGenerator* ng =
     static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
-  std::string convPath = ng->Convert(path + "/all", cmOutputConverter::HOME);
+  std::string convPath = ng->ConvertToRelativePath(
+    this->LocalGenerators[0]->GetState()->GetSourceDirectory(), path + "/all");
   convPath = this->NinjaOutputPath(convPath);
 #ifdef _WIN32
   std::replace(convPath.begin(), convPath.end(), '/', '\\');
@@ -799,7 +897,7 @@ void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
   if (this->CompileCommandsStream) {
     *this->CompileCommandsStream << "\n]";
     delete this->CompileCommandsStream;
-    this->CompileCommandsStream = 0;
+    this->CompileCommandsStream = CM_NULLPTR;
   }
 }
 
@@ -830,7 +928,7 @@ void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
     std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps));
     WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
                             "Assume dependencies for generated source file.",
-                            /*uses_terminal*/ false,
+                            /*depfile*/ "", /*uses_terminal*/ false,
                             /*restat*/ true, cmNinjaDeps(1, i->first), deps);
   }
 }
@@ -857,6 +955,7 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs(
       break;
     }
     case cmState::OBJECT_LIBRARY:
+    case cmState::GLOBAL_TARGET:
     case cmState::UTILITY: {
       std::string path =
         target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
@@ -865,12 +964,6 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs(
       break;
     }
 
-    case cmState::GLOBAL_TARGET:
-      // Always use the target in HOME instead of an unused duplicate in a
-      // subdirectory.
-      outputs.push_back(this->NinjaOutputPath(target->GetName()));
-      break;
-
     default:
       return;
   }
@@ -880,10 +973,15 @@ void cmGlobalNinjaGenerator::AppendTargetDepends(
   cmGeneratorTarget const* target, cmNinjaDeps& outputs)
 {
   if (target->GetType() == cmState::GLOBAL_TARGET) {
-    // Global targets only depend on other utilities, which may not appear in
-    // the TargetDepends set (e.g. "all").
+    // These depend only on other CMake-provided targets, e.g. "all".
     std::set<std::string> const& utils = target->GetUtilities();
-    std::copy(utils.begin(), utils.end(), std::back_inserter(outputs));
+    for (std::set<std::string>::const_iterator i = utils.begin();
+         i != utils.end(); ++i) {
+      std::string d =
+        target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
+        std::string("/") + *i;
+      outputs.push_back(this->ConvertToNinjaPath(d));
+    }
   } else {
     cmNinjaDeps outs;
     cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
@@ -899,6 +997,42 @@ void cmGlobalNinjaGenerator::AppendTargetDepends(
   }
 }
 
+void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
+  cmGeneratorTarget const* target, cmNinjaDeps& outputs)
+{
+  TargetDependsClosureMap::iterator i =
+    this->TargetDependsClosures.find(target);
+  if (i == this->TargetDependsClosures.end()) {
+    TargetDependsClosureMap::value_type e(
+      target, std::set<cmGeneratorTarget const*>());
+    i = this->TargetDependsClosures.insert(e).first;
+    this->ComputeTargetDependsClosure(target, i->second);
+  }
+  std::set<cmGeneratorTarget const*> const& targets = i->second;
+  cmNinjaDeps outs;
+  for (std::set<cmGeneratorTarget const*>::const_iterator ti = targets.begin();
+       ti != targets.end(); ++ti) {
+    this->AppendTargetOutputs(*ti, outs);
+  }
+  std::sort(outs.begin(), outs.end());
+  outputs.insert(outputs.end(), outs.begin(), outs.end());
+}
+
+void cmGlobalNinjaGenerator::ComputeTargetDependsClosure(
+  cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& depends)
+{
+  cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
+  for (cmTargetDependSet::const_iterator i = targetDeps.begin();
+       i != targetDeps.end(); ++i) {
+    if ((*i)->GetType() == cmState::INTERFACE_LIBRARY) {
+      continue;
+    }
+    if (depends.insert(*i).second) {
+      this->ComputeTargetDependsClosure(*i, depends);
+    }
+  }
+}
+
 void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
                                             cmGeneratorTarget* target)
 {
@@ -907,15 +1041,17 @@ void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
   this->AppendTargetOutputs(target, outputs);
   // Mark the target's outputs as ambiguous to ensure that no other target uses
   // the output as an alias.
-  for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i)
-    TargetAliases[*i] = 0;
+  for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i) {
+    TargetAliases[*i] = CM_NULLPTR;
+  }
 
   // Insert the alias into the map.  If the alias was already present in the
   // map and referred to another target, mark it as ambiguous.
   std::pair<TargetAliasMap::iterator, bool> newAlias =
     TargetAliases.insert(std::make_pair(buildAlias, target));
-  if (newAlias.second && newAlias.first->second != target)
-    newAlias.first->second = 0;
+  if (newAlias.second && newAlias.first->second != target) {
+    newAlias.first->second = CM_NULLPTR;
+  }
 }
 
 void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
@@ -926,8 +1062,9 @@ void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
   for (TargetAliasMap::const_iterator i = TargetAliases.begin();
        i != TargetAliases.end(); ++i) {
     // Don't write ambiguous aliases.
-    if (!i->second)
+    if (!i->second) {
       continue;
+    }
 
     cmNinjaDeps deps;
     this->AppendTargetOutputs(i->second, deps);
@@ -1208,6 +1345,7 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
   this->WriteBuild(os, "Re-run CMake if any of its inputs changed.",
                    "RERUN_CMAKE",
                    /*outputs=*/cmNinjaDeps(1, ninjaBuildFile),
+                   /*implicitOuts=*/cmNinjaDeps(),
                    /*explicitDeps=*/cmNinjaDeps(), implicitDeps,
                    /*orderOnlyDeps=*/cmNinjaDeps(), variables);
 
@@ -1227,9 +1365,12 @@ std::string cmGlobalNinjaGenerator::ninjaCmd() const
 
 bool cmGlobalNinjaGenerator::SupportsConsolePool() const
 {
-  return cmSystemTools::VersionCompare(
-           cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
-           RequiredNinjaVersionForConsolePool().c_str()) == false;
+  return this->NinjaSupportsConsolePool;
+}
+
+bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
+{
+  return this->NinjaSupportsImplicitOuts;
 }
 
 void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
@@ -1245,6 +1386,7 @@ void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
             /*generator=*/false);
   WriteBuild(os, "Clean all the built files.", "CLEAN",
              /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("clean")),
+             /*implicitOuts=*/cmNinjaDeps(),
              /*explicitDeps=*/cmNinjaDeps(),
              /*implicitDeps=*/cmNinjaDeps(),
              /*orderOnlyDeps=*/cmNinjaDeps(),
@@ -1264,6 +1406,7 @@ void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
             /*generator=*/false);
   WriteBuild(os, "Print all primary targets available.", "HELP",
              /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("help")),
+             /*implicitOuts=*/cmNinjaDeps(),
              /*explicitDeps=*/cmNinjaDeps(),
              /*implicitDeps=*/cmNinjaDeps(),
              /*orderOnlyDeps=*/cmNinjaDeps(),
@@ -1295,3 +1438,421 @@ void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
   EnsureTrailingSlash(path);
   cmStripSuffixIfExists(path, this->OutputPathPrefix);
 }
+
+/*
+
+We use the following approach to support Fortran.  Each target already
+has a <target>.dir/ directory used to hold intermediate files for CMake.
+For each target, a FortranDependInfo.json file is generated by CMake with
+information about include directories, module directories, and the locations
+the per-target directories for target dependencies.
+
+Compilation of source files within a target is split into the following steps:
+
+1. Preprocess all sources, scan preprocessed output for module dependencies.
+   This step is done with independent build statements for each source,
+   and can therefore be done in parallel.
+
+    rule Fortran_PREPROCESS
+      depfile = $DEP_FILE
+      command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
+                cmake -E cmake_ninja_depends \
+                  --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \
+                  --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE
+
+    build src.f90-pp.f90 | src.f90-pp.f90.ddi: Fortran_PREPROCESS src.f90
+      OBJ_FILE = src.f90.o
+      DEP_FILE = src.f90-pp.f90.d
+      DYNDEP_INTERMEDIATE_FILE = src.f90-pp.f90.ddi
+
+   The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
+   and generates the ninja depfile for preprocessor dependencies.  It also
+   generates a "ddi" file (in a format private to CMake) that lists the
+   object file that compilation will produce along with the module names
+   it provides and/or requires.  The "ddi" file is an implicit output
+   because it should not appear in "$out" but is generated by the rule.
+
+2. Consolidate the per-source module dependencies saved in the "ddi"
+   files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
+
+    rule Fortran_DYNDEP
+      command = cmake -E cmake_ninja_dyndep \
+                  --tdi=FortranDependInfo.json --dd=$out $in
+
+    build Fortran.dd: Fortran_DYNDEP src1.f90-pp.f90.ddi src2.f90-pp.f90.ddi
+
+   The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
+   sources in the target and the ``FortranModules.json`` files from targets
+   on which the target depends.  It computes dependency edges on compilations
+   that require modules to those that provide the modules.  This information
+   is placed in the ``Fortran.dd`` file for ninja to load later.  It also
+   writes the expected location of modules provided by this target into
+   ``FortranModules.json`` for use by dependent targets.
+
+3. Compile all sources after loading dynamically discovered dependencies
+   of the compilation build statements from their ``dyndep`` bindings.
+
+    rule Fortran_COMPILE
+      command = gfortran $INCLUDES $FLAGS -c $in -o $out
+
+    build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
+      dyndep = Fortran.dd
+
+   The "dyndep" binding tells ninja to load dynamically discovered
+   dependency information from ``Fortran.dd``.  This adds information
+   such as:
+
+    build src1.f90.o | mod1.mod: dyndep
+      restat = 1
+
+   This tells ninja that ``mod1.mod`` is an implicit output of compiling
+   the object file ``src1.f90.o``.  The ``restat`` binding tells it that
+   the timestamp of the output may not always change.  Additionally:
+
+    build src2.f90.o: dyndep | mod1.mod
+
+   This tells ninja that ``mod1.mod`` is a dependency of compiling the
+   object file ``src2.f90.o``.  This ensures that ``src1.f90.o`` and
+   ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
+   (because the latter consumes the module).
+*/
+
+int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
+                              std::vector<std::string>::const_iterator argEnd)
+{
+  std::string arg_tdi;
+  std::string arg_pp;
+  std::string arg_dep;
+  std::string arg_obj;
+  std::string arg_ddi;
+  for (std::vector<std::string>::const_iterator a = argBeg; a != argEnd; ++a) {
+    std::string const& arg = *a;
+    if (cmHasLiteralPrefix(arg, "--tdi=")) {
+      arg_tdi = arg.substr(6);
+    } else if (cmHasLiteralPrefix(arg, "--pp=")) {
+      arg_pp = arg.substr(5);
+    } else if (cmHasLiteralPrefix(arg, "--dep=")) {
+      arg_dep = arg.substr(6);
+    } else if (cmHasLiteralPrefix(arg, "--obj=")) {
+      arg_obj = arg.substr(6);
+    } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
+      arg_ddi = arg.substr(6);
+    } else {
+      cmSystemTools::Error("-E cmake_ninja_depends unknown argument: ",
+                           arg.c_str());
+      return 1;
+    }
+  }
+  if (arg_tdi.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
+    return 1;
+  }
+  if (arg_pp.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_depends requires value for --pp=");
+    return 1;
+  }
+  if (arg_dep.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
+    return 1;
+  }
+  if (arg_obj.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
+    return 1;
+  }
+  if (arg_ddi.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
+    return 1;
+  }
+
+  std::vector<std::string> includes;
+  {
+    Json::Value tdio;
+    Json::Value const& tdi = tdio;
+    {
+      cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
+      Json::Reader reader;
+      if (!reader.parse(tdif, tdio, false)) {
+        cmSystemTools::Error("-E cmake_ninja_depends failed to parse ",
+                             arg_tdi.c_str(),
+                             reader.getFormattedErrorMessages().c_str());
+        return 1;
+      }
+    }
+
+    Json::Value const& tdi_include_dirs = tdi["include-dirs"];
+    if (tdi_include_dirs.isArray()) {
+      for (Json::Value::const_iterator i = tdi_include_dirs.begin();
+           i != tdi_include_dirs.end(); ++i) {
+        includes.push_back(i->asString());
+      }
+    }
+  }
+
+  cmFortranSourceInfo info;
+  std::set<std::string> defines;
+  cmFortranParser parser(includes, defines, info);
+  if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) {
+    cmSystemTools::Error("-E cmake_ninja_depends failed to open ",
+                         arg_pp.c_str());
+    return 1;
+  }
+  if (cmFortran_yyparse(parser.Scanner) != 0) {
+    // Failed to parse the file.
+    return 1;
+  }
+
+  {
+    cmGeneratedFileStream depfile(arg_dep.c_str());
+    depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
+    for (std::set<std::string>::iterator i = info.Includes.begin();
+         i != info.Includes.end(); ++i) {
+      depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(*i);
+    }
+    depfile << "\n";
+  }
+
+  Json::Value ddi(Json::objectValue);
+  ddi["object"] = arg_obj;
+
+  Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue;
+  for (std::set<std::string>::iterator i = info.Provides.begin();
+       i != info.Provides.end(); ++i) {
+    ddi_provides.append(*i);
+  }
+  Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue;
+  for (std::set<std::string>::iterator i = info.Requires.begin();
+       i != info.Requires.end(); ++i) {
+    // Require modules not provided in the same source.
+    if (!info.Provides.count(*i)) {
+      ddi_requires.append(*i);
+    }
+  }
+
+  cmGeneratedFileStream ddif(arg_ddi.c_str());
+  ddif << ddi;
+  if (!ddif) {
+    cmSystemTools::Error("-E cmake_ninja_depends failed to write ",
+                         arg_ddi.c_str());
+    return 1;
+  }
+  return 0;
+}
+
+struct cmFortranObjectInfo
+{
+  std::string Object;
+  std::vector<std::string> Provides;
+  std::vector<std::string> Requires;
+};
+
+bool cmGlobalNinjaGenerator::WriteDyndepFile(
+  std::string const& dir_top_src, std::string const& dir_top_bld,
+  std::string const& dir_cur_src, std::string const& dir_cur_bld,
+  std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
+  std::string const& module_dir,
+  std::vector<std::string> const& linked_target_dirs)
+{
+  // Setup path conversions.
+  {
+    cmState::Snapshot snapshot =
+      this->GetCMakeInstance()->GetCurrentSnapshot();
+    snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
+    snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
+    snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
+    snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
+    CM_AUTO_PTR<cmMakefile> mfd(new cmMakefile(this, snapshot));
+    CM_AUTO_PTR<cmLocalNinjaGenerator> lgd(static_cast<cmLocalNinjaGenerator*>(
+      this->CreateLocalGenerator(mfd.get())));
+    this->Makefiles.push_back(mfd.release());
+    this->LocalGenerators.push_back(lgd.release());
+  }
+
+  std::vector<cmFortranObjectInfo> objects;
+  for (std::vector<std::string>::const_iterator ddii = arg_ddis.begin();
+       ddii != arg_ddis.end(); ++ddii) {
+    // Load the ddi file and compute the module file paths it provides.
+    Json::Value ddio;
+    Json::Value const& ddi = ddio;
+    cmsys::ifstream ddif(ddii->c_str(), std::ios::in | std::ios::binary);
+    Json::Reader reader;
+    if (!reader.parse(ddif, ddio, false)) {
+      cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
+                           ddii->c_str(),
+                           reader.getFormattedErrorMessages().c_str());
+      return false;
+    }
+
+    cmFortranObjectInfo info;
+    info.Object = ddi["object"].asString();
+    Json::Value const& ddi_provides = ddi["provides"];
+    if (ddi_provides.isArray()) {
+      for (Json::Value::const_iterator i = ddi_provides.begin();
+           i != ddi_provides.end(); ++i) {
+        info.Provides.push_back(i->asString());
+      }
+    }
+    Json::Value const& ddi_requires = ddi["requires"];
+    if (ddi_requires.isArray()) {
+      for (Json::Value::const_iterator i = ddi_requires.begin();
+           i != ddi_requires.end(); ++i) {
+        info.Requires.push_back(i->asString());
+      }
+    }
+    objects.push_back(info);
+  }
+
+  // Map from module name to module file path, if known.
+  std::map<std::string, std::string> mod_files;
+
+  // Populate the module map with those provided by linked targets first.
+  for (std::vector<std::string>::const_iterator di =
+         linked_target_dirs.begin();
+       di != linked_target_dirs.end(); ++di) {
+    std::string const ltmn = *di + "/FortranModules.json";
+    Json::Value ltm;
+    cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
+    Json::Reader reader;
+    if (ltmf && !reader.parse(ltmf, ltm, false)) {
+      cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
+                           di->c_str(),
+                           reader.getFormattedErrorMessages().c_str());
+      return false;
+    }
+    if (ltm.isObject()) {
+      for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) {
+        mod_files[i.key().asString()] = i->asString();
+      }
+    }
+  }
+
+  // Extend the module map with those provided by this target.
+  // We do this after loading the modules provided by linked targets
+  // in case we have one of the same name that must be preferred.
+  Json::Value tm = Json::objectValue;
+  for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin();
+       oi != objects.end(); ++oi) {
+    for (std::vector<std::string>::iterator i = oi->Provides.begin();
+         i != oi->Provides.end(); ++i) {
+      std::string const mod = module_dir + *i + ".mod";
+      mod_files[*i] = mod;
+      tm[*i] = mod;
+    }
+  }
+
+  cmGeneratedFileStream ddf(arg_dd.c_str());
+  ddf << "ninja_dyndep_version = 1.0\n";
+
+  for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin();
+       oi != objects.end(); ++oi) {
+    std::string const ddComment;
+    std::string const ddRule = "dyndep";
+    cmNinjaDeps ddOutputs;
+    cmNinjaDeps ddImplicitOuts;
+    cmNinjaDeps ddExplicitDeps;
+    cmNinjaDeps ddImplicitDeps;
+    cmNinjaDeps ddOrderOnlyDeps;
+    cmNinjaVars ddVars;
+
+    ddOutputs.push_back(oi->Object);
+    for (std::vector<std::string>::iterator i = oi->Provides.begin();
+         i != oi->Provides.end(); ++i) {
+      ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[*i]));
+    }
+    for (std::vector<std::string>::iterator i = oi->Requires.begin();
+         i != oi->Requires.end(); ++i) {
+      std::map<std::string, std::string>::iterator m = mod_files.find(*i);
+      if (m != mod_files.end()) {
+        ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second));
+      }
+    }
+    if (!oi->Provides.empty()) {
+      ddVars["restat"] = "1";
+    }
+
+    this->WriteBuild(ddf, ddComment, ddRule, ddOutputs, ddImplicitOuts,
+                     ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
+  }
+
+  // Store the map of modules provided by this target in a file for
+  // use by dependents that reference this target in linked-target-dirs.
+  std::string const target_mods_file =
+    cmSystemTools::GetFilenamePath(arg_dd) + "/FortranModules.json";
+  cmGeneratedFileStream tmf(target_mods_file.c_str());
+  tmf << tm;
+
+  return true;
+}
+
+int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
+                             std::vector<std::string>::const_iterator argEnd)
+{
+  std::string arg_dd;
+  std::string arg_tdi;
+  std::vector<std::string> arg_ddis;
+  for (std::vector<std::string>::const_iterator a = argBeg; a != argEnd; ++a) {
+    std::string const& arg = *a;
+    if (cmHasLiteralPrefix(arg, "--tdi=")) {
+      arg_tdi = arg.substr(6);
+    } else if (cmHasLiteralPrefix(arg, "--dd=")) {
+      arg_dd = arg.substr(5);
+    } else if (!cmHasLiteralPrefix(arg, "--") &&
+               cmHasLiteralSuffix(arg, ".ddi")) {
+      arg_ddis.push_back(arg);
+    } else {
+      cmSystemTools::Error("-E cmake_ninja_dyndep unknown argument: ",
+                           arg.c_str());
+      return 1;
+    }
+  }
+  if (arg_tdi.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
+    return 1;
+  }
+  if (arg_dd.empty()) {
+    cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
+    return 1;
+  }
+
+  Json::Value tdio;
+  Json::Value const& tdi = tdio;
+  {
+    cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
+    Json::Reader reader;
+    if (!reader.parse(tdif, tdio, false)) {
+      cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
+                           arg_tdi.c_str(),
+                           reader.getFormattedErrorMessages().c_str());
+      return 1;
+    }
+  }
+
+  std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
+  std::string const dir_cur_src = tdi["dir-cur-src"].asString();
+  std::string const dir_top_bld = tdi["dir-top-bld"].asString();
+  std::string const dir_top_src = tdi["dir-top-src"].asString();
+  std::string module_dir = tdi["module-dir"].asString();
+  if (!module_dir.empty()) {
+    module_dir += "/";
+  }
+  std::vector<std::string> linked_target_dirs;
+  Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
+  if (tdi_linked_target_dirs.isArray()) {
+    for (Json::Value::const_iterator i = tdi_linked_target_dirs.begin();
+         i != tdi_linked_target_dirs.end(); ++i) {
+      linked_target_dirs.push_back(i->asString());
+    }
+  }
+
+  cmake cm;
+  cm.SetHomeDirectory(dir_top_src);
+  cm.SetHomeOutputDirectory(dir_top_bld);
+  CM_AUTO_PTR<cmGlobalNinjaGenerator> ggd(
+    static_cast<cmGlobalNinjaGenerator*>(cm.CreateGlobalGenerator("Ninja")));
+  if (!ggd.get() ||
+      !ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld,
+                            arg_dd, arg_ddis, module_dir,
+                            linked_target_dirs)) {
+    return 1;
+  }
+  return 0;
+}
diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h
index 6d9bfe8..dcf7406 100644
--- a/Source/cmGlobalNinjaGenerator.h
+++ b/Source/cmGlobalNinjaGenerator.h
@@ -1,28 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalNinjaGenerator_h
 #define cmGlobalNinjaGenerator_h
 
-#include "cmGlobalCommonGenerator.h"
+#include <cmConfigure.h>
 
+#include "cmGlobalCommonGenerator.h"
+#include "cmGlobalGenerator.h"
 #include "cmGlobalGeneratorFactory.h"
 #include "cmNinjaTypes.h"
-
-//#define NINJA_GEN_VERBOSE_FILES
-
-class cmLocalGenerator;
+#include "cmPolicies.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+class cmCustomCommand;
+class cmMakefile;
+class cmake;
+struct cmDocumentationEntry;
 class cmGeneratedFileStream;
 class cmGeneratorTarget;
+class cmLocalGenerator;
 
 /**
  * \class cmGlobalNinjaGenerator
@@ -81,6 +83,12 @@ public:
   static bool SupportsToolset() { return false; }
 
   /**
+   * Utilized by the generator factory to determine if this generator
+   * supports platforms.
+   */
+  static bool SupportsPlatform() { return false; }
+
+  /**
    * Write a build statement to @a os with the @a comment using
    * the @a rule the list of @a outputs files and inputs.
    * It also writes the variables bound to this build statement.
@@ -88,12 +96,13 @@ public:
    */
   void WriteBuild(std::ostream& os, const std::string& comment,
                   const std::string& rule, const cmNinjaDeps& outputs,
+                  const cmNinjaDeps& implicitOuts,
                   const cmNinjaDeps& explicitDeps,
                   const cmNinjaDeps& implicitDeps,
                   const cmNinjaDeps& orderOnlyDeps,
                   const cmNinjaVars& variables,
                   const std::string& rspfile = std::string(),
-                  int cmdLineLimit = 0, bool* usedResponseFile = 0);
+                  int cmdLineLimit = 0, bool* usedResponseFile = CM_NULLPTR);
 
   /**
    * Helper to write a build statement with the special 'phony' rule.
@@ -107,7 +116,8 @@ public:
 
   void WriteCustomCommandBuild(const std::string& command,
                                const std::string& description,
-                               const std::string& comment, bool uses_terminal,
+                               const std::string& comment,
+                               const std::string& depfile, bool uses_terminal,
                                bool restat, const cmNinjaDeps& outputs,
                                const cmNinjaDeps& deps = cmNinjaDeps(),
                                const cmNinjaDeps& orderOnly = cmNinjaDeps());
@@ -161,11 +171,11 @@ public:
     return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>();
   }
 
-  virtual ~cmGlobalNinjaGenerator() {}
+  ~cmGlobalNinjaGenerator() CM_OVERRIDE {}
 
-  virtual cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf);
+  cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
 
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return cmGlobalNinjaGenerator::GetActualName();
   }
@@ -174,39 +184,44 @@ public:
 
   static void GetDocumentation(cmDocumentationEntry& entry);
 
-  virtual void EnableLanguage(std::vector<std::string> const& languages,
-                              cmMakefile* mf, bool optional);
+  void EnableLanguage(std::vector<std::string> const& languages,
+                      cmMakefile* mf, bool optional) CM_OVERRIDE;
 
-  virtual void GenerateBuildCommand(
-    std::vector<std::string>& makeCommand, const std::string& makeProgram,
-    const std::string& projectName, const std::string& projectDir,
-    const std::string& targetName, const std::string& config, bool fast,
-    bool verbose,
-    std::vector<std::string> const& makeOptions = std::vector<std::string>());
+  void GenerateBuildCommand(std::vector<std::string>& makeCommand,
+                            const std::string& makeProgram,
+                            const std::string& projectName,
+                            const std::string& projectDir,
+                            const std::string& targetName,
+                            const std::string& config, bool fast, bool verbose,
+                            std::vector<std::string> const& makeOptions =
+                              std::vector<std::string>()) CM_OVERRIDE;
 
   // Setup target names
-  virtual const char* GetAllTargetName() const { return "all"; }
-  virtual const char* GetInstallTargetName() const { return "install"; }
-  virtual const char* GetInstallLocalTargetName() const
+  const char* GetAllTargetName() const CM_OVERRIDE { return "all"; }
+  const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
+  const char* GetInstallLocalTargetName() const CM_OVERRIDE
   {
     return "install/local";
   }
-  virtual const char* GetInstallStripTargetName() const
+  const char* GetInstallStripTargetName() const CM_OVERRIDE
   {
     return "install/strip";
   }
-  virtual const char* GetTestTargetName() const { return "test"; }
-  virtual const char* GetPackageTargetName() const { return "package"; }
-  virtual const char* GetPackageSourceTargetName() const
+  const char* GetTestTargetName() const CM_OVERRIDE { return "test"; }
+  const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
+  const char* GetPackageSourceTargetName() const CM_OVERRIDE
   {
     return "package_source";
   }
-  virtual const char* GetEditCacheTargetName() const { return "edit_cache"; }
-  virtual const char* GetRebuildCacheTargetName() const
+  const char* GetEditCacheTargetName() const CM_OVERRIDE
+  {
+    return "edit_cache";
+  }
+  const char* GetRebuildCacheTargetName() const CM_OVERRIDE
   {
     return "rebuild_cache";
   }
-  virtual const char* GetCleanTargetName() const { return "clean"; }
+  const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; }
 
   cmGeneratedFileStream* GetBuildFileStream() const
   {
@@ -290,6 +305,8 @@ public:
                            cmNinjaDeps& outputs);
   void AppendTargetDepends(cmGeneratorTarget const* target,
                            cmNinjaDeps& outputs);
+  void AppendTargetDependsClosure(cmGeneratorTarget const* target,
+                                  cmNinjaDeps& outputs);
   void AddDependencyToAll(cmGeneratorTarget* target);
   void AddDependencyToAll(const std::string& input);
 
@@ -307,25 +324,40 @@ public:
 
   void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
 
-  virtual void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
+  void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
 
   // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
   static std::string RequiredNinjaVersion() { return "1.3"; }
   static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; }
+  static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; }
   bool SupportsConsolePool() const;
+  bool SupportsImplicitOuts() const;
 
   std::string NinjaOutputPath(std::string const& path);
   bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
   void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
 
+  bool WriteDyndepFile(std::string const& dir_top_src,
+                       std::string const& dir_top_bld,
+                       std::string const& dir_cur_src,
+                       std::string const& dir_cur_bld,
+                       std::string const& arg_dd,
+                       std::vector<std::string> const& arg_ddis,
+                       std::string const& module_dir,
+                       std::vector<std::string> const& linked_target_dirs);
+
 protected:
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
-  virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const { return true; }
+  bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; }
 
 private:
-  virtual std::string GetEditCacheCommand() const;
-  virtual void FindMakeProgram(cmMakefile* mf);
+  std::string GetEditCacheCommand() const CM_OVERRIDE;
+  void FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+  void CheckNinjaFeatures();
+  bool CheckLanguages(std::vector<std::string> const& languages,
+                      cmMakefile* mf) const CM_OVERRIDE;
+  bool CheckFortran(cmMakefile* mf) const;
 
   void OpenBuildFileStream();
   void CloseBuildFileStream();
@@ -350,6 +382,10 @@ private:
   void WriteTargetClean(std::ostream& os);
   void WriteTargetHelp(std::ostream& os);
 
+  void ComputeTargetDependsClosure(
+    cmGeneratorTarget const* target,
+    std::set<cmGeneratorTarget const*>& depends);
+
   std::string ninjaCmd() const;
 
   /// The file containing the build statement. (the relationship of the
@@ -399,8 +435,16 @@ private:
   typedef std::map<std::string, cmGeneratorTarget*> TargetAliasMap;
   TargetAliasMap TargetAliases;
 
+  typedef std::map<cmGeneratorTarget const*,
+                   std::set<cmGeneratorTarget const*> >
+    TargetDependsClosureMap;
+  TargetDependsClosureMap TargetDependsClosures;
+
   std::string NinjaCommand;
   std::string NinjaVersion;
+  bool NinjaSupportsConsolePool;
+  bool NinjaSupportsImplicitOuts;
+  unsigned long NinjaSupportsDyndeps;
 
 private:
   void InitOutputPathPrefix();
diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx
index cc5d1ba..4a5cc77 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.cxx
+++ b/Source/cmGlobalUnixMakefileGenerator3.cxx
@@ -1,24 +1,27 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalUnixMakefileGenerator3.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmMakefileTargetGenerator.h"
+#include "cmOutputConverter.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetDepend.h"
 #include "cmake.h"
 
+#include <algorithm>
+#include <functional>
+#include <sstream>
+#include <utility>
+
 cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
   : cmGlobalCommonGenerator(cm)
 {
@@ -32,7 +35,7 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
 #else
   this->UseLinkScript = true;
 #endif
-  this->CommandDatabase = NULL;
+  this->CommandDatabase = CM_NULLPTR;
 
   this->IncludeDirective = "include";
   this->DefineWindowsNULL = false;
@@ -155,10 +158,10 @@ void cmGlobalUnixMakefileGenerator3::Generate()
   this->WriteMainMakefile2();
   this->WriteMainCMakefile();
 
-  if (this->CommandDatabase != NULL) {
+  if (this->CommandDatabase != CM_NULLPTR) {
     *this->CommandDatabase << std::endl << "]";
     delete this->CommandDatabase;
-    this->CommandDatabase = NULL;
+    this->CommandDatabase = CM_NULLPTR;
   }
 }
 
@@ -166,7 +169,7 @@ void cmGlobalUnixMakefileGenerator3::AddCXXCompileCommand(
   const std::string& sourceFile, const std::string& workingDirectory,
   const std::string& compileCommand)
 {
-  if (this->CommandDatabase == NULL) {
+  if (this->CommandDatabase == CM_NULLPTR) {
     std::string commandDatabaseName =
       std::string(this->GetCMakeInstance()->GetHomeOutputDirectory()) +
       "/compile_commands.json";
@@ -307,15 +310,15 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
   std::string cache = this->GetCMakeInstance()->GetHomeOutputDirectory();
   cache += "/CMakeCache.txt";
 
+  std::string currentBinDir = lg->GetCurrentBinaryDirectory();
   // Save the list to the cmake file.
   cmakefileStream
     << "# The top level Makefile was generated from the following files:\n"
     << "set(CMAKE_MAKEFILE_DEPENDS\n"
-    << "  \"" << lg->Convert(cache, cmOutputConverter::START_OUTPUT) << "\"\n";
+    << "  \"" << lg->ConvertToRelativePath(currentBinDir, cache) << "\"\n";
   for (std::vector<std::string>::const_iterator i = lfiles.begin();
        i != lfiles.end(); ++i) {
-    cmakefileStream << "  \""
-                    << lg->Convert(*i, cmOutputConverter::START_OUTPUT)
+    cmakefileStream << "  \"" << lg->ConvertToRelativePath(currentBinDir, *i)
                     << "\"\n";
   }
   cmakefileStream << "  )\n\n";
@@ -329,13 +332,14 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
   cmakefileStream << "# The corresponding makefile is:\n"
                   << "set(CMAKE_MAKEFILE_OUTPUTS\n"
                   << "  \""
-                  << lg->Convert(makefileName, cmOutputConverter::START_OUTPUT)
+                  << lg->ConvertToRelativePath(currentBinDir, makefileName)
                   << "\"\n"
-                  << "  \""
-                  << lg->Convert(check, cmOutputConverter::START_OUTPUT)
+                  << "  \"" << lg->ConvertToRelativePath(currentBinDir, check)
                   << "\"\n";
   cmakefileStream << "  )\n\n";
 
+  const std::string binDir = lg->GetBinaryDirectory();
+
   // CMake must rerun if a byproduct is missing.
   {
     cmakefileStream << "# Byproducts of CMake generate step:\n"
@@ -344,8 +348,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
       lg->GetMakefile()->GetOutputFiles();
     for (std::vector<std::string>::const_iterator k = outfiles.begin();
          k != outfiles.end(); ++k) {
-      cmakefileStream << "  \""
-                      << lg->Convert(*k, cmOutputConverter::HOME_OUTPUT)
+      cmakefileStream << "  \"" << lg->ConvertToRelativePath(binDir, *k)
                       << "\"\n";
     }
 
@@ -357,8 +360,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
       tmpStr = lg->GetCurrentBinaryDirectory();
       tmpStr += cmake::GetCMakeFilesDirectory();
       tmpStr += "/CMakeDirectoryInformation.cmake";
-      cmakefileStream << "  \""
-                      << lg->Convert(tmpStr, cmOutputConverter::HOME_OUTPUT)
+      cmakefileStream << "  \"" << lg->ConvertToRelativePath(binDir, tmpStr)
                       << "\"\n";
     }
     cmakefileStream << "  )\n\n";
@@ -469,9 +471,10 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRules2(
   }
 
   // Begin the directory-level rules section.
-  std::string dir = lg->GetCurrentBinaryDirectory();
-  dir = lg->Convert(dir, cmOutputConverter::HOME_OUTPUT,
-                    cmOutputConverter::MAKERULE);
+  std::string dir = cmSystemTools::ConvertToOutputPath(
+    lg->ConvertToRelativePath(lg->GetBinaryDirectory(),
+                              lg->GetCurrentBinaryDirectory())
+      .c_str());
   lg->WriteDivider(ruleFileStream);
   ruleFileStream << "# Directory level rules for directory " << dir << "\n\n";
 
@@ -519,7 +522,8 @@ void cmGlobalUnixMakefileGenerator3::GenerateBuildCommand(
       tname += "/fast";
     }
     cmOutputConverter conv(mf->GetStateSnapshot());
-    tname = conv.Convert(tname, cmOutputConverter::HOME_OUTPUT);
+    tname =
+      conv.ConvertToRelativePath(mf->GetState()->GetBinaryDirectory(), tname);
     cmSystemTools::ConvertToOutputSlashes(tname);
     makeCommand.push_back(tname);
     if (this->Makefiles.empty()) {
@@ -716,8 +720,9 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
         std::ostringstream progCmd;
         progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
         // # in target
-        progCmd << lg->Convert(progress.Dir, cmOutputConverter::FULL,
-                               cmOutputConverter::SHELL);
+        progCmd << lg->ConvertToOutputFormat(
+          cmSystemTools::CollapseFullPath(progress.Dir),
+          cmOutputConverter::SHELL);
         //
         std::set<cmGeneratorTarget const*> emitted;
         progCmd << " " << this->CountProgressMarksInTarget(gtarget, emitted);
@@ -729,8 +734,9 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
       {
         std::ostringstream progCmd;
         progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
-        progCmd << lg->Convert(progress.Dir, cmOutputConverter::FULL,
-                               cmOutputConverter::SHELL);
+        progCmd << lg->ConvertToOutputFormat(
+          cmSystemTools::CollapseFullPath(progress.Dir),
+          cmOutputConverter::SHELL);
         progCmd << " 0";
         commands.push_back(progCmd.str());
       }
diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h
index f951b2a..1019d86 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.h
+++ b/Source/cmGlobalUnixMakefileGenerator3.h
@@ -1,24 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalUnixMakefileGenerator3_h
 #define cmGlobalUnixMakefileGenerator3_h
 
-#include "cmGlobalCommonGenerator.h"
+#include <cmConfigure.h>
 
+#include "cmGeneratorTarget.h"
+#include "cmGlobalCommonGenerator.h"
 #include "cmGlobalGeneratorFactory.h"
+#include "cmState.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmGeneratedFileStream;
-class cmMakefileTargetGenerator;
+class cmLocalGenerator;
 class cmLocalUnixMakefileGenerator3;
+class cmMakefile;
+class cmMakefileTargetGenerator;
+class cmake;
+struct cmDocumentationEntry;
 
 /** \class cmGlobalUnixMakefileGenerator3
  * \brief Write a Unix makefiles.
@@ -63,7 +68,7 @@ public:
   }
 
   ///! Get the name for the generator.
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return cmGlobalUnixMakefileGenerator3::GetActualName();
   }
@@ -75,26 +80,32 @@ public:
    */
   static bool SupportsToolset() { return false; }
 
+  /**
+   * Utilized by the generator factory to determine if this generator
+   * supports platforms.
+   */
+  static bool SupportsPlatform() { return false; }
+
   /** Get the documentation entry for this generator.  */
   static void GetDocumentation(cmDocumentationEntry& entry);
 
-  virtual cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf);
+  cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
 
   /**
    * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
-  virtual void EnableLanguage(std::vector<std::string> const& languages,
-                              cmMakefile*, bool optional);
+  void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
+                      bool optional) CM_OVERRIDE;
 
-  virtual void Configure();
+  void Configure() CM_OVERRIDE;
 
   /**
    * Generate the all required files for building this project/tree. This
    * basically creates a series of LocalGenerators for each directory and
    * requests that they Generate.
    */
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
   void WriteMainCMakefileLanguageRules(cmGeneratedFileStream& cmakefileStream,
                                        std::vector<cmLocalGenerator*>&);
@@ -116,12 +127,14 @@ public:
   std::string GetEmptyRuleHackDepends() { return this->EmptyRuleHackDepends; }
 
   // change the build command for speed
-  virtual void GenerateBuildCommand(
-    std::vector<std::string>& makeCommand, const std::string& makeProgram,
-    const std::string& projectName, const std::string& projectDir,
-    const std::string& targetName, const std::string& config, bool fast,
-    bool verbose,
-    std::vector<std::string> const& makeOptions = std::vector<std::string>());
+  void GenerateBuildCommand(std::vector<std::string>& makeCommand,
+                            const std::string& makeProgram,
+                            const std::string& projectName,
+                            const std::string& projectDir,
+                            const std::string& targetName,
+                            const std::string& config, bool fast, bool verbose,
+                            std::vector<std::string> const& makeOptions =
+                              std::vector<std::string>()) CM_OVERRIDE;
 
   /** Record per-target progress information.  */
   void RecordTargetProgress(cmMakefileTargetGenerator* tg);
@@ -136,7 +149,7 @@ public:
   /** Does the make tool tolerate .DELETE_ON_ERROR? */
   virtual bool AllowDeleteOnError() const { return true; }
 
-  virtual void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
+  void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
 
   std::string IncludeDirective;
   bool DefineWindowsNULL;
@@ -163,19 +176,37 @@ protected:
   bool NeedRequiresStep(cmGeneratorTarget const*);
 
   // Target name hooks for superclass.
-  const char* GetAllTargetName() const { return "all"; }
-  const char* GetInstallTargetName() const { return "install"; }
-  const char* GetInstallLocalTargetName() const { return "install/local"; }
-  const char* GetInstallStripTargetName() const { return "install/strip"; }
-  const char* GetPreinstallTargetName() const { return "preinstall"; }
-  const char* GetTestTargetName() const { return "test"; }
-  const char* GetPackageTargetName() const { return "package"; }
-  const char* GetPackageSourceTargetName() const { return "package_source"; }
-  const char* GetEditCacheTargetName() const { return "edit_cache"; }
-  const char* GetRebuildCacheTargetName() const { return "rebuild_cache"; }
-  const char* GetCleanTargetName() const { return "clean"; }
-
-  virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const { return true; }
+  const char* GetAllTargetName() const CM_OVERRIDE { return "all"; }
+  const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
+  const char* GetInstallLocalTargetName() const CM_OVERRIDE
+  {
+    return "install/local";
+  }
+  const char* GetInstallStripTargetName() const CM_OVERRIDE
+  {
+    return "install/strip";
+  }
+  const char* GetPreinstallTargetName() const CM_OVERRIDE
+  {
+    return "preinstall";
+  }
+  const char* GetTestTargetName() const CM_OVERRIDE { return "test"; }
+  const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
+  const char* GetPackageSourceTargetName() const CM_OVERRIDE
+  {
+    return "package_source";
+  }
+  const char* GetEditCacheTargetName() const CM_OVERRIDE
+  {
+    return "edit_cache";
+  }
+  const char* GetRebuildCacheTargetName() const CM_OVERRIDE
+  {
+    return "rebuild_cache";
+  }
+  const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; }
+
+  bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; }
 
   // Some make programs (Borland) do not keep a rule if there are no
   // dependencies or commands.  This is a problem for creating rules
@@ -214,13 +245,13 @@ protected:
   cmGeneratedFileStream* CommandDatabase;
 
 private:
-  virtual const char* GetBuildIgnoreErrorsFlag() const { return "-i"; }
-  virtual std::string GetEditCacheCommand() const;
+  const char* GetBuildIgnoreErrorsFlag() const CM_OVERRIDE { return "-i"; }
+  std::string GetEditCacheCommand() const CM_OVERRIDE;
 
   std::map<cmState::Snapshot, std::set<cmGeneratorTarget const*>,
            cmState::Snapshot::StrictWeakOrder>
     DirectoryTargetsMap;
-  virtual void InitializeProgressMarks();
+  void InitializeProgressMarks() CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx
index 90ff98b..caaac87 100644
--- a/Source/cmGlobalVisualStudio10Generator.cxx
+++ b/Source/cmGlobalVisualStudio10Generator.cxx
@@ -1,19 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "windows.h" // this must be first to define GetCurrentDirectory
 
 #include "cmGlobalVisualStudio10Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
@@ -42,8 +34,8 @@ class cmGlobalVisualStudio10Generator::Factory
   : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     std::string genName;
     const char* p = cmVS10GenName(name, genName);
@@ -65,21 +57,22 @@ public:
     return 0;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs10generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2010 project files.  "
                   "Optional [arch] can be \"Win64\" or \"IA64\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs10generatorName);
     names.push_back(vs10generatorName + std::string(" IA64"));
     names.push_back(vs10generatorName + std::string(" Win64"));
   }
 
-  virtual bool SupportsToolset() const { return true; }
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio10Generator::NewFactory()
@@ -100,6 +93,7 @@ cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator(
   this->SystemIsWindowsPhone = false;
   this->SystemIsWindowsStore = false;
   this->MSBuildCommandInitialized = false;
+  this->DefaultPlatformToolset = "v100";
   this->Version = VS10;
 }
 
@@ -347,16 +341,36 @@ std::string const& cmGlobalVisualStudio10Generator::GetMSBuildCommand()
 std::string cmGlobalVisualStudio10Generator::FindMSBuildCommand()
 {
   std::string msbuild;
-  std::string mskey =
-    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\";
+  std::string mskey;
+
+  // Search in standard location.
+  mskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\";
   mskey += this->GetToolsVersion();
   mskey += ";MSBuildToolsPath";
   if (cmSystemTools::ReadRegistryValue(mskey.c_str(), msbuild,
                                        cmSystemTools::KeyWOW64_32)) {
     cmSystemTools::ConvertToUnixSlashes(msbuild);
-    msbuild += "/";
+    msbuild += "/MSBuild.exe";
+    if (cmSystemTools::FileExists(msbuild, true)) {
+      return msbuild;
+    }
+  }
+
+  // Search where VS15Preview places it.
+  mskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;";
+  mskey += this->GetIDEVersion();
+  if (cmSystemTools::ReadRegistryValue(mskey.c_str(), msbuild,
+                                       cmSystemTools::KeyWOW64_32)) {
+    cmSystemTools::ConvertToUnixSlashes(msbuild);
+    msbuild += "/MSBuild/";
+    msbuild += this->GetIDEVersion();
+    msbuild += "/Bin/MSBuild.exe";
+    if (cmSystemTools::FileExists(msbuild, true)) {
+      return msbuild;
+    }
   }
-  msbuild += "MSBuild.exe";
+
+  msbuild = "MSBuild.exe";
   return msbuild;
 }
 
@@ -459,6 +473,10 @@ void cmGlobalVisualStudio10Generator::GenerateBuildCommand(
 
 bool cmGlobalVisualStudio10Generator::Find64BitTools(cmMakefile* mf)
 {
+  if (this->DefaultPlatformToolset == "v100") {
+    // The v100 64-bit toolset does not exist in the express edition.
+    this->DefaultPlatformToolset.clear();
+  }
   if (this->GetPlatformToolset()) {
     return true;
   }
diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h
index 51fd5a5..19c60aa 100644
--- a/Source/cmGlobalVisualStudio10Generator.h
+++ b/Source/cmGlobalVisualStudio10Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio10Generator_h
 #define cmGlobalVisualStudio10Generator_h
 
diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx
index 295b6eb..5d9a02b 100644
--- a/Source/cmGlobalVisualStudio11Generator.cxx
+++ b/Source/cmGlobalVisualStudio11Generator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalVisualStudio11Generator.h"
 
 #include "cmAlgorithms.h"
@@ -36,8 +27,8 @@ class cmGlobalVisualStudio11Generator::Factory
   : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     std::string genName;
     const char* p = cmVS11GenName(name, genName);
@@ -70,14 +61,14 @@ public:
     return ret;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs11generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2012 project files.  "
                   "Optional [arch] can be \"Win64\" or \"ARM\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs11generatorName);
     names.push_back(vs11generatorName + std::string(" ARM"));
@@ -91,7 +82,8 @@ public:
     }
   }
 
-  virtual bool SupportsToolset() const { return true; }
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio11Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio11Generator.h b/Source/cmGlobalVisualStudio11Generator.h
index ef6d343..0c03b0a 100644
--- a/Source/cmGlobalVisualStudio11Generator.h
+++ b/Source/cmGlobalVisualStudio11Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio11Generator_h
 #define cmGlobalVisualStudio11Generator_h
 
diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx
index 318cb39..5fdeec7 100644
--- a/Source/cmGlobalVisualStudio12Generator.cxx
+++ b/Source/cmGlobalVisualStudio12Generator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalVisualStudio12Generator.h"
 
 #include "cmAlgorithms.h"
@@ -36,8 +27,8 @@ class cmGlobalVisualStudio12Generator::Factory
   : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     std::string genName;
     const char* p = cmVS12GenName(name, genName);
@@ -59,21 +50,22 @@ public:
     return 0;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs12generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2013 project files.  "
                   "Optional [arch] can be \"Win64\" or \"ARM\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs12generatorName);
     names.push_back(vs12generatorName + std::string(" ARM"));
     names.push_back(vs12generatorName + std::string(" Win64"));
   }
 
-  virtual bool SupportsToolset() const { return true; }
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio12Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h
index 567e240..78bb637 100644
--- a/Source/cmGlobalVisualStudio12Generator.h
+++ b/Source/cmGlobalVisualStudio12Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio12Generator_h
 #define cmGlobalVisualStudio12Generator_h
 
diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx
index e190e84..586fe3c 100644
--- a/Source/cmGlobalVisualStudio14Generator.cxx
+++ b/Source/cmGlobalVisualStudio14Generator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalVisualStudio14Generator.h"
 
 #include "cmAlgorithms.h"
@@ -36,8 +27,8 @@ class cmGlobalVisualStudio14Generator::Factory
   : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     std::string genName;
     const char* p = cmVS14GenName(name, genName);
@@ -59,21 +50,22 @@ public:
     return 0;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs14generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2015 project files.  "
                   "Optional [arch] can be \"Win64\" or \"ARM\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs14generatorName);
     names.push_back(vs14generatorName + std::string(" ARM"));
     names.push_back(vs14generatorName + std::string(" Win64"));
   }
 
-  virtual bool SupportsToolset() const { return true; }
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio14Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio14Generator.h b/Source/cmGlobalVisualStudio14Generator.h
index a00f6c7..991f018 100644
--- a/Source/cmGlobalVisualStudio14Generator.h
+++ b/Source/cmGlobalVisualStudio14Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio14Generator_h
 #define cmGlobalVisualStudio14Generator_h
 
diff --git a/Source/cmGlobalVisualStudio15Generator.cxx b/Source/cmGlobalVisualStudio15Generator.cxx
new file mode 100644
index 0000000..4d62f2b
--- /dev/null
+++ b/Source/cmGlobalVisualStudio15Generator.cxx
@@ -0,0 +1,142 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmGlobalVisualStudio15Generator.h"
+
+#include "cmAlgorithms.h"
+#include "cmLocalVisualStudio10Generator.h"
+#include "cmMakefile.h"
+
+static const char vs15generatorName[] = "Visual Studio 15";
+
+// Map generator name without year to name with year.
+static const char* cmVS15GenName(const std::string& name, std::string& genName)
+{
+  if (strncmp(name.c_str(), vs15generatorName,
+              sizeof(vs15generatorName) - 1) != 0) {
+    return 0;
+  }
+  const char* p = name.c_str() + sizeof(vs15generatorName) - 1;
+  genName = std::string(vs15generatorName) + p;
+  return p;
+}
+
+class cmGlobalVisualStudio15Generator::Factory
+  : public cmGlobalGeneratorFactory
+{
+public:
+  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                                   cmake* cm) const
+  {
+    std::string genName;
+    const char* p = cmVS15GenName(name, genName);
+    if (!p) {
+      return 0;
+    }
+    if (!*p) {
+      return new cmGlobalVisualStudio15Generator(cm, genName, "");
+    }
+    if (*p++ != ' ') {
+      return 0;
+    }
+    if (strcmp(p, "Win64") == 0) {
+      return new cmGlobalVisualStudio15Generator(cm, genName, "x64");
+    }
+    if (strcmp(p, "ARM") == 0) {
+      return new cmGlobalVisualStudio15Generator(cm, genName, "ARM");
+    }
+    return 0;
+  }
+
+  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  {
+    entry.Name = std::string(vs15generatorName) + " [arch]";
+    entry.Brief = "Generates Visual Studio 15 project files.  "
+                  "Optional [arch] can be \"Win64\" or \"ARM\".";
+  }
+
+  virtual void GetGenerators(std::vector<std::string>& names) const
+  {
+    names.push_back(vs15generatorName);
+    names.push_back(vs15generatorName + std::string(" ARM"));
+    names.push_back(vs15generatorName + std::string(" Win64"));
+  }
+
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
+};
+
+cmGlobalGeneratorFactory* cmGlobalVisualStudio15Generator::NewFactory()
+{
+  return new Factory;
+}
+
+cmGlobalVisualStudio15Generator::cmGlobalVisualStudio15Generator(
+  cmake* cm, const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio14Generator(cm, name, platformName)
+{
+  std::string vc15Express;
+  this->ExpressEdition = cmSystemTools::ReadRegistryValue(
+    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\15.0\\Setup\\VC;"
+    "ProductDir",
+    vc15Express, cmSystemTools::KeyWOW64_32);
+  this->DefaultPlatformToolset = "v140";
+  this->Version = VS15;
+}
+
+bool cmGlobalVisualStudio15Generator::MatchesGeneratorName(
+  const std::string& name) const
+{
+  std::string genName;
+  if (cmVS15GenName(name, genName)) {
+    return genName == this->GetName();
+  }
+  return false;
+}
+
+void cmGlobalVisualStudio15Generator::WriteSLNHeader(std::ostream& fout)
+{
+  // Visual Studio 15 writes .sln format 12.00
+  fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
+  if (this->ExpressEdition) {
+    fout << "# Visual Studio Express 15 for Windows Desktop\n";
+  } else {
+    fout << "# Visual Studio 15\n";
+  }
+}
+
+bool cmGlobalVisualStudio15Generator::SelectWindowsStoreToolset(
+  std::string& toolset) const
+{
+  if (cmHasLiteralPrefix(this->SystemVersion, "10.0")) {
+    if (this->IsWindowsStoreToolsetInstalled() &&
+        this->IsWindowsDesktopToolsetInstalled()) {
+      toolset = "v140"; // VS 15 uses v140 toolset
+      return true;
+    } else {
+      return false;
+    }
+  }
+  return this->cmGlobalVisualStudio14Generator::SelectWindowsStoreToolset(
+    toolset);
+}
+
+bool cmGlobalVisualStudio15Generator::IsWindowsDesktopToolsetInstalled() const
+{
+  const char desktop10Key[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
+                              "VisualStudio\\15.0\\VC\\Runtimes";
+
+  std::vector<std::string> vc15;
+  return cmSystemTools::GetRegistrySubKeys(desktop10Key, vc15,
+                                           cmSystemTools::KeyWOW64_32);
+}
+
+bool cmGlobalVisualStudio15Generator::IsWindowsStoreToolsetInstalled() const
+{
+  const char universal10Key[] =
+    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
+    "VisualStudio\\15.0\\Setup\\Build Tools for Windows 10;SrcPath";
+
+  std::string win10SDK;
+  return cmSystemTools::ReadRegistryValue(universal10Key, win10SDK,
+                                          cmSystemTools::KeyWOW64_32);
+}
diff --git a/Source/cmGlobalVisualStudio15Generator.h b/Source/cmGlobalVisualStudio15Generator.h
new file mode 100644
index 0000000..2e458f4
--- /dev/null
+++ b/Source/cmGlobalVisualStudio15Generator.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 cmGlobalVisualStudio15Generator_h
+#define cmGlobalVisualStudio15Generator_h
+
+#include "cmGlobalVisualStudio14Generator.h"
+
+/** \class cmGlobalVisualStudio15Generator  */
+class cmGlobalVisualStudio15Generator : public cmGlobalVisualStudio14Generator
+{
+public:
+  cmGlobalVisualStudio15Generator(cmake* cm, const std::string& name,
+                                  const std::string& platformName);
+  static cmGlobalGeneratorFactory* NewFactory();
+
+  virtual bool MatchesGeneratorName(const std::string& name) const;
+
+  virtual void WriteSLNHeader(std::ostream& fout);
+
+  virtual const char* GetToolsVersion() { return "15.0"; }
+protected:
+  virtual bool SelectWindowsStoreToolset(std::string& toolset) const;
+
+  virtual const char* GetIDEVersion() { return "15.0"; }
+
+  // Used to verify that the Desktop toolset for the current generator is
+  // installed on the machine.
+  virtual bool IsWindowsDesktopToolsetInstalled() const;
+
+  // These aren't virtual because we need to check if the selected version
+  // of the toolset is installed
+  bool IsWindowsStoreToolsetInstalled() const;
+
+private:
+  class Factory;
+};
+#endif
diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx
index 45d9522..ffd87e2 100644
--- a/Source/cmGlobalVisualStudio71Generator.cxx
+++ b/Source/cmGlobalVisualStudio71Generator.cxx
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "windows.h" // this must be first to define GetCurrentDirectory
 
 #include "cmGlobalVisualStudio71Generator.h"
 
+#include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
 #include "cmake.h"
diff --git a/Source/cmGlobalVisualStudio71Generator.h b/Source/cmGlobalVisualStudio71Generator.h
index 9ad1fad..eb65bcb 100644
--- a/Source/cmGlobalVisualStudio71Generator.h
+++ b/Source/cmGlobalVisualStudio71Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio71Generator_h
 #define cmGlobalVisualStudio71Generator_h
 
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index a33bd8b..3637fed 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -1,19 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "windows.h" // this must be first to define GetCurrentDirectory
 
 #include "cmGlobalVisualStudio7Generator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
 #include "cmUuid.h"
@@ -122,9 +114,9 @@ void cmGlobalVisualStudio7Generator::EnableLanguage(
   // does not use the environment it is run in, and this allows
   // for running commands and using dll's that the IDE environment
   // does not know about.
-  const char* extraPath = cmSystemTools::GetEnv("CMAKE_MSVCIDE_RUN_PATH");
-  if (extraPath) {
-    mf->AddCacheDefinition("CMAKE_MSVCIDE_RUN_PATH", extraPath,
+  std::string extraPath;
+  if (cmSystemTools::GetEnv("CMAKE_MSVCIDE_RUN_PATH", extraPath)) {
+    mf->AddCacheDefinition("CMAKE_MSVCIDE_RUN_PATH", extraPath.c_str(),
                            "Saved environment variable CMAKE_MSVCIDE_RUN_PATH",
                            cmState::STATIC);
   }
@@ -149,13 +141,32 @@ std::string const& cmGlobalVisualStudio7Generator::GetDevEnvCommand()
 std::string cmGlobalVisualStudio7Generator::FindDevEnvCommand()
 {
   std::string vscmd;
-  std::string vskey = this->GetRegistryBase() + ";InstallDir";
+  std::string vskey;
+
+  // Search in standard location.
+  vskey = this->GetRegistryBase() + ";InstallDir";
   if (cmSystemTools::ReadRegistryValue(vskey.c_str(), vscmd,
                                        cmSystemTools::KeyWOW64_32)) {
     cmSystemTools::ConvertToUnixSlashes(vscmd);
-    vscmd += "/";
+    vscmd += "/devenv.com";
+    if (cmSystemTools::FileExists(vscmd, true)) {
+      return vscmd;
+    }
   }
-  vscmd += "devenv.com";
+
+  // Search where VS15Preview places it.
+  vskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;";
+  vskey += this->GetIDEVersion();
+  if (cmSystemTools::ReadRegistryValue(vskey.c_str(), vscmd,
+                                       cmSystemTools::KeyWOW64_32)) {
+    cmSystemTools::ConvertToUnixSlashes(vscmd);
+    vscmd += "/Common7/IDE/devenv.com";
+    if (cmSystemTools::FileExists(vscmd, true)) {
+      return vscmd;
+    }
+  }
+
+  vscmd = "devenv.com";
   return vscmd;
 }
 
@@ -362,6 +373,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
 {
   VisualStudioFolders.clear();
 
+  std::string rootBinaryDir = root->GetCurrentBinaryDirectory();
   for (OrderedTargetDependSet::const_iterator tt = projectTargets.begin();
        tt != projectTargets.end(); ++tt) {
     cmGeneratorTarget const* target = *tt;
@@ -385,7 +397,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
       if (vcprojName) {
         cmLocalGenerator* lg = target->GetLocalGenerator();
         std::string dir = lg->GetCurrentBinaryDirectory();
-        dir = root->Convert(dir.c_str(), cmOutputConverter::START_OUTPUT);
+        dir = root->ConvertToRelativePath(rootBinaryDir, dir.c_str());
         if (dir == ".") {
           dir = ""; // msbuild cannot handle ".\" prefix
         }
@@ -674,7 +686,7 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(
           target->Target->GetMakefile()->GetDefinition(
             "CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD");
         cmGeneratorExpression ge;
-        cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+        CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
           ge.Parse(propertyValue);
         if (cmSystemTools::IsOn(
               cge->Evaluate(target->GetLocalGenerator(), *i))) {
diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h
index 2092343..3c6ce11 100644
--- a/Source/cmGlobalVisualStudio7Generator.h
+++ b/Source/cmGlobalVisualStudio7Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio7Generator_h
 #define cmGlobalVisualStudio7Generator_h
 
@@ -48,6 +39,12 @@ public:
   static bool SupportsToolset() { return false; }
 
   /**
+   * Utilized by the generator factory to determine if this generator
+   * supports platforms.
+   */
+  static bool SupportsPlatform() { return false; }
+
+  /**
    * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx
index dfe196a..2ce0098 100644
--- a/Source/cmGlobalVisualStudio8Generator.cxx
+++ b/Source/cmGlobalVisualStudio8Generator.cxx
@@ -1,19 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "windows.h" // this must be first to define GetCurrentDirectory
 
 #include "cmGlobalVisualStudio8Generator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
@@ -25,8 +17,8 @@ static const char vs8generatorName[] = "Visual Studio 8 2005";
 class cmGlobalVisualStudio8Generator::Factory : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     if (strncmp(name.c_str(), vs8generatorName,
                 sizeof(vs8generatorName) - 1) != 0) {
@@ -60,14 +52,14 @@ public:
     return ret;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs8generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2005 project files.  "
                   "Optional [arch] can be \"Win64\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs8generatorName);
     names.push_back(vs8generatorName + std::string(" Win64"));
@@ -82,7 +74,8 @@ public:
     }
   }
 
-  virtual bool SupportsToolset() const { return false; }
+  bool SupportsToolset() const CM_OVERRIDE { return false; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio8Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h
index b29106f..2543ec1 100644
--- a/Source/cmGlobalVisualStudio8Generator.h
+++ b/Source/cmGlobalVisualStudio8Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio8Generator_h
 #define cmGlobalVisualStudio8Generator_h
 
diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx
index a47f4fc..32ba849 100644
--- a/Source/cmGlobalVisualStudio9Generator.cxx
+++ b/Source/cmGlobalVisualStudio9Generator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "windows.h" // this must be first to define GetCurrentDirectory
 
 #include "cmGlobalVisualStudio9Generator.h"
@@ -23,8 +14,8 @@ static const char vs9generatorName[] = "Visual Studio 9 2008";
 class cmGlobalVisualStudio9Generator::Factory : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE
   {
     if (strncmp(name.c_str(), vs9generatorName,
                 sizeof(vs9generatorName) - 1) != 0) {
@@ -62,14 +53,14 @@ public:
     return ret;
   }
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     entry.Name = std::string(vs9generatorName) + " [arch]";
     entry.Brief = "Generates Visual Studio 2008 project files.  "
                   "Optional [arch] can be \"Win64\" or \"IA64\".";
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(vs9generatorName);
     names.push_back(vs9generatorName + std::string(" Win64"));
@@ -85,7 +76,8 @@ public:
     }
   }
 
-  virtual bool SupportsToolset() const { return false; }
+  bool SupportsToolset() const CM_OVERRIDE { return false; }
+  bool SupportsPlatform() const CM_OVERRIDE { return true; }
 };
 
 cmGlobalGeneratorFactory* cmGlobalVisualStudio9Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio9Generator.h b/Source/cmGlobalVisualStudio9Generator.h
index 2c82c3a..fbc1f5d 100644
--- a/Source/cmGlobalVisualStudio9Generator.h
+++ b/Source/cmGlobalVisualStudio9Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudio9Generator_h
 #define cmGlobalVisualStudio9Generator_h
 
diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx
index 1bec581..6296dd2 100644
--- a/Source/cmGlobalVisualStudioGenerator.cxx
+++ b/Source/cmGlobalVisualStudioGenerator.cxx
@@ -1,15 +1,6 @@
 
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalVisualStudioGenerator.h"
 
 #include "cmAlgorithms.h"
@@ -827,6 +818,7 @@ void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
     cmSystemTools::Error("could not open ", objs_file.c_str());
     return;
   }
+  std::vector<std::string> objs;
   for (std::vector<cmSourceFile const*>::const_iterator it =
          objectSources.begin();
        it != objectSources.end(); ++it) {
@@ -836,6 +828,12 @@ void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
     // It must exist because we populated the mapping just above.
     assert(!map_it->second.empty());
     std::string objFile = obj_dir + map_it->second;
+    objs.push_back(objFile);
+  }
+  gt->UseObjectLibraries(objs, configName);
+  for (std::vector<std::string>::iterator it = objs.begin(); it != objs.end();
+       ++it) {
+    std::string objFile = *it;
     // replace $(ConfigurationName) in the object names
     cmSystemTools::ReplaceString(objFile, this->GetCMakeCFGIntDir(),
                                  configName.c_str());
diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h
index fb2cdbd..a774d96 100644
--- a/Source/cmGlobalVisualStudioGenerator.h
+++ b/Source/cmGlobalVisualStudioGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalVisualStudioGenerator_h
 #define cmGlobalVisualStudioGenerator_h
 
@@ -34,7 +25,8 @@ public:
     VS11 = 110,
     VS12 = 120,
     /* VS13 = 130 was skipped */
-    VS14 = 140
+    VS14 = 140,
+    VS15 = 150
   };
 
   cmGlobalVisualStudioGenerator(cmake* cm);
@@ -85,7 +77,7 @@ public:
 
   /** Return true if the generated build tree may contain multiple builds.
       i.e. "Can I build Debug and Release in the same tree?" */
-  virtual bool IsMultiConfig() { return true; }
+  virtual bool IsMultiConfig() const { return true; }
 
   /** Return true if building for Windows CE */
   virtual bool TargetsWindowsCE() const { return false; }
diff --git a/Source/cmGlobalWatcomWMakeGenerator.cxx b/Source/cmGlobalWatcomWMakeGenerator.cxx
index 86fe6f2..94cdb38 100644
--- a/Source/cmGlobalWatcomWMakeGenerator.cxx
+++ b/Source/cmGlobalWatcomWMakeGenerator.cxx
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalWatcomWMakeGenerator.h"
 
-#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmDocumentationEntry.h"
 #include "cmMakefile.h"
+#include "cmState.h"
+#include "cmake.h"
 
 cmGlobalWatcomWMakeGenerator::cmGlobalWatcomWMakeGenerator(cmake* cm)
   : cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalWatcomWMakeGenerator.h b/Source/cmGlobalWatcomWMakeGenerator.h
index 3954907..1c290f8 100644
--- a/Source/cmGlobalWatcomWMakeGenerator.h
+++ b/Source/cmGlobalWatcomWMakeGenerator.h
@@ -1,19 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalWatcomWMakeGenerator_h
 #define cmGlobalWatcomWMakeGenerator_h
 
+#include <cmConfigure.h>
+
+#include "cmGlobalGeneratorFactory.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
 
+#include <string>
+#include <vector>
+
+class cmMakefile;
+class cmake;
+struct cmDocumentationEntry;
+
 /** \class cmGlobalWatcomWMakeGenerator
  * \brief Write a NMake makefiles.
  *
@@ -28,7 +29,7 @@ public:
     return new cmGlobalGeneratorSimpleFactory<cmGlobalWatcomWMakeGenerator>();
   }
   ///! Get the name for the generator.
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return cmGlobalWatcomWMakeGenerator::GetActualName();
   }
@@ -41,11 +42,11 @@ public:
    * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
-  virtual void EnableLanguage(std::vector<std::string> const& languages,
-                              cmMakefile*, bool optional);
+  void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
+                      bool optional) CM_OVERRIDE;
 
-  virtual bool AllowNotParallel() const { return false; }
-  virtual bool AllowDeleteOnError() const { return false; }
+  bool AllowNotParallel() const CM_OVERRIDE { return false; }
+  bool AllowDeleteOnError() const CM_OVERRIDE { return false; }
 };
 
 #endif
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 6628cfc..4ff612d 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalXCodeGenerator.h"
 
 #include "cmAlgorithms.h"
@@ -24,7 +15,7 @@
 #include "cmXCodeObject.h"
 #include "cmake.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmXMLParser.h"
@@ -108,20 +99,21 @@ public:
 class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
 {
 public:
-  virtual cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
-                                                   cmake* cm) const;
+  cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+                                           cmake* cm) const CM_OVERRIDE;
 
-  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+  void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
   {
     cmGlobalXCodeGenerator::GetDocumentation(entry);
   }
 
-  virtual void GetGenerators(std::vector<std::string>& names) const
+  void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
   {
     names.push_back(cmGlobalXCodeGenerator::GetActualName());
   }
 
-  virtual bool SupportsToolset() const { return true; }
+  bool SupportsToolset() const CM_OVERRIDE { return true; }
+  bool SupportsPlatform() const CM_OVERRIDE { return false; }
 };
 
 cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(cmake* cm,
@@ -175,7 +167,7 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(
     parser.ParseFile(
       "/Developer/Applications/Xcode.app/Contents/version.plist");
   }
-  cmsys::auto_ptr<cmGlobalXCodeGenerator> gg(
+  CM_AUTO_PTR<cmGlobalXCodeGenerator> gg(
     new cmGlobalXCodeGenerator(cm, parser.Version));
   if (gg->XcodeVersion == 20) {
     cmSystemTools::Message("Xcode 2.0 not really supported by cmake, "
@@ -396,7 +388,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
   std::string listfile = root->GetCurrentSourceDirectory();
   listfile += "/";
   listfile += "CMakeLists.txt";
-  allBuildGt->AddSource(listfile.c_str());
+  allBuildGt->AddSource(listfile);
 
   // Add XCODE depend helper
   std::string dir = root->GetCurrentBinaryDirectory();
@@ -404,9 +396,9 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
   if (this->XcodeVersion < 50) {
     makeHelper.push_back("make");
     makeHelper.push_back("-C");
-    makeHelper.push_back(dir.c_str());
+    makeHelper.push_back(dir);
     makeHelper.push_back("-f");
-    makeHelper.push_back(this->CurrentXCodeHackMakefile.c_str());
+    makeHelper.push_back(this->CurrentXCodeHackMakefile);
     makeHelper.push_back(""); // placeholder, see below
   }
 
@@ -479,7 +471,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
       listfile = lg->GetCurrentSourceDirectory();
       listfile += "/";
       listfile += "CMakeLists.txt";
-      target->AddSource(listfile.c_str());
+      target->AddSource(listfile);
     }
   }
 }
@@ -659,7 +651,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
   // Add flags from target and source file properties.
   std::string flags;
   const char* srcfmt = sf->GetProperty("Fortran_FORMAT");
-  switch (this->CurrentLocalGenerator->GetFortranFormat(srcfmt)) {
+  switch (cmOutputConverter::GetFortranFormat(srcfmt)) {
     case cmOutputConverter::FortranFormatFixed:
       flags = "-fixed " + flags;
       break;
@@ -689,7 +681,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
   cmXCodeObject* fileRef = buildFile->GetObject("fileRef")->GetObject();
 
   cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
-  settings->AddAttribute("COMPILER_FLAGS", this->CreateString(flags));
+  settings->AddAttributeIfNotEmpty("COMPILER_FLAGS",
+                                   this->CreateString(flags));
 
   // Is this a resource file in this target? Add it to the resources group...
   //
@@ -698,23 +691,37 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
     gtgt->GetTargetSourceFileFlags(sf);
   bool isResource = tsFlags.Type == cmGeneratorTarget::SourceFileTypeResource;
 
+  cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
+
   // Is this a "private" or "public" framework header file?
   // Set the ATTRIBUTES attribute appropriately...
   //
   if (gtgt->IsFrameworkOnApple()) {
     if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePrivateHeader) {
-      cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
       attrs->AddObject(this->CreateString("Private"));
-      settings->AddAttribute("ATTRIBUTES", attrs);
       isResource = true;
     } else if (tsFlags.Type == cmGeneratorTarget::SourceFileTypePublicHeader) {
-      cmXCodeObject* attrs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
       attrs->AddObject(this->CreateString("Public"));
-      settings->AddAttribute("ATTRIBUTES", attrs);
       isResource = true;
     }
   }
 
+  // Add user-specified file attributes.
+  const char* extraFileAttributes = sf->GetProperty("XCODE_FILE_ATTRIBUTES");
+  if (extraFileAttributes) {
+    // Expand the list of attributes.
+    std::vector<std::string> attributes;
+    cmSystemTools::ExpandListArgument(extraFileAttributes, attributes);
+
+    // Store the attributes.
+    for (std::vector<std::string>::const_iterator ai = attributes.begin();
+         ai != attributes.end(); ++ai) {
+      attrs->AddObject(this->CreateString(*ai));
+    }
+  }
+
+  settings->AddAttributeIfNotEmpty("ATTRIBUTES", attrs);
+
   // Add the fileRef to the top level Resources group/folder if it is not
   // already there.
   //
@@ -723,7 +730,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
     this->ResourcesGroupChildren->AddObject(fileRef);
   }
 
-  buildFile->AddAttribute("settings", settings);
+  buildFile->AddAttributeIfNotEmpty("settings", settings);
   return buildFile;
 }
 
@@ -772,6 +779,8 @@ std::string GetSourcecodeValueFromFileExtension(const std::string& _ext,
     sourcecode += ".asm";
   } else if (ext == "metal") {
     sourcecode += ".metal";
+  } else if (ext == "mig") {
+    sourcecode += ".mig";
   }
   // else
   //  {
@@ -823,7 +832,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
     // lastKnownFileType as folder in order for Xcode to be able to
     // open the contents of the folder.
     // (Xcode 4.6 does not like explicitFileType=folder).
-    if (cmSystemTools::FileIsDirectory(fullpath.c_str())) {
+    if (cmSystemTools::FileIsDirectory(fullpath)) {
       fileType = (ext == "xcassets" ? "folder.assetcatalog" : "folder");
       useLastKnownFileType = true;
     } else {
@@ -838,7 +847,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeFileReferenceFromPath(
 
   // Store the file path relative to the top of the source tree.
   std::string path = this->RelativeToSource(fullpath.c_str());
-  std::string name = cmSystemTools::GetFilenameName(path.c_str());
+  std::string name = cmSystemTools::GetFilenameName(path);
   const char* sourceTree =
     (cmSystemTools::FileIsFullPath(path.c_str()) ? "<absolute>"
                                                  : "SOURCE_ROOT");
@@ -878,10 +887,6 @@ void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen)
 {
   this->CurrentLocalGenerator = gen;
   this->CurrentMakefile = gen->GetMakefile();
-  std::string outdir = cmSystemTools::CollapseFullPath(
-    this->CurrentLocalGenerator->GetCurrentBinaryDirectory());
-  cmSystemTools::SplitPath(outdir.c_str(),
-                           this->CurrentOutputDirectoryComponents);
 
   // Select the current set of configuration types.
   this->CurrentConfigurationTypes.clear();
@@ -933,7 +938,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
     std::string targetName = gtgt->GetName();
 
     // make sure ALL_BUILD, INSTALL, etc are only done once
-    if (this->SpecialTargetEmitted(targetName.c_str())) {
+    if (this->SpecialTargetEmitted(targetName)) {
       continue;
     }
 
@@ -1205,7 +1210,7 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
     cmGeneratedFileStream fout(fname.c_str());
     fout << "\n";
   }
-  if (cmSourceFile* sf = mf->GetOrCreateSource(fname.c_str())) {
+  if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
     sf->SetProperty("LANGUAGE", llang.c_str());
     gtgt->AddSource(fname);
   }
@@ -1450,7 +1455,7 @@ void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(
        currentConfig != this->CurrentConfigurationTypes.end();
        currentConfig++) {
     this->CreateCustomRulesMakefile(makefile.c_str(), target, commands,
-                                    currentConfig->c_str());
+                                    *currentConfig);
   }
 
   std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
@@ -1532,8 +1537,8 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
              ccg.GetDepends().begin();
            d != ccg.GetDepends().end(); ++d) {
         std::string dep;
-        if (this->CurrentLocalGenerator->GetRealDependency(d->c_str(),
-                                                           configName, dep)) {
+        if (this->CurrentLocalGenerator->GetRealDependency(*d, configName,
+                                                           dep)) {
           makefileStream << "\\\n"
                          << this->ConvertToRelativeForMake(dep.c_str());
         }
@@ -1544,7 +1549,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
         std::string echo_cmd = "echo ";
         echo_cmd += (this->CurrentLocalGenerator->EscapeForShell(
           comment, ccg.GetCC().GetEscapeAllowMakeVars()));
-        makefileStream << "\t" << echo_cmd.c_str() << "\n";
+        makefileStream << "\t" << echo_cmd << "\n";
       }
 
       // Add each command line to the set of commands.
@@ -1562,7 +1567,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
         }
         cmd += cmd2;
         ccg.AppendArguments(c, cmd);
-        makefileStream << "\t" << cmd.c_str() << "\n";
+        makefileStream << "\t" << cmd << "\n";
       }
     }
   }
@@ -1644,7 +1649,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
   }
   if (!extraLinkOptionsVar.empty()) {
     this->CurrentLocalGenerator->AddConfigVariableFlags(
-      extraLinkOptions, extraLinkOptionsVar.c_str(), configName);
+      extraLinkOptions, extraLinkOptionsVar, configName);
   }
 
   if (gtgt->GetType() == cmState::OBJECT_LIBRARY ||
@@ -1660,7 +1665,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
     if (!configName.empty()) {
       std::string linkFlagsVar = "LINK_FLAGS_";
       linkFlagsVar += cmSystemTools::UpperCase(configName);
-      if (const char* linkFlags = gtgt->GetProperty(linkFlagsVar.c_str())) {
+      if (const char* linkFlags = gtgt->GetProperty(linkFlagsVar)) {
         this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, linkFlags);
       }
     }
@@ -1784,6 +1789,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
           extraLinkOptions += " ";
           extraLinkOptions += createFlags;
         }
+        const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
+        if (ext) {
+          buildSettings->AddAttribute("WRAPPER_EXTENSION",
+                                      this->CreateString(ext));
+        }
         std::string plist = this->ComputeInfoPListLocation(gtgt);
         // Xcode will create the final version of Info.plist at build time,
         // so let it replace the cfbundle name. This avoids creating
@@ -1821,6 +1831,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
         std::string fw_version = gtgt->GetFrameworkVersion();
         buildSettings->AddAttribute("FRAMEWORK_VERSION",
                                     this->CreateString(fw_version));
+        const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
+        if (ext) {
+          buildSettings->AddAttribute("WRAPPER_EXTENSION",
+                                      this->CreateString(ext));
+        }
 
         std::string plist = this->ComputeInfoPListLocation(gtgt);
         // Xcode will create the final version of Info.plist at build time,
@@ -1855,6 +1870,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
       // Handle bundles and normal executables separately.
       if (gtgt->GetPropertyAsBool("MACOSX_BUNDLE")) {
+        const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
+        if (ext) {
+          buildSettings->AddAttribute("WRAPPER_EXTENSION",
+                                      this->CreateString(ext));
+        }
         std::string plist = this->ComputeInfoPListLocation(gtgt);
         // Xcode will create the final version of Info.plist at build time,
         // so let it replace the executable name.  This avoids creating
@@ -1874,23 +1894,40 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
   BuildObjectListOrString dirs(this, this->XcodeVersion >= 30);
   BuildObjectListOrString fdirs(this, this->XcodeVersion >= 30);
-  std::vector<std::string> includes;
-  this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, "C",
-                                                     configName);
   std::set<std::string> emitted;
   emitted.insert("/System/Library/Frameworks");
-  for (std::vector<std::string>::iterator i = includes.begin();
-       i != includes.end(); ++i) {
-    if (this->NameResolvesToFramework(i->c_str())) {
-      std::string frameworkDir = *i;
-      frameworkDir += "/../";
-      frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
-      if (emitted.insert(frameworkDir).second) {
-        fdirs.Add(this->XCodeEscapePath(frameworkDir));
+
+  if (this->XcodeVersion < 60) {
+    std::vector<std::string> includes;
+    this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, "C",
+                                                       configName);
+    for (std::vector<std::string>::iterator i = includes.begin();
+         i != includes.end(); ++i) {
+      if (this->NameResolvesToFramework(*i)) {
+        std::string frameworkDir = *i;
+        frameworkDir += "/../";
+        frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
+        if (emitted.insert(frameworkDir).second) {
+          fdirs.Add(this->XCodeEscapePath(frameworkDir));
+        }
+      } else {
+        std::string incpath = this->XCodeEscapePath(*i);
+        dirs.Add(incpath);
+      }
+    }
+  } else {
+    for (std::set<std::string>::iterator li = languages.begin();
+         li != languages.end(); ++li) {
+      std::vector<std::string> includes;
+      this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, *li,
+                                                         configName);
+      std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
+        includes, gtgt, *li, true, false, configName);
+
+      std::string& flags = cflags[*li];
+      if (!includeFlags.empty()) {
+        flags += " " + includeFlags;
       }
-    } else {
-      std::string incpath = this->XCodeEscapePath(*i);
-      dirs.Add(incpath);
     }
   }
   // Add framework search paths needed for linking.
@@ -1975,13 +2012,16 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
                                   this->CreateString(flags));
     } else if (*li == "C") {
       buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
+    } else if (*li == "Swift") {
+      buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
+                                  this->CreateString(flags));
     }
   }
 
   // Add Fortran source format attribute if property is set.
   const char* format = 0;
   const char* tgtfmt = gtgt->GetProperty("Fortran_FORMAT");
-  switch (this->CurrentLocalGenerator->GetFortranFormat(tgtfmt)) {
+  switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
     case cmOutputConverter::FortranFormatFixed:
       format = "fixed";
       break;
@@ -2112,7 +2152,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
           std::string processed =
             ge.Parse(gtgt->GetProperty(*i))
               ->Evaluate(this->CurrentLocalGenerator, configName);
-          buildSettings->AddAttribute(attribute.c_str(),
+          buildSettings->AddAttribute(attribute,
                                       this->CreateString(processed));
         }
       }
@@ -2142,7 +2182,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
 
   cmXCodeObject* target =
     this->CreateObject(cmXCodeObject::PBXAggregateTarget);
-  target->SetComment(gtgt->GetName().c_str());
+  target->SetComment(gtgt->GetName());
   cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
   std::vector<cmXCodeObject*> emptyContentVector;
   this->CreateCustomCommands(buildPhases, 0, 0, 0, emptyContentVector, 0,
@@ -2180,7 +2220,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
     }
   }
 
-  target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()).c_str());
+  target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
 
   return target;
 }
@@ -2204,7 +2244,7 @@ std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
   comment += " \"";
   comment += gtgt->GetName();
   comment += "\"";
-  configlist->SetComment(comment.c_str());
+  configlist->SetComment(comment);
   target->AddAttribute("buildConfigurationList",
                        this->CreateObjectReference(configlist));
   for (unsigned int i = 0; i < configVector.size(); ++i) {
@@ -2213,9 +2253,9 @@ std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
     buildConfigurations->AddObject(config);
     cmXCodeObject* buildSettings =
       this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
-    this->CreateBuildSettings(gtgt, buildSettings, configVector[i].c_str());
+    this->CreateBuildSettings(gtgt, buildSettings, configVector[i]);
     config->AddAttribute("name", this->CreateString(configVector[i]));
-    config->SetComment(configVector[i].c_str());
+    config->SetComment(configVector[i]);
     config->AddAttribute("buildSettings", buildSettings);
   }
   if (!configVector.empty()) {
@@ -2314,7 +2354,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
     cmXCodeObject* buildSettings =
       this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
     defConfig = this->CurrentMakefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-    this->CreateBuildSettings(gtgt, buildSettings, defConfig.c_str());
+    this->CreateBuildSettings(gtgt, buildSettings, defConfig);
     target->AddAttribute("buildSettings", buildSettings);
   }
   cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
@@ -2332,7 +2372,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
     fullName += gtgt->GetName();
     fullName += ".a";
   } else {
-    fullName = gtgt->GetFullName(defConfig.c_str());
+    fullName = gtgt->GetFullName(defConfig);
   }
   fileRef->AddAttribute("path", this->CreateString(fullName));
   if (this->XcodeVersion == 15) {
@@ -2340,7 +2380,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
   }
   fileRef->AddAttribute("sourceTree",
                         this->CreateString("BUILT_PRODUCTS_DIR"));
-  fileRef->SetComment(gtgt->GetName().c_str());
+  fileRef->SetComment(gtgt->GetName());
   target->AddAttribute("productReference",
                        this->CreateObjectReference(fileRef));
   if (const char* productType = this->GetTargetProductType(gtgt)) {
@@ -2348,7 +2388,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
   }
   target->SetTarget(gtgt);
   this->XCodeObjectMap[gtgt] = target;
-  target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()).c_str());
+  target->SetId(this->GetOrCreateId(gtgt->GetName(), target->GetId()));
   return target;
 }
 
@@ -2373,15 +2413,14 @@ std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
   std::string guidStoreName = name;
   guidStoreName += "_GUID_CMAKE";
   const char* storedGUID =
-    this->CMakeInstance->GetCacheDefinition(guidStoreName.c_str());
+    this->CMakeInstance->GetCacheDefinition(guidStoreName);
 
   if (storedGUID) {
     return storedGUID;
   }
 
-  this->CMakeInstance->AddCacheEntry(guidStoreName.c_str(), id.c_str(),
-                                     "Stored Xcode object GUID",
-                                     cmState::INTERNAL);
+  this->CMakeInstance->AddCacheEntry(
+    guidStoreName, id.c_str(), "Stored Xcode object GUID", cmState::INTERNAL);
 
   return id;
 }
@@ -2429,7 +2468,7 @@ void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings,
       std::string oldValue = attr->GetString();
       oldValue += " ";
       oldValue += value;
-      attr->SetString(oldValue.c_str());
+      attr->SetString(oldValue);
     }
   }
 }
@@ -2529,7 +2568,7 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
       std::vector<std::string> const& libDeps = cli.GetDepends();
       for (std::vector<std::string>::const_iterator j = libDeps.begin();
            j != libDeps.end(); ++j) {
-        target->AddDependLibrary(configName, j->c_str());
+        target->AddDependLibrary(configName, *j);
       }
     }
 
@@ -2582,13 +2621,10 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
 }
 
 bool cmGlobalXCodeGenerator::CreateGroups(
-  cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
+  std::vector<cmLocalGenerator*>& generators)
 {
   for (std::vector<cmLocalGenerator*>::iterator i = generators.begin();
        i != generators.end(); ++i) {
-    if (this->IsExcluded(root, *i)) {
-      continue;
-    }
     cmMakefile* mf = (*i)->GetMakefile();
     std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
     std::vector<cmGeneratorTarget*> tgts = (*i)->GetGeneratorTargets();
@@ -2820,7 +2856,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
   this->MainGroupChildren->AddObject(resourcesGroup);
 
   // now create the cmake groups
-  if (!this->CreateGroups(root, generators)) {
+  if (!this->CreateGroups(generators)) {
     return false;
   }
 
@@ -2841,8 +2877,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
   std::string project_id = "PROJECT_";
   project_id += root->GetProjectName();
   this->RootObject->SetId(
-    this->GetOrCreateId(project_id.c_str(), this->RootObject->GetId())
-      .c_str());
+    this->GetOrCreateId(project_id.c_str(), this->RootObject->GetId()));
 
   group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
   this->RootObject->AddAttribute("mainGroup",
@@ -2913,7 +2948,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
   comment += " \"";
   comment += this->CurrentProject;
   comment += "\"";
-  configlist->SetComment(comment.c_str());
+  configlist->SetComment(comment);
   configlist->AddAttribute("defaultConfigurationIsVisible",
                            this->CreateString("0"));
   configlist->AddAttribute("defaultConfigurationName",
@@ -2952,6 +2987,15 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
     buildSettings->AddAttribute("GCC_VERSION",
                                 this->CreateString(this->GeneratorToolset));
   }
+  if (this->GetLanguageEnabled("Swift")) {
+    std::string swiftVersion = "2.3";
+    if (const char* vers = this->CurrentMakefile->GetDefinition(
+          "CMAKE_Swift_LANGUAGE_VERSION")) {
+      swiftVersion = vers;
+    }
+    buildSettings->AddAttribute("SWIFT_VERSION",
+                                this->CreateString(swiftVersion));
+  }
 
   std::string symroot = root->GetCurrentBinaryDirectory();
   symroot += "/build";
@@ -2988,10 +3032,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
   std::vector<cmXCodeObject*> targets;
   for (std::vector<cmLocalGenerator*>::iterator i = generators.begin();
        i != generators.end(); ++i) {
-    if (!this->IsExcluded(root, *i)) {
-      if (!this->CreateXCodeTargets(*i, targets)) {
-        return false;
-      }
+    if (!this->CreateXCodeTargets(*i, targets)) {
+      return false;
     }
   }
   // loop over all targets and add link and depend info
@@ -3325,8 +3367,7 @@ std::string cmGlobalXCodeGenerator::LookupFlags(
     std::string varName = varNamePrefix;
     varName += varNameLang;
     varName += varNameSuffix;
-    if (const char* varValue =
-          this->CurrentMakefile->GetDefinition(varName.c_str())) {
+    if (const char* varValue = this->CurrentMakefile->GetDefinition(varName)) {
       if (*varValue) {
         return varValue;
       }
@@ -3437,7 +3478,7 @@ std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation(
 
 // Return true if the generated build tree may contain multiple builds.
 // i.e. "Can I build Debug and Release in the same tree?"
-bool cmGlobalXCodeGenerator::IsMultiConfig()
+bool cmGlobalXCodeGenerator::IsMultiConfig() const
 {
   // Old Xcode 1.5 is single config:
   if (this->XcodeVersion == 15) {
diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h
index 2ca4c19..dbd5205 100644
--- a/Source/cmGlobalXCodeGenerator.h
+++ b/Source/cmGlobalXCodeGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGlobalXCodeGenerator_h
 #define cmGlobalXCodeGenerator_h
 
@@ -79,7 +70,7 @@ public:
 
   /** Return true if the generated build tree may contain multiple builds.
       i.e. "Can I build Debug and Release in the same tree?" */
-  virtual bool IsMultiConfig();
+  virtual bool IsMultiConfig() const;
 
   virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
   void AppendFlag(std::string& flags, std::string const& flag);
@@ -92,8 +83,7 @@ private:
   cmXCodeObject* CreateOrGetPBXGroup(cmGeneratorTarget* gtgt,
                                      cmSourceGroup* sg);
   cmXCodeObject* CreatePBXGroup(cmXCodeObject* parent, std::string name);
-  bool CreateGroups(cmLocalGenerator* root,
-                    std::vector<cmLocalGenerator*>& generators);
+  bool CreateGroups(std::vector<cmLocalGenerator*>& generators);
   std::string XCodeEscapePath(const std::string& p);
   std::string RelativeToSource(const char* p);
   std::string RelativeToBinary(const char* p);
@@ -242,7 +232,6 @@ private:
   std::string CurrentXCodeHackMakefile;
   std::string CurrentProject;
   std::set<std::string> TargetDoneSet;
-  std::vector<std::string> CurrentOutputDirectoryComponents;
   std::vector<std::string> ProjectSourceDirectoryComponents;
   std::vector<std::string> ProjectOutputDirectoryComponents;
   std::map<std::string, cmXCodeObject*> GroupMap;
diff --git a/Source/cmGraphAdjacencyList.h b/Source/cmGraphAdjacencyList.h
index 5666d48..a154373 100644
--- a/Source/cmGraphAdjacencyList.h
+++ b/Source/cmGraphAdjacencyList.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmGraphAdjacencyList_h
 #define cmGraphAdjacencyList_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /**
diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx
index 20cd171..db11bd3 100644
--- a/Source/cmGraphVizWriter.cxx
+++ b/Source/cmGraphVizWriter.cxx
@@ -1,20 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGraphVizWriter.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
+#include <cmConfigure.h>
+#include <iostream>
+#include <sstream>
+#include <utility>
 
 static const char* getShapeForTarget(const cmGeneratorTarget* target)
 {
@@ -64,9 +65,8 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
   cm.SetHomeOutputDirectory("");
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator ggi(&cm);
-  cmsys::auto_ptr<cmMakefile> mf(
-    new cmMakefile(&ggi, cm.GetCurrentSnapshot()));
-  cmsys::auto_ptr<cmLocalGenerator> lg(ggi.CreateLocalGenerator(mf.get()));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&ggi, cm.GetCurrentSnapshot()));
+  CM_AUTO_PTR<cmLocalGenerator> lg(ggi.CreateLocalGenerator(mf.get()));
 
   const char* inFileName = settingsFileName;
 
@@ -89,7 +89,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
   {                                                                           \
     const char* value = mf->GetDefinition(cmakeDefinition);                   \
     if (value) {                                                              \
-      var = value;                                                            \
+      (var) = value;                                                          \
     }                                                                         \
   }
 
@@ -102,7 +102,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
   {                                                                           \
     const char* value = mf->GetDefinition(cmakeDefinition);                   \
     if (value) {                                                              \
-      var = mf->IsOn(cmakeDefinition);                                        \
+      (var) = mf->IsOn(cmakeDefinition);                                      \
     }                                                                         \
   }
 
@@ -140,7 +140,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
 // which other targets depend on it.
 void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName)
 {
-  if (this->GenerateDependers == false) {
+  if (!this->GenerateDependers) {
     return;
   }
 
@@ -149,11 +149,11 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName)
   for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
          this->TargetPtrs.begin();
        ptrIt != this->TargetPtrs.end(); ++ptrIt) {
-    if (ptrIt->second == NULL) {
+    if (ptrIt->second == CM_NULLPTR) {
       continue;
     }
 
-    if (this->GenerateForTargetType(ptrIt->second->GetType()) == false) {
+    if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
       continue;
     }
 
@@ -184,7 +184,7 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName)
 // on which targets it depends.
 void cmGraphVizWriter::WritePerTargetFiles(const char* fileName)
 {
-  if (this->GeneratePerTarget == false) {
+  if (!this->GeneratePerTarget) {
     return;
   }
 
@@ -193,11 +193,11 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName)
   for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
          this->TargetPtrs.begin();
        ptrIt != this->TargetPtrs.end(); ++ptrIt) {
-    if (ptrIt->second == NULL) {
+    if (ptrIt->second == CM_NULLPTR) {
       continue;
     }
 
-    if (this->GenerateForTargetType(ptrIt->second->GetType()) == false) {
+    if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
       continue;
     }
 
@@ -239,11 +239,11 @@ void cmGraphVizWriter::WriteGlobalFile(const char* fileName)
   for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
          this->TargetPtrs.begin();
        ptrIt != this->TargetPtrs.end(); ++ptrIt) {
-    if (ptrIt->second == NULL) {
+    if (ptrIt->second == CM_NULLPTR) {
       continue;
     }
 
-    if (this->GenerateForTargetType(ptrIt->second->GetType()) == false) {
+    if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
       continue;
     }
 
@@ -278,7 +278,7 @@ void cmGraphVizWriter::WriteConnections(
 
   this->WriteNode(targetName, targetPtrIt->second, insertedNodes, str);
 
-  if (targetPtrIt->second == NULL) // it's an external library
+  if (targetPtrIt->second == CM_NULLPTR) // it's an external library
   {
     return;
   }
@@ -329,7 +329,7 @@ void cmGraphVizWriter::WriteDependerConnections(
 
   this->WriteNode(targetName, targetPtrIt->second, insertedNodes, str);
 
-  if (targetPtrIt->second == NULL) // it's an external library
+  if (targetPtrIt->second == CM_NULLPTR) // it's an external library
   {
     return;
   }
@@ -340,11 +340,11 @@ void cmGraphVizWriter::WriteDependerConnections(
   for (std::map<std::string, const cmGeneratorTarget*>::const_iterator
          dependerIt = this->TargetPtrs.begin();
        dependerIt != this->TargetPtrs.end(); ++dependerIt) {
-    if (dependerIt->second == NULL) {
+    if (dependerIt->second == CM_NULLPTR) {
       continue;
     }
 
-    if (this->GenerateForTargetType(dependerIt->second->GetType()) == false) {
+    if (!this->GenerateForTargetType(dependerIt->second->GetType())) {
       continue;
     }
 
@@ -403,7 +403,7 @@ void cmGraphVizWriter::WriteNode(const std::string& targetName,
 
 void cmGraphVizWriter::CollectTargetsAndLibs()
 {
-  if (this->HaveTargetsAndLibs == false) {
+  if (!this->HaveTargetsAndLibs) {
     this->HaveTargetsAndLibs = true;
     int cnt = this->CollectAllTargets();
     if (this->GenerateForExternals) {
@@ -427,7 +427,7 @@ int cmGraphVizWriter::CollectAllTargets()
         // Skip ignored targets
         continue;
       }
-      // std::cout << "Found target: " << tit->first.c_str() << std::endl;
+      // std::cout << "Found target: " << tit->first << std::endl;
       std::ostringstream ostr;
       ostr << this->GraphNodePrefix << cnt++;
       this->TargetNamesNodes[realTargetName] = ostr.str();
@@ -468,8 +468,8 @@ int cmGraphVizWriter::CollectAllExternalLibs(int cnt)
           std::ostringstream ostr;
           ostr << this->GraphNodePrefix << cnt++;
           this->TargetNamesNodes[libName] = ostr.str();
-          this->TargetPtrs[libName] = NULL;
-          // str << "    \"" << ostr.c_str() << "\" [ label=\"" << libName
+          this->TargetPtrs[libName] = CM_NULLPTR;
+          // str << "    \"" << ostr << "\" [ label=\"" << libName
           // <<  "\" shape=\"ellipse\"];" << std::endl;
         }
       }
diff --git a/Source/cmGraphVizWriter.h b/Source/cmGraphVizWriter.h
index c73d82d..0efe2b7 100644
--- a/Source/cmGraphVizWriter.h
+++ b/Source/cmGraphVizWriter.h
@@ -1,24 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef CMGRAPHVIZWRITER_H
 #define CMGRAPHVIZWRITER_H
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include "cmState.h"
 
-#include "cmGeneratedFileStream.h"
-#include "cmLocalGenerator.h"
 #include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
+class cmGeneratedFileStream;
 class cmGeneratorTarget;
+class cmLocalGenerator;
 
 /** This class implements writing files for graphviz (dot) for graphs
  * representing the dependencies between the targets in the project. */
diff --git a/Source/cmHexFileConverter.cxx b/Source/cmHexFileConverter.cxx
index 9609e95..e121ece 100644
--- a/Source/cmHexFileConverter.cxx
+++ b/Source/cmHexFileConverter.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmHexFileConverter.h"
 
 #include <stdio.h>
@@ -28,7 +19,7 @@ static bool cm_IsHexChar(char c)
 
 static unsigned int ChompStrlen(const char* line)
 {
-  if (line == 0) {
+  if (line == CM_NULLPTR) {
     return 0;
   }
   unsigned int length = static_cast<unsigned int>(strlen(line));
@@ -89,7 +80,8 @@ static bool ConvertMotorolaSrecLine(const char* buf, FILE* outFile)
   if ((buf[1] == '5') || (buf[1] == '7') || (buf[1] == '8') ||
       (buf[1] == '9')) {
     return true;
-  } else if (buf[1] == '1') {
+  }
+  if (buf[1] == '1') {
     dataStart = 8;
   } else if (buf[1] == '2') {
     dataStart = 10;
@@ -144,7 +136,7 @@ cmHexFileConverter::FileType cmHexFileConverter::DetermineFileType(
 {
   char buf[1024];
   FILE* inFile = cmsys::SystemTools::Fopen(inFileName, "rb");
-  if (inFile == 0) {
+  if (inFile == CM_NULLPTR) {
     return Binary;
   }
 
@@ -193,11 +185,11 @@ bool cmHexFileConverter::TryConvert(const char* inFileName,
   // try to open the file
   FILE* inFile = cmsys::SystemTools::Fopen(inFileName, "rb");
   FILE* outFile = cmsys::SystemTools::Fopen(outFileName, "wb");
-  if ((inFile == 0) || (outFile == 0)) {
-    if (inFile != 0) {
+  if ((inFile == CM_NULLPTR) || (outFile == CM_NULLPTR)) {
+    if (inFile != CM_NULLPTR) {
       fclose(inFile);
     }
-    if (outFile != 0) {
+    if (outFile != CM_NULLPTR) {
       fclose(outFile);
     }
     return false;
@@ -206,7 +198,7 @@ bool cmHexFileConverter::TryConvert(const char* inFileName,
   // convert them line by line
   bool success = false;
   char buf[1024];
-  while (fgets(buf, 1024, inFile) != 0) {
+  while (fgets(buf, 1024, inFile) != CM_NULLPTR) {
     if (type == MotorolaSrec) {
       success = ConvertMotorolaSrecLine(buf, outFile);
     } else if (type == IntelHex) {
diff --git a/Source/cmHexFileConverter.h b/Source/cmHexFileConverter.h
index 56fa9b1..cb550bb 100644
--- a/Source/cmHexFileConverter.h
+++ b/Source/cmHexFileConverter.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmHexFileConverter_h
 #define cmHexFileConverter_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmHexFileConverter
diff --git a/Source/cmIDEFlagTable.h b/Source/cmIDEFlagTable.h
index e8a6e38..64ade76 100644
--- a/Source/cmIDEFlagTable.h
+++ b/Source/cmIDEFlagTable.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIDEFlagTable_h
 #define cmIDEFlagTable_h
 
diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx
index 9f4b537..286076f 100644
--- a/Source/cmIDEOptions.cxx
+++ b/Source/cmIDEOptions.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIDEOptions.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h
index fac7d4e..1067c40 100644
--- a/Source/cmIDEOptions.h
+++ b/Source/cmIDEOptions.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIDEOptions_h
 #define cmIDEOptions_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include "cmIDEFlagTable.h"
diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx
index 45395d1..a2dec55 100644
--- a/Source/cmIfCommand.cxx
+++ b/Source/cmIfCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIfCommand.h"
 
 #include "cmOutputConverter.h"
@@ -46,8 +37,7 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
     // if this is the endif for this if statement, then start executing
     if (!this->ScopeDepth) {
       // Remove the function blocker for this scope or bail.
-      cmsys::auto_ptr<cmFunctionBlocker> fb(
-        mf.RemoveFunctionBlocker(this, lff));
+      CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
       if (!fb.get()) {
         return false;
       }
@@ -185,15 +175,14 @@ bool cmIfCommand::InvokeInitialPass(
     conditionEvaluator.IsTrue(expandedArguments, errorString, status);
 
   if (!errorString.empty()) {
-    std::string err = cmIfCommandError(expandedArguments);
+    std::string err = "if " + cmIfCommandError(expandedArguments);
     err += errorString;
     if (status == cmake::FATAL_ERROR) {
-      this->SetError(err);
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR, err);
       cmSystemTools::SetFatalErrorOccured();
-      return false;
-    } else {
-      this->Makefile->IssueMessage(status, err);
+      return true;
     }
+    this->Makefile->IssueMessage(status, err);
   }
 
   cmIfFunctionBlocker* f = new cmIfFunctionBlocker();
diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h
index 54200df..f449023 100644
--- a/Source/cmIfCommand.h
+++ b/Source/cmIfCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIfCommand_h
 #define cmIfCommand_h
 
@@ -24,10 +15,10 @@ public:
     this->HasRun = false;
     this->ScopeDepth = 0;
   }
-  virtual ~cmIfFunctionBlocker() {}
-  virtual bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
-                                 cmExecutionStatus&);
-  virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf);
+  ~cmIfFunctionBlocker() CM_OVERRIDE {}
+  bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
+                         cmExecutionStatus&) CM_OVERRIDE;
+  bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
 
   std::vector<cmListFileArgument> Args;
   std::vector<cmListFileFunction> Functions;
@@ -43,20 +34,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmIfCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmIfCommand; }
 
   /**
    * This overrides the default InvokeInitialPass implementation.
    * It records the arguments before expansion.
    */
-  virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -64,12 +56,12 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "if"; }
+  std::string GetName() const CM_OVERRIDE { return "if"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   // Filter the given variable definition based on policy CMP0054.
   static const char* GetDefinitionIfUnquoted(
diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx
index cb9b74d..acf51a7 100644
--- a/Source/cmIncludeCommand.cxx
+++ b/Source/cmIncludeCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeCommand.h"
 
 // cmIncludeCommand
 bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
 {
-  if (args.size() < 1 || args.size() > 4) {
+  if (args.empty() || args.size() > 4) {
     this->SetError("called with wrong number of arguments.  "
                    "include() only takes one file.");
     return false;
@@ -77,7 +68,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
 
   cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
   if (gg->IsExportedTargetsFile(fname_abs)) {
-    const char* modal = 0;
+    const char* modal = CM_NULLPTR;
     std::ostringstream e;
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
 
diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h
index e319dbd..7ff7b9d 100644
--- a/Source/cmIncludeCommand.h
+++ b/Source/cmIncludeCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIncludeCommand_h
 #define cmIncludeCommand_h
 
@@ -26,24 +17,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmIncludeCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmIncludeCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "include"; }
+  std::string GetName() const CM_OVERRIDE { return "include"; }
 
   cmTypeMacro(cmIncludeCommand, cmCommand);
 };
diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx
index cafdba7..f37f1ca 100644
--- a/Source/cmIncludeDirectoryCommand.cxx
+++ b/Source/cmIncludeDirectoryCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeDirectoryCommand.h"
 
 // cmIncludeDirectoryCommand
 bool cmIncludeDirectoryCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmIncludeDirectoryCommand.h b/Source/cmIncludeDirectoryCommand.h
index 952294b..46e433a 100644
--- a/Source/cmIncludeDirectoryCommand.h
+++ b/Source/cmIncludeDirectoryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIncludeDirectoryCommand_h
 #define cmIncludeDirectoryCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmIncludeDirectoryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmIncludeDirectoryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "include_directories"; }
+  std::string GetName() const CM_OVERRIDE { return "include_directories"; }
 
   cmTypeMacro(cmIncludeDirectoryCommand, cmCommand);
 
diff --git a/Source/cmIncludeExternalMSProjectCommand.cxx b/Source/cmIncludeExternalMSProjectCommand.cxx
index 9720d63..166bc7c 100644
--- a/Source/cmIncludeExternalMSProjectCommand.cxx
+++ b/Source/cmIncludeExternalMSProjectCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeExternalMSProjectCommand.h"
 
 // cmIncludeExternalMSProjectCommand
diff --git a/Source/cmIncludeExternalMSProjectCommand.h b/Source/cmIncludeExternalMSProjectCommand.h
index 999eb9e..9401016 100644
--- a/Source/cmIncludeExternalMSProjectCommand.h
+++ b/Source/cmIncludeExternalMSProjectCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIncludeExternalMSProjectCommand_h
 #define cmIncludeExternalMSProjectCommand_h
 
@@ -27,19 +18,25 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmIncludeExternalMSProjectCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmIncludeExternalMSProjectCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "include_external_msproject"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "include_external_msproject";
+  }
 
   cmTypeMacro(cmIncludeExternalMSProjectCommand, cmCommand);
 };
diff --git a/Source/cmIncludeRegularExpressionCommand.cxx b/Source/cmIncludeRegularExpressionCommand.cxx
index 2473dff..6dc20a0 100644
--- a/Source/cmIncludeRegularExpressionCommand.cxx
+++ b/Source/cmIncludeRegularExpressionCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeRegularExpressionCommand.h"
 
 // cmIncludeRegularExpressionCommand
 bool cmIncludeRegularExpressionCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if ((args.size() < 1) || (args.size() > 2)) {
+  if ((args.empty()) || (args.size() > 2)) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmIncludeRegularExpressionCommand.h b/Source/cmIncludeRegularExpressionCommand.h
index 1071a7a..648bce2 100644
--- a/Source/cmIncludeRegularExpressionCommand.h
+++ b/Source/cmIncludeRegularExpressionCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmIncludeRegularExpressionCommand_h
 #define cmIncludeRegularExpressionCommand_h
 
@@ -26,19 +17,25 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmIncludeRegularExpressionCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmIncludeRegularExpressionCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "include_regular_expression"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "include_regular_expression";
+  }
 
   cmTypeMacro(cmIncludeRegularExpressionCommand, cmCommand);
 };
diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx
index e9de8df..f040a4e 100644
--- a/Source/cmInstallCommand.cxx
+++ b/Source/cmInstallCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallCommand.h"
 
 #include "cmExportSet.h"
@@ -71,19 +62,28 @@ bool cmInstallCommand::InitialPass(std::vector<std::string> const& args,
   // Switch among the command modes.
   if (args[0] == "SCRIPT") {
     return this->HandleScriptMode(args);
-  } else if (args[0] == "CODE") {
+  }
+  if (args[0] == "CODE") {
     return this->HandleScriptMode(args);
-  } else if (args[0] == "TARGETS") {
+  }
+  if (args[0] == "TARGETS") {
     return this->HandleTargetsMode(args);
-  } else if (args[0] == "FILES") {
+  }
+  if (args[0] == "FILES") {
     return this->HandleFilesMode(args);
-  } else if (args[0] == "PROGRAMS") {
+  }
+  if (args[0] == "PROGRAMS") {
     return this->HandleFilesMode(args);
-  } else if (args[0] == "DIRECTORY") {
+  }
+  if (args[0] == "DIRECTORY") {
     return this->HandleDirectoryMode(args);
-  } else if (args[0] == "EXPORT") {
+  }
+  if (args[0] == "EXPORT") {
     return this->HandleExportMode(args);
   }
+  if (args[0] == "EXPORT_ANDROID_MK") {
+    return this->HandleExportAndroidMKMode(args);
+  }
 
   // Unknown mode.
   std::string e = "called with unknown mode ";
@@ -186,7 +186,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
 
   cmCommandArgumentsHelper argHelper;
   cmCommandArgumentGroup group;
-  cmCAStringVector genericArgVector(&argHelper, 0);
+  cmCAStringVector genericArgVector(&argHelper, CM_NULLPTR);
   cmCAStringVector archiveArgVector(&argHelper, "ARCHIVE", &group);
   cmCAStringVector libraryArgVector(&argHelper, "LIBRARY", &group);
   cmCAStringVector runtimeArgVector(&argHelper, "RUNTIME", &group);
@@ -197,10 +197,10 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
                                           &group);
   cmCAStringVector publicHeaderArgVector(&argHelper, "PUBLIC_HEADER", &group);
   cmCAStringVector resourceArgVector(&argHelper, "RESOURCE", &group);
-  genericArgVector.Follows(0);
+  genericArgVector.Follows(CM_NULLPTR);
   group.Follows(&genericArgVector);
 
-  argHelper.Parse(&args, 0);
+  argHelper.Parse(&args, CM_NULLPTR);
 
   // now parse the generic args (i.e. the ones not specialized on LIBRARY/
   // ARCHIVE, RUNTIME etc. (see above)
@@ -210,7 +210,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
   cmCAStringVector targetList(&genericArgs.Parser, "TARGETS");
   cmCAString exports(&genericArgs.Parser, "EXPORT",
                      &genericArgs.ArgumentGroup);
-  targetList.Follows(0);
+  targetList.Follows(CM_NULLPTR);
   genericArgs.ArgumentGroup.Follows(&targetList);
   genericArgs.Parse(&genericArgVector.GetVector(), &unknownArgs);
   bool success = genericArgs.Finalize();
@@ -338,7 +338,8 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
           << "\" which is not an executable, library, or module.";
         this->SetError(e.str());
         return false;
-      } else if (target->GetType() == cmState::OBJECT_LIBRARY) {
+      }
+      if (target->GetType() == cmState::OBJECT_LIBRARY) {
         std::ostringstream e;
         e << "TARGETS given OBJECT library \"" << (*targetIt)
           << "\" which may not be installed.";
@@ -373,14 +374,14 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
        ti != targets.end(); ++ti) {
     // Handle each target type.
     cmTarget& target = *(*ti);
-    cmInstallTargetGenerator* archiveGenerator = 0;
-    cmInstallTargetGenerator* libraryGenerator = 0;
-    cmInstallTargetGenerator* runtimeGenerator = 0;
-    cmInstallTargetGenerator* frameworkGenerator = 0;
-    cmInstallTargetGenerator* bundleGenerator = 0;
-    cmInstallFilesGenerator* privateHeaderGenerator = 0;
-    cmInstallFilesGenerator* publicHeaderGenerator = 0;
-    cmInstallFilesGenerator* resourceGenerator = 0;
+    cmInstallTargetGenerator* archiveGenerator = CM_NULLPTR;
+    cmInstallTargetGenerator* libraryGenerator = CM_NULLPTR;
+    cmInstallTargetGenerator* runtimeGenerator = CM_NULLPTR;
+    cmInstallTargetGenerator* frameworkGenerator = CM_NULLPTR;
+    cmInstallTargetGenerator* bundleGenerator = CM_NULLPTR;
+    cmInstallFilesGenerator* privateHeaderGenerator = CM_NULLPTR;
+    cmInstallFilesGenerator* publicHeaderGenerator = CM_NULLPTR;
+    cmInstallFilesGenerator* resourceGenerator = CM_NULLPTR;
 
     // Track whether this is a namelink-only rule.
     bool namelinkOnly = false;
@@ -407,7 +408,8 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
             runtimeGenerator =
               CreateInstallTargetGenerator(target, runtimeArgs, false);
           }
-          if ((archiveGenerator == 0) && (runtimeGenerator == 0)) {
+          if ((archiveGenerator == CM_NULLPTR) &&
+              (runtimeGenerator == CM_NULLPTR)) {
             this->SetError("Library TARGETS given no DESTINATION!");
             return false;
           }
@@ -621,14 +623,15 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
     }
 
     // Keep track of whether we're installing anything in each category
-    installsArchive = installsArchive || archiveGenerator != 0;
-    installsLibrary = installsLibrary || libraryGenerator != 0;
-    installsRuntime = installsRuntime || runtimeGenerator != 0;
-    installsFramework = installsFramework || frameworkGenerator != 0;
-    installsBundle = installsBundle || bundleGenerator != 0;
+    installsArchive = installsArchive || archiveGenerator != CM_NULLPTR;
+    installsLibrary = installsLibrary || libraryGenerator != CM_NULLPTR;
+    installsRuntime = installsRuntime || runtimeGenerator != CM_NULLPTR;
+    installsFramework = installsFramework || frameworkGenerator != CM_NULLPTR;
+    installsBundle = installsBundle || bundleGenerator != CM_NULLPTR;
     installsPrivateHeader =
-      installsPrivateHeader || privateHeaderGenerator != 0;
-    installsPublicHeader = installsPublicHeader || publicHeaderGenerator != 0;
+      installsPrivateHeader || privateHeaderGenerator != CM_NULLPTR;
+    installsPublicHeader =
+      installsPublicHeader || publicHeaderGenerator != CM_NULLPTR;
     installsResource = installsResource || resourceGenerator;
 
     this->Makefile->AddInstallGenerator(archiveGenerator);
@@ -704,7 +707,7 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args)
   bool programs = (args[0] == "PROGRAMS");
   cmInstallCommandArguments ica(this->DefaultComponentName);
   cmCAStringVector files(&ica.Parser, programs ? "PROGRAMS" : "FILES");
-  files.Follows(0);
+  files.Follows(CM_NULLPTR);
   ica.ArgumentGroup.Follows(&files);
   std::vector<std::string> unknownArgs;
   ica.Parse(&args, &unknownArgs);
@@ -744,7 +747,7 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args)
   for (std::vector<std::string>::const_iterator fileIt = filesVector.begin();
        fileIt != filesVector.end(); ++fileIt) {
     if (gg->IsExportedTargetsFile(*fileIt)) {
-      const char* modal = 0;
+      const char* modal = CM_NULLPTR;
       std::ostringstream e;
       cmake::MessageType messageType = cmake::AUTHOR_WARNING;
 
@@ -820,7 +823,7 @@ bool cmInstallCommand::HandleDirectoryMode(
   bool exclude_from_all = false;
   bool message_never = false;
   std::vector<std::string> dirs;
-  const char* destination = 0;
+  const char* destination = CM_NULLPTR;
   std::string permissions_file;
   std::string permissions_dir;
   std::vector<std::string> configurations;
@@ -974,7 +977,8 @@ bool cmInstallCommand::HandleDirectoryMode(
     } else if (doing == DoingDirs) {
       // Convert this directory to a full path.
       std::string dir = args[i];
-      if (!cmSystemTools::FileIsFullPath(dir.c_str())) {
+      std::string::size_type gpos = cmGeneratorExpression::Find(dir);
+      if (gpos != 0 && !cmSystemTools::FileIsFullPath(dir.c_str())) {
         dir = this->Makefile->GetCurrentSourceDirectory();
         dir += "/";
         dir += args[i];
@@ -1094,6 +1098,100 @@ bool cmInstallCommand::HandleDirectoryMode(
   return true;
 }
 
+bool cmInstallCommand::HandleExportAndroidMKMode(
+  std::vector<std::string> const& args)
+{
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  // This is the EXPORT mode.
+  cmInstallCommandArguments ica(this->DefaultComponentName);
+  cmCAString exp(&ica.Parser, "EXPORT_ANDROID_MK");
+  cmCAString name_space(&ica.Parser, "NAMESPACE", &ica.ArgumentGroup);
+  cmCAEnabler exportOld(&ica.Parser, "EXPORT_LINK_INTERFACE_LIBRARIES",
+                        &ica.ArgumentGroup);
+  cmCAString filename(&ica.Parser, "FILE", &ica.ArgumentGroup);
+  exp.Follows(CM_NULLPTR);
+
+  ica.ArgumentGroup.Follows(&exp);
+  std::vector<std::string> unknownArgs;
+  ica.Parse(&args, &unknownArgs);
+
+  if (!unknownArgs.empty()) {
+    // Unknown argument.
+    std::ostringstream e;
+    e << args[0] << " given unknown argument \"" << unknownArgs[0] << "\".";
+    this->SetError(e.str());
+    return false;
+  }
+
+  if (!ica.Finalize()) {
+    return false;
+  }
+
+  // Make sure there is a destination.
+  if (ica.GetDestination().empty()) {
+    // A destination is required.
+    std::ostringstream e;
+    e << args[0] << " given no DESTINATION!";
+    this->SetError(e.str());
+    return false;
+  }
+
+  // Check the file name.
+  std::string fname = filename.GetString();
+  if (fname.find_first_of(":/\\") != fname.npos) {
+    std::ostringstream e;
+    e << args[0] << " given invalid export file name \"" << fname << "\".  "
+      << "The FILE argument may not contain a path.  "
+      << "Specify the path in the DESTINATION argument.";
+    this->SetError(e.str());
+    return false;
+  }
+
+  // Check the file extension.
+  if (!fname.empty() &&
+      cmSystemTools::GetFilenameLastExtension(fname) != ".mk") {
+    std::ostringstream e;
+    e << args[0] << " given invalid export file name \"" << fname << "\".  "
+      << "The FILE argument must specify a name ending in \".mk\".";
+    this->SetError(e.str());
+    return false;
+  }
+  if (fname.find_first_of(":/\\") != fname.npos) {
+    std::ostringstream e;
+    e << args[0] << " given export name \"" << exp.GetString() << "\".  "
+      << "This name cannot be safely converted to a file name.  "
+      << "Specify a different export name or use the FILE option to set "
+      << "a file name explicitly.";
+    this->SetError(e.str());
+    return false;
+  }
+  // Use the default name
+  if (fname.empty()) {
+    fname = "Android.mk";
+  }
+
+  cmExportSet* exportSet =
+    this->Makefile->GetGlobalGenerator()->GetExportSets()[exp.GetString()];
+
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(this->Makefile);
+
+  // Create the export install generator.
+  cmInstallExportGenerator* exportGenerator = new cmInstallExportGenerator(
+    exportSet, ica.GetDestination().c_str(), ica.GetPermissions().c_str(),
+    ica.GetConfigurations(), ica.GetComponent().c_str(), message,
+    ica.GetExcludeFromAll(), fname.c_str(), name_space.GetCString(),
+    exportOld.IsEnabled(), true);
+  this->Makefile->AddInstallGenerator(exportGenerator);
+
+  return true;
+#else
+  static_cast<void>(args);
+  this->SetError("EXPORT_ANDROID_MK not supported in bootstrap cmake");
+  return false;
+#endif
+}
+
 bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args)
 {
   // This is the EXPORT mode.
@@ -1103,7 +1201,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args)
   cmCAEnabler exportOld(&ica.Parser, "EXPORT_LINK_INTERFACE_LIBRARIES",
                         &ica.ArgumentGroup);
   cmCAString filename(&ica.Parser, "FILE", &ica.ArgumentGroup);
-  exp.Follows(0);
+  exp.Follows(CM_NULLPTR);
 
   ica.ArgumentGroup.Follows(&exp);
   std::vector<std::string> unknownArgs;
@@ -1200,7 +1298,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args)
     exportSet, ica.GetDestination().c_str(), ica.GetPermissions().c_str(),
     ica.GetConfigurations(), ica.GetComponent().c_str(), message,
     ica.GetExcludeFromAll(), fname.c_str(), name_space.GetCString(),
-    exportOld.IsEnabled());
+    exportOld.IsEnabled(), false);
   this->Makefile->AddInstallGenerator(exportGenerator);
 
   return true;
diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h
index 93aca45..6f785ae 100644
--- a/Source/cmInstallCommand.h
+++ b/Source/cmInstallCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallCommand_h
 #define cmInstallCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmInstallCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmInstallCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "install"; }
+  std::string GetName() const CM_OVERRIDE { return "install"; }
 
   cmTypeMacro(cmInstallCommand, cmCommand);
 
@@ -48,6 +39,7 @@ private:
   bool HandleFilesMode(std::vector<std::string> const& args);
   bool HandleDirectoryMode(std::vector<std::string> const& args);
   bool HandleExportMode(std::vector<std::string> const& args);
+  bool HandleExportAndroidMKMode(std::vector<std::string> const& args);
   bool MakeFilesFullPath(const char* modeName,
                          const std::vector<std::string>& relFiles,
                          std::vector<std::string>& absFiles);
diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx
index 57e37a3..de6919b 100644
--- a/Source/cmInstallCommandArguments.cxx
+++ b/Source/cmInstallCommandArguments.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallCommandArguments.h"
 
 #include "cmSystemTools.h"
@@ -17,7 +8,7 @@
 const char* cmInstallCommandArguments::PermissionsTable[] = {
   "OWNER_READ",    "OWNER_WRITE",   "OWNER_EXECUTE", "GROUP_READ",
   "GROUP_WRITE",   "GROUP_EXECUTE", "WORLD_READ",    "WORLD_WRITE",
-  "WORLD_EXECUTE", "SETUID",        "SETGID",        0
+  "WORLD_EXECUTE", "SETUID",        "SETGID",        CM_NULLPTR
 };
 
 const std::string cmInstallCommandArguments::EmptyString;
@@ -35,7 +26,7 @@ cmInstallCommandArguments::cmInstallCommandArguments(
   , Optional(&Parser, "OPTIONAL", &ArgumentGroup)
   , NamelinkOnly(&Parser, "NAMELINK_ONLY", &ArgumentGroup)
   , NamelinkSkip(&Parser, "NAMELINK_SKIP", &ArgumentGroup)
-  , GenericArguments(0)
+  , GenericArguments(CM_NULLPTR)
   , DefaultComponentName(defaultComponent)
 {
 }
@@ -45,7 +36,7 @@ const std::string& cmInstallCommandArguments::GetDestination() const
   if (!this->DestinationString.empty()) {
     return this->DestinationString;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetDestination();
   }
   return this->EmptyString;
@@ -56,7 +47,7 @@ const std::string& cmInstallCommandArguments::GetComponent() const
   if (!this->Component.GetString().empty()) {
     return this->Component.GetString();
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetComponent();
   }
   if (!this->DefaultComponentName.empty()) {
@@ -71,7 +62,7 @@ const std::string& cmInstallCommandArguments::GetRename() const
   if (!this->Rename.GetString().empty()) {
     return this->Rename.GetString();
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetRename();
   }
   return this->EmptyString;
@@ -82,7 +73,7 @@ const std::string& cmInstallCommandArguments::GetPermissions() const
   if (!this->PermissionsString.empty()) {
     return this->PermissionsString;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetPermissions();
   }
   return this->EmptyString;
@@ -93,7 +84,7 @@ bool cmInstallCommandArguments::GetOptional() const
   if (this->Optional.IsEnabled()) {
     return true;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetOptional();
   }
   return false;
@@ -104,7 +95,7 @@ bool cmInstallCommandArguments::GetExcludeFromAll() const
   if (this->ExcludeFromAll.IsEnabled()) {
     return true;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetExcludeFromAll();
   }
   return false;
@@ -115,7 +106,7 @@ bool cmInstallCommandArguments::GetNamelinkOnly() const
   if (this->NamelinkOnly.IsEnabled()) {
     return true;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetNamelinkOnly();
   }
   return false;
@@ -126,7 +117,7 @@ bool cmInstallCommandArguments::GetNamelinkSkip() const
   if (this->NamelinkSkip.IsEnabled()) {
     return true;
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetNamelinkSkip();
   }
   return false;
@@ -138,7 +129,7 @@ const std::vector<std::string>& cmInstallCommandArguments::GetConfigurations()
   if (!this->Configurations.GetVector().empty()) {
     return this->Configurations.GetVector();
   }
-  if (this->GenericArguments != 0) {
+  if (this->GenericArguments != CM_NULLPTR) {
     return this->GenericArguments->GetConfigurations();
   }
   return this->Configurations.GetVector();
diff --git a/Source/cmInstallCommandArguments.h b/Source/cmInstallCommandArguments.h
index 6ccb3e8..82c2310 100644
--- a/Source/cmInstallCommandArguments.h
+++ b/Source/cmInstallCommandArguments.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallCommandArguments_h
 #define cmInstallCommandArguments_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include "cmCommandArgumentsHelper.h"
diff --git a/Source/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx
index 671ab4c..dfb3aeb 100644
--- a/Source/cmInstallDirectoryGenerator.cxx
+++ b/Source/cmInstallDirectoryGenerator.cxx
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallDirectoryGenerator.h"
 
 #include "cmGeneratorExpression.h"
+#include "cmInstallType.h"
 #include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 
 cmInstallDirectoryGenerator::cmInstallDirectoryGenerator(
   std::vector<std::string> const& dirs, const char* dest,
@@ -22,7 +17,7 @@ cmInstallDirectoryGenerator::cmInstallDirectoryGenerator(
   bool optional)
   : cmInstallGenerator(dest, configurations, component, message,
                        exclude_from_all)
-  , LocalGenerator(0)
+  , LocalGenerator(CM_NULLPTR)
   , Directories(dirs)
   , FilePermissions(file_permissions)
   , DirPermissions(dir_permissions)
@@ -69,10 +64,20 @@ void cmInstallDirectoryGenerator::GenerateScriptForConfig(
   cmGeneratorExpression ge;
   for (std::vector<std::string>::const_iterator i = this->Directories.begin();
        i != this->Directories.end(); ++i) {
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
     cmSystemTools::ExpandListArgument(
       cge->Evaluate(this->LocalGenerator, config), dirs);
   }
+
+  // Make sure all dirs have absolute paths.
+  cmMakefile const& mf = *this->LocalGenerator->GetMakefile();
+  for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end();
+       ++i) {
+    if (!cmSystemTools::FileIsFullPath(i->c_str())) {
+      *i = std::string(mf.GetCurrentSourceDirectory()) + "/" + *i;
+    }
+  }
+
   this->AddDirectoryInstallRule(os, config, indent, dirs);
 }
 
@@ -81,7 +86,7 @@ void cmInstallDirectoryGenerator::AddDirectoryInstallRule(
   std::vector<std::string> const& dirs)
 {
   // Write code to install the directories.
-  const char* no_rename = 0;
+  const char* no_rename = CM_NULLPTR;
   this->AddInstallRule(os, this->GetDestination(config),
                        cmInstallType_DIRECTORY, dirs, this->Optional,
                        this->FilePermissions.c_str(),
diff --git a/Source/cmInstallDirectoryGenerator.h b/Source/cmInstallDirectoryGenerator.h
index 10d7c95..0518092 100644
--- a/Source/cmInstallDirectoryGenerator.h
+++ b/Source/cmInstallDirectoryGenerator.h
@@ -1,18 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallDirectoryGenerator_h
 #define cmInstallDirectoryGenerator_h
 
 #include "cmInstallGenerator.h"
+#include "cmScriptGenerator.h"
+
+#include <cmConfigure.h>
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+class cmLocalGenerator;
 
 /** \class cmInstallDirectoryGenerator
  * \brief Generate directory installation rules.
@@ -27,17 +26,17 @@ public:
                               const char* component, MessageLevel message,
                               bool exclude_from_all, const char* literal_args,
                               bool optional = false);
-  virtual ~cmInstallDirectoryGenerator();
+  ~cmInstallDirectoryGenerator() CM_OVERRIDE;
 
-  void Compute(cmLocalGenerator* lg);
+  void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
 
   std::string GetDestination(std::string const& config) const;
 
 protected:
-  virtual void GenerateScriptActions(std::ostream& os, Indent const& indent);
-  virtual void GenerateScriptForConfig(std::ostream& os,
-                                       const std::string& config,
-                                       Indent const& indent);
+  void GenerateScriptActions(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptForConfig(std::ostream& os, const std::string& config,
+                               Indent const& indent) CM_OVERRIDE;
   void AddDirectoryInstallRule(std::ostream& os, const std::string& config,
                                Indent const& indent,
                                std::vector<std::string> const& dirs);
diff --git a/Source/cmInstallExportAndroidMKGenerator.cxx b/Source/cmInstallExportAndroidMKGenerator.cxx
new file mode 100644
index 0000000..8eeaa9c
--- /dev/null
+++ b/Source/cmInstallExportAndroidMKGenerator.cxx
@@ -0,0 +1,140 @@
+
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmInstallExportAndroidMKGenerator.h"
+
+#include <stdio.h>
+
+#include "cmExportInstallFileGenerator.h"
+#include "cmExportSet.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmInstallFilesGenerator.h"
+#include "cmInstallTargetGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmake.h"
+
+cmInstallExportAndroidMKGenerator::cmInstallExportAndroidMKGenerator(
+  cmExportSet* exportSet, const char* destination,
+  const char* file_permissions, std::vector<std::string> const& configurations,
+  const char* component, MessageLevel message, bool exclude_from_all,
+  const char* filename, const char* name_space, bool exportOld)
+  : cmInstallExportGenerator(exportSet, destination, file_permissions,
+                             configurations, component, message,
+                             exclude_from_all, filename, name_space, exportOld)
+{
+}
+
+cmInstallExportAndroidMKGenerator::~cmInstallExportAndroidMKGenerator()
+{
+}
+
+void cmInstallExportAndroidMKGenerator::Compute(cmLocalGenerator* lg)
+{
+  this->LocalGenerator = lg;
+  this->ExportSet->Compute(lg);
+}
+
+void cmInstallExportAndroidMKGenerator::GenerateScript(std::ostream& os)
+{
+  // Skip empty sets.
+  if (ExportSet->GetTargetExports()->empty()) {
+    std::ostringstream e;
+    e << "INSTALL(EXPORT) given unknown export \"" << ExportSet->GetName()
+      << "\"";
+    cmSystemTools::Error(e.str().c_str());
+    return;
+  }
+
+  // Create the temporary directory in which to store the files.
+  this->ComputeTempDir();
+  cmSystemTools::MakeDirectory(this->TempDir.c_str());
+
+  // Construct a temporary location for the file.
+  this->MainImportFile = this->TempDir;
+  this->MainImportFile += "/";
+  this->MainImportFile += this->FileName;
+
+  // Generate the import file for this export set.
+  this->EFGen->SetExportFile(this->MainImportFile.c_str());
+  this->EFGen->SetNamespace(this->Namespace);
+  this->EFGen->SetExportOld(this->ExportOld);
+  if (this->ConfigurationTypes->empty()) {
+    if (!this->ConfigurationName.empty()) {
+      this->EFGen->AddConfiguration(this->ConfigurationName);
+    } else {
+      this->EFGen->AddConfiguration("");
+    }
+  } else {
+    for (std::vector<std::string>::const_iterator ci =
+           this->ConfigurationTypes->begin();
+         ci != this->ConfigurationTypes->end(); ++ci) {
+      this->EFGen->AddConfiguration(*ci);
+    }
+  }
+  this->EFGen->GenerateImportFile();
+
+  // Perform the main install script generation.
+  this->cmInstallGenerator::GenerateScript(os);
+}
+
+void cmInstallExportAndroidMKGenerator::GenerateScriptConfigs(
+  std::ostream& os, Indent const& indent)
+{
+  // Create the main install rules first.
+  this->cmInstallGenerator::GenerateScriptConfigs(os, indent);
+
+  // Now create a configuration-specific install rule for the import
+  // file of each configuration.
+  std::vector<std::string> files;
+  for (std::map<std::string, std::string>::const_iterator i =
+         this->EFGen->GetConfigImportFiles().begin();
+       i != this->EFGen->GetConfigImportFiles().end(); ++i) {
+    files.push_back(i->second);
+    std::string config_test = this->CreateConfigTest(i->first);
+    os << indent << "if(" << config_test << ")\n";
+    this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
+                         false, this->FilePermissions.c_str(), CM_NULLPTR,
+                         CM_NULLPTR, CM_NULLPTR, indent.Next());
+    os << indent << "endif()\n";
+    files.clear();
+  }
+}
+
+void cmInstallExportAndroidMKGenerator::GenerateScriptActions(
+  std::ostream& os, Indent const& indent)
+{
+  // Remove old per-configuration export files if the main changes.
+  std::string installedDir = "$ENV{DESTDIR}";
+  installedDir += this->ConvertToAbsoluteDestination(this->Destination);
+  installedDir += "/";
+  std::string installedFile = installedDir;
+  installedFile += this->FileName;
+  os << indent << "if(EXISTS \"" << installedFile << "\")\n";
+  Indent indentN = indent.Next();
+  Indent indentNN = indentN.Next();
+  Indent indentNNN = indentNN.Next();
+  /* clang-format off */
+  os << indentN << "file(DIFFERENT EXPORT_FILE_CHANGED FILES\n"
+     << indentN << "     \"" << installedFile << "\"\n"
+     << indentN << "     \"" << this->MainImportFile << "\")\n";
+  os << indentN << "if(EXPORT_FILE_CHANGED)\n";
+  os << indentNN << "file(GLOB OLD_CONFIG_FILES \"" << installedDir
+     << this->EFGen->GetConfigImportFileGlob() << "\")\n";
+  os << indentNN << "if(OLD_CONFIG_FILES)\n";
+  os << indentNNN << "message(STATUS \"Old export file \\\"" << installedFile
+     << "\\\" will be replaced.  Removing files [${OLD_CONFIG_FILES}].\")\n";
+  os << indentNNN << "file(REMOVE ${OLD_CONFIG_FILES})\n";
+  os << indentNN << "endif()\n";
+  os << indentN << "endif()\n";
+  os << indent << "endif()\n";
+  /* clang-format on */
+
+  // Install the main export file.
+  std::vector<std::string> files;
+  files.push_back(this->MainImportFile);
+  this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
+                       false, this->FilePermissions.c_str(), CM_NULLPTR,
+                       CM_NULLPTR, CM_NULLPTR, indent);
+}
diff --git a/Source/cmInstallExportAndroidMKGenerator.h b/Source/cmInstallExportAndroidMKGenerator.h
new file mode 100644
index 0000000..189084a
--- /dev/null
+++ b/Source/cmInstallExportAndroidMKGenerator.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 cmInstallExportAndroidMKGenerator_h
+#define cmInstallExportAndroidMKGenerator_h
+
+#include "cmInstallExportGenerator.h"
+
+class cmExportInstallFileGenerator;
+class cmInstallFilesGenerator;
+class cmInstallTargetGenerator;
+class cmExportSet;
+class cmMakefile;
+
+/** \class cmInstallExportAndroidMKGenerator
+ * \brief Generate rules for creating an export files.
+ */
+class cmInstallExportAndroidMKGenerator : public cmInstallExportGenerator
+{
+public:
+  cmInstallExportAndroidMKGenerator(
+    cmExportSet* exportSet, const char* dest, const char* file_permissions,
+    const std::vector<std::string>& configurations, const char* component,
+    MessageLevel message, bool exclude_from_all, const char* filename,
+    const char* name_space, bool exportOld);
+  ~cmInstallExportAndroidMKGenerator();
+
+  void Compute(cmLocalGenerator* lg);
+
+protected:
+  virtual void GenerateScript(std::ostream& os);
+  virtual void GenerateScriptConfigs(std::ostream& os, Indent const& indent);
+  virtual void GenerateScriptActions(std::ostream& os, Indent const& indent);
+  void GenerateImportFile(cmExportSet const* exportSet);
+  void GenerateImportFile(const char* config, cmExportSet const* exportSet);
+};
+
+#endif
diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx
index 2fef3a8..39fab4f 100644
--- a/Source/cmInstallExportGenerator.cxx
+++ b/Source/cmInstallExportGenerator.cxx
@@ -1,35 +1,27 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallExportGenerator.h"
 
-#include <stdio.h>
-
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmInstallTargetGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
-#include "cmake.h"
-
-#include "cmInstallFilesGenerator.h"
+#include <algorithm>
+#include <map>
+#include <sstream>
+#include <utility>
 
+#ifdef CMAKE_BUILD_WITH_CMAKE
+#include "cmExportInstallAndroidMKGenerator.h"
+#endif
 #include "cmExportInstallFileGenerator.h"
 #include "cmExportSet.h"
+#include "cmInstallType.h"
+#include "cmLocalGenerator.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
 
 cmInstallExportGenerator::cmInstallExportGenerator(
   cmExportSet* exportSet, const char* destination,
   const char* file_permissions, std::vector<std::string> const& configurations,
   const char* component, MessageLevel message, bool exclude_from_all,
-  const char* filename, const char* name_space, bool exportOld)
+  const char* filename, const char* name_space, bool exportOld, bool android)
   : cmInstallGenerator(destination, configurations, component, message,
                        exclude_from_all)
   , ExportSet(exportSet)
@@ -37,9 +29,15 @@ cmInstallExportGenerator::cmInstallExportGenerator(
   , FileName(filename)
   , Namespace(name_space)
   , ExportOld(exportOld)
-  , LocalGenerator(0)
+  , LocalGenerator(CM_NULLPTR)
 {
-  this->EFGen = new cmExportInstallFileGenerator(this);
+  if (android) {
+#ifdef CMAKE_BUILD_WITH_CMAKE
+    this->EFGen = new cmExportInstallAndroidMKGenerator(this);
+#endif
+  } else {
+    this->EFGen = new cmExportInstallFileGenerator(this);
+  }
   exportSet->AddInstallation(this);
 }
 
@@ -63,9 +61,8 @@ void cmInstallExportGenerator::ComputeTempDir()
   this->TempDir += "/Export";
   if (this->Destination.empty()) {
     return;
-  } else {
-    this->TempDir += "/";
   }
+  this->TempDir += "/";
 
   // Enforce a maximum length.
   bool useMD5 = false;
@@ -74,9 +71,12 @@ void cmInstallExportGenerator::ComputeTempDir()
 #else
   std::string::size_type const max_total_len = 1000;
 #endif
-  if (this->TempDir.size() < max_total_len) {
+  // Will generate files of the form "<temp-dir>/<base>-<config>.<ext>".
+  std::string::size_type const len = this->TempDir.size() + 1 +
+    this->FileName.size() + 1 + this->GetMaxConfigLength();
+  if (len < max_total_len) {
     // Keep the total path length below the limit.
-    std::string::size_type max_len = max_total_len - this->TempDir.size();
+    std::string::size_type const max_len = max_total_len - len;
     if (this->Destination.size() > max_len) {
       useMD5 = true;
     }
@@ -102,6 +102,26 @@ void cmInstallExportGenerator::ComputeTempDir()
   }
 }
 
+size_t cmInstallExportGenerator::GetMaxConfigLength() const
+{
+  // Always use at least 8 for "noconfig".
+  size_t len = 8;
+  if (this->ConfigurationTypes->empty()) {
+    if (this->ConfigurationName.size() > 8) {
+      len = this->ConfigurationName.size();
+    }
+  } else {
+    for (std::vector<std::string>::const_iterator ci =
+           this->ConfigurationTypes->begin();
+         ci != this->ConfigurationTypes->end(); ++ci) {
+      if (ci->size() > len) {
+        len = ci->size();
+      }
+    }
+  }
+  return len;
+}
+
 void cmInstallExportGenerator::GenerateScript(std::ostream& os)
 {
   // Skip empty sets.
@@ -161,8 +181,8 @@ void cmInstallExportGenerator::GenerateScriptConfigs(std::ostream& os,
     std::string config_test = this->CreateConfigTest(i->first);
     os << indent << "if(" << config_test << ")\n";
     this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
-                         false, this->FilePermissions.c_str(), 0, 0, 0,
-                         indent.Next());
+                         false, this->FilePermissions.c_str(), CM_NULLPTR,
+                         CM_NULLPTR, CM_NULLPTR, indent.Next());
     os << indent << "endif()\n";
     files.clear();
   }
@@ -201,5 +221,6 @@ void cmInstallExportGenerator::GenerateScriptActions(std::ostream& os,
   std::vector<std::string> files;
   files.push_back(this->MainImportFile);
   this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
-                       false, this->FilePermissions.c_str(), 0, 0, 0, indent);
+                       false, this->FilePermissions.c_str(), CM_NULLPTR,
+                       CM_NULLPTR, CM_NULLPTR, indent);
 }
diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h
index 256c0c9..b0fe889 100644
--- a/Source/cmInstallExportGenerator.h
+++ b/Source/cmInstallExportGenerator.h
@@ -1,24 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallExportGenerator_h
 #define cmInstallExportGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmInstallGenerator.h"
+#include "cmScriptGenerator.h"
+
+#include <iosfwd>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmExportInstallFileGenerator;
-class cmInstallFilesGenerator;
-class cmInstallTargetGenerator;
 class cmExportSet;
-class cmMakefile;
+class cmLocalGenerator;
 
 /** \class cmInstallExportGenerator
  * \brief Generate rules for creating an export files.
@@ -31,12 +28,13 @@ public:
                            const std::vector<std::string>& configurations,
                            const char* component, MessageLevel message,
                            bool exclude_from_all, const char* filename,
-                           const char* name_space, bool exportOld);
-  ~cmInstallExportGenerator();
+                           const char* name_space, bool exportOld,
+                           bool android);
+  ~cmInstallExportGenerator() CM_OVERRIDE;
 
   cmExportSet* GetExportSet() { return this->ExportSet; }
 
-  void Compute(cmLocalGenerator* lg);
+  void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
 
   cmLocalGenerator* GetLocalGenerator() const { return this->LocalGenerator; }
 
@@ -45,12 +43,15 @@ public:
   std::string const& GetDestination() const { return this->Destination; }
 
 protected:
-  virtual void GenerateScript(std::ostream& os);
-  virtual void GenerateScriptConfigs(std::ostream& os, Indent const& indent);
-  virtual void GenerateScriptActions(std::ostream& os, Indent const& indent);
+  void GenerateScript(std::ostream& os) CM_OVERRIDE;
+  void GenerateScriptConfigs(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptActions(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
   void GenerateImportFile(cmExportSet const* exportSet);
   void GenerateImportFile(const char* config, cmExportSet const* exportSet);
   void ComputeTempDir();
+  size_t GetMaxConfigLength() const;
 
   cmExportSet* ExportSet;
   std::string FilePermissions;
diff --git a/Source/cmInstallFilesCommand.cxx b/Source/cmInstallFilesCommand.cxx
index 64efe61..f072ff5 100644
--- a/Source/cmInstallFilesCommand.cxx
+++ b/Source/cmInstallFilesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallFilesCommand.h"
 
 #include "cmInstallFilesGenerator.h"
@@ -143,12 +134,12 @@ std::string cmInstallFilesCommand::FindInstallSource(const char* name) const
   if (cmSystemTools::FileExists(tb.c_str())) {
     // The file exists in the binary tree.  Use it.
     return tb;
-  } else if (cmSystemTools::FileExists(ts.c_str())) {
+  }
+  if (cmSystemTools::FileExists(ts.c_str())) {
     // The file exists in the source tree.  Use it.
     return ts;
-  } else {
-    // The file doesn't exist.  Assume it will be present in the
-    // binary tree when the install occurs.
-    return tb;
   }
+  // The file doesn't exist.  Assume it will be present in the
+  // binary tree when the install occurs.
+  return tb;
 }
diff --git a/Source/cmInstallFilesCommand.h b/Source/cmInstallFilesCommand.h
index 0d0388a..a80184a 100644
--- a/Source/cmInstallFilesCommand.h
+++ b/Source/cmInstallFilesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallFilesCommand_h
 #define cmInstallFilesCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmInstallFilesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmInstallFilesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "install_files"; }
+  std::string GetName() const CM_OVERRIDE { return "install_files"; }
 
   /**
    * This is called at the end after all the information
@@ -46,8 +37,8 @@ public:
    * not implement this method.  At this point, reading and
    * writing to the cache can be done.
    */
-  virtual void FinalPass();
-  virtual bool HasFinalPass() const { return !this->IsFilesForm; }
+  void FinalPass() CM_OVERRIDE;
+  bool HasFinalPass() const CM_OVERRIDE { return !this->IsFilesForm; }
 
   cmTypeMacro(cmInstallFilesCommand, cmCommand);
 
diff --git a/Source/cmInstallFilesGenerator.cxx b/Source/cmInstallFilesGenerator.cxx
index 8c1b357..7daea38 100644
--- a/Source/cmInstallFilesGenerator.cxx
+++ b/Source/cmInstallFilesGenerator.cxx
@@ -1,20 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallFilesGenerator.h"
 
 #include "cmGeneratorExpression.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
+#include "cmInstallType.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+
+class cmLocalGenerator;
 
 cmInstallFilesGenerator::cmInstallFilesGenerator(
   std::vector<std::string> const& files, const char* dest, bool programs,
@@ -23,7 +16,7 @@ cmInstallFilesGenerator::cmInstallFilesGenerator(
   const char* rename, bool optional)
   : cmInstallGenerator(dest, configurations, component, message,
                        exclude_from_all)
-  , LocalGenerator(0)
+  , LocalGenerator(CM_NULLPTR)
   , Files(files)
   , FilePermissions(file_permissions)
   , Rename(rename)
@@ -65,12 +58,12 @@ void cmInstallFilesGenerator::AddFilesInstallRule(
   std::vector<std::string> const& files)
 {
   // Write code to install the files.
-  const char* no_dir_permissions = 0;
+  const char* no_dir_permissions = CM_NULLPTR;
   this->AddInstallRule(
     os, this->GetDestination(config),
     (this->Programs ? cmInstallType_PROGRAMS : cmInstallType_FILES), files,
     this->Optional, this->FilePermissions.c_str(), no_dir_permissions,
-    this->Rename.c_str(), 0, indent);
+    this->Rename.c_str(), CM_NULLPTR, indent);
 }
 
 void cmInstallFilesGenerator::GenerateScriptActions(std::ostream& os,
@@ -90,7 +83,7 @@ void cmInstallFilesGenerator::GenerateScriptForConfig(
   cmGeneratorExpression ge;
   for (std::vector<std::string>::const_iterator i = this->Files.begin();
        i != this->Files.end(); ++i) {
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
     cmSystemTools::ExpandListArgument(
       cge->Evaluate(this->LocalGenerator, config), files);
   }
diff --git a/Source/cmInstallFilesGenerator.h b/Source/cmInstallFilesGenerator.h
index 0e738d3..ca8c6e1 100644
--- a/Source/cmInstallFilesGenerator.h
+++ b/Source/cmInstallFilesGenerator.h
@@ -1,18 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallFilesGenerator_h
 #define cmInstallFilesGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmInstallGenerator.h"
+#include "cmScriptGenerator.h"
+
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+class cmLocalGenerator;
 
 /** \class cmInstallFilesGenerator
  * \brief Generate file installation rules.
@@ -27,17 +27,17 @@ public:
                           const char* component, MessageLevel message,
                           bool exclude_from_all, const char* rename,
                           bool optional = false);
-  virtual ~cmInstallFilesGenerator();
+  ~cmInstallFilesGenerator() CM_OVERRIDE;
 
-  void Compute(cmLocalGenerator* lg);
+  void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
 
   std::string GetDestination(std::string const& config) const;
 
 protected:
-  virtual void GenerateScriptActions(std::ostream& os, Indent const& indent);
-  virtual void GenerateScriptForConfig(std::ostream& os,
-                                       const std::string& config,
-                                       Indent const& indent);
+  void GenerateScriptActions(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptForConfig(std::ostream& os, const std::string& config,
+                               Indent const& indent) CM_OVERRIDE;
   void AddFilesInstallRule(std::ostream& os, std::string const& config,
                            Indent const& indent,
                            std::vector<std::string> const& files);
diff --git a/Source/cmInstallGenerator.cxx b/Source/cmInstallGenerator.cxx
index e3d5bad..120d1b3 100644
--- a/Source/cmInstallGenerator.cxx
+++ b/Source/cmInstallGenerator.cxx
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallGenerator.h"
 
 #include "cmMakefile.h"
 #include "cmSystemTools.h"
 
+#include <ostream>
+
 cmInstallGenerator::cmInstallGenerator(
   const char* destination, std::vector<std::string> const& configurations,
   const char* component, MessageLevel message, bool exclude_from_all)
diff --git a/Source/cmInstallGenerator.h b/Source/cmInstallGenerator.h
index e271d53..48e1644 100644
--- a/Source/cmInstallGenerator.h
+++ b/Source/cmInstallGenerator.h
@@ -1,20 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallGenerator_h
 #define cmInstallGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmInstallType.h"
 #include "cmScriptGenerator.h"
 
+#include <iosfwd>
+#include <string>
+#include <vector>
+
 class cmLocalGenerator;
 class cmMakefile;
 
@@ -37,15 +34,14 @@ public:
                      std::vector<std::string> const& configurations,
                      const char* component, MessageLevel message,
                      bool exclude_from_all);
-  virtual ~cmInstallGenerator();
+  ~cmInstallGenerator() CM_OVERRIDE;
 
-  void AddInstallRule(std::ostream& os, std::string const& dest,
-                      cmInstallType type,
-                      std::vector<std::string> const& files,
-                      bool optional = false, const char* permissions_file = 0,
-                      const char* permissions_dir = 0, const char* rename = 0,
-                      const char* literal_args = 0,
-                      Indent const& indent = Indent());
+  void AddInstallRule(
+    std::ostream& os, std::string const& dest, cmInstallType type,
+    std::vector<std::string> const& files, bool optional = false,
+    const char* permissions_file = CM_NULLPTR,
+    const char* permissions_dir = CM_NULLPTR, const char* rename = CM_NULLPTR,
+    const char* literal_args = CM_NULLPTR, Indent const& indent = Indent());
 
   /** Get the install destination as it should appear in the
       installation script.  */
@@ -60,7 +56,7 @@ public:
   virtual void Compute(cmLocalGenerator*) {}
 
 protected:
-  virtual void GenerateScript(std::ostream& os);
+  void GenerateScript(std::ostream& os) CM_OVERRIDE;
 
   std::string CreateComponentTest(const char* component,
                                   bool exclude_from_all);
diff --git a/Source/cmInstallProgramsCommand.cxx b/Source/cmInstallProgramsCommand.cxx
index 2e5fc1f..bb2b61f 100644
--- a/Source/cmInstallProgramsCommand.cxx
+++ b/Source/cmInstallProgramsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallProgramsCommand.h"
 
 #include "cmInstallFilesGenerator.h"
@@ -113,12 +104,12 @@ std::string cmInstallProgramsCommand::FindInstallSource(const char* name) const
   if (cmSystemTools::FileExists(tb.c_str())) {
     // The file exists in the binary tree.  Use it.
     return tb;
-  } else if (cmSystemTools::FileExists(ts.c_str())) {
+  }
+  if (cmSystemTools::FileExists(ts.c_str())) {
     // The file exists in the source tree.  Use it.
     return ts;
-  } else {
-    // The file doesn't exist.  Assume it will be present in the
-    // binary tree when the install occurs.
-    return tb;
   }
+  // The file doesn't exist.  Assume it will be present in the
+  // binary tree when the install occurs.
+  return tb;
 }
diff --git a/Source/cmInstallProgramsCommand.h b/Source/cmInstallProgramsCommand.h
index b104c69..cb85cce 100644
--- a/Source/cmInstallProgramsCommand.h
+++ b/Source/cmInstallProgramsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallProgramsCommand_h
 #define cmInstallProgramsCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmInstallProgramsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmInstallProgramsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "install_programs"; }
+  std::string GetName() const CM_OVERRIDE { return "install_programs"; }
 
   /**
    * This is called at the end after all the information
@@ -46,9 +37,9 @@ public:
    * not implement this method.  At this point, reading and
    * writing to the cache can be done.
    */
-  virtual void FinalPass();
+  void FinalPass() CM_OVERRIDE;
 
-  virtual bool HasFinalPass() const { return true; }
+  bool HasFinalPass() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmInstallProgramsCommand, cmCommand);
 
diff --git a/Source/cmInstallScriptGenerator.cxx b/Source/cmInstallScriptGenerator.cxx
index 1b0f1d1..b39a622 100644
--- a/Source/cmInstallScriptGenerator.cxx
+++ b/Source/cmInstallScriptGenerator.cxx
@@ -1,21 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmInstallScriptGenerator.h"
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
+#include "cmScriptGenerator.h"
 
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include "cmInstallScriptGenerator.h"
+#include <ostream>
+#include <vector>
 
 cmInstallScriptGenerator::cmInstallScriptGenerator(const char* script,
                                                    bool code,
                                                    const char* component,
                                                    bool exclude_from_all)
-  : cmInstallGenerator(0, std::vector<std::string>(), component,
+  : cmInstallGenerator(CM_NULLPTR, std::vector<std::string>(), component,
                        MessageDefault, exclude_from_all)
   , Script(script)
   , Code(code)
diff --git a/Source/cmInstallScriptGenerator.h b/Source/cmInstallScriptGenerator.h
index ff2f2fa..0b54994 100644
--- a/Source/cmInstallScriptGenerator.h
+++ b/Source/cmInstallScriptGenerator.h
@@ -1,19 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallScriptGenerator_h
 #define cmInstallScriptGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmInstallGenerator.h"
 
+#include <iosfwd>
+#include <string>
+
 /** \class cmInstallScriptGenerator
  * \brief Generate target installation rules.
  */
@@ -22,10 +18,10 @@ class cmInstallScriptGenerator : public cmInstallGenerator
 public:
   cmInstallScriptGenerator(const char* script, bool code,
                            const char* component, bool exclude_from_all);
-  virtual ~cmInstallScriptGenerator();
+  ~cmInstallScriptGenerator() CM_OVERRIDE;
 
 protected:
-  virtual void GenerateScript(std::ostream& os);
+  void GenerateScript(std::ostream& os) CM_OVERRIDE;
   std::string Script;
   bool Code;
 };
diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx
index e68bac2..70ae204 100644
--- a/Source/cmInstallTargetGenerator.cxx
+++ b/Source/cmInstallTargetGenerator.cxx
@@ -1,26 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallTargetGenerator.h"
 
 #include "cmComputeLinkInformation.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
-#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
+#include "cmInstallType.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
 #include <assert.h>
+#include <map>
+#include <set>
+#include <sstream>
+#include <utility>
 
 cmInstallTargetGenerator::cmInstallTargetGenerator(
   const std::string& targetName, const char* dest, bool implib,
@@ -30,7 +29,7 @@ cmInstallTargetGenerator::cmInstallTargetGenerator(
   : cmInstallGenerator(dest, configurations, component, message,
                        exclude_from_all)
   , TargetName(targetName)
-  , Target(0)
+  , Target(CM_NULLPTR)
   , FilePermissions(file_permissions)
   , ImportLibrary(implib)
   , Optional(optional)
@@ -142,13 +141,22 @@ void cmInstallTargetGenerator::GenerateScriptForConfig(
       if (this->Target->IsAppBundleOnApple()) {
         cmMakefile const* mf = this->Target->Target->GetMakefile();
 
+        // Get App Bundle Extension
+        const char* ext = this->Target->GetProperty("BUNDLE_EXTENSION");
+        if (!ext) {
+          ext = "app";
+        }
+
         // Install the whole app bundle directory.
         type = cmInstallType_DIRECTORY;
         literal_args += " USE_SOURCE_PERMISSIONS";
-        from1 += ".app";
+        from1 += ".";
+        from1 += ext;
 
         // Tweaks apply to the binary inside the bundle.
-        to1 += ".app/";
+        to1 += ".";
+        to1 += ext;
+        to1 += "/";
         if (!mf->PlatformIsAppleIos()) {
           to1 += "Contents/MacOS/";
         }
@@ -294,8 +302,8 @@ void cmInstallTargetGenerator::GenerateScriptForConfig(
                  &cmInstallTargetGenerator::PreReplacementTweaks);
 
   // Write code to install the target file.
-  const char* no_dir_permissions = 0;
-  const char* no_rename = 0;
+  const char* no_dir_permissions = CM_NULLPTR;
+  const char* no_rename = CM_NULLPTR;
   bool optional = this->Optional || this->ImportLibrary;
   this->AddInstallRule(os, this->GetDestination(config), type, filesFrom,
                        optional, this->FilePermissions.c_str(),
@@ -623,7 +631,7 @@ void cmInstallTargetGenerator::AddChrpathPatchRule(
     std::string darwin_major_version_s =
       mf->GetSafeDefinition("DARWIN_MAJOR_VERSION");
 
-    std::stringstream ss(darwin_major_version_s);
+    std::istringstream ss(darwin_major_version_s);
     int darwin_major_version;
     ss >> darwin_major_version;
     if (!ss.fail() && darwin_major_version <= 9 &&
diff --git a/Source/cmInstallTargetGenerator.h b/Source/cmInstallTargetGenerator.h
index 2fd85b5..084a033 100644
--- a/Source/cmInstallTargetGenerator.h
+++ b/Source/cmInstallTargetGenerator.h
@@ -1,20 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallTargetGenerator_h
 #define cmInstallTargetGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmInstallGenerator.h"
+#include "cmScriptGenerator.h"
+
+#include <iosfwd>
+#include <string>
+#include <vector>
 
 class cmGeneratorTarget;
+class cmLocalGenerator;
 
 /** \class cmInstallTargetGenerator
  * \brief Generate target installation rules.
@@ -27,7 +26,7 @@ public:
                            std::vector<std::string> const& configurations,
                            const char* component, MessageLevel message,
                            bool exclude_from_all, bool optional);
-  virtual ~cmInstallTargetGenerator();
+  ~cmInstallTargetGenerator() CM_OVERRIDE;
 
   /** Select the policy for installing shared library linkable name
       symlinks.  */
@@ -54,7 +53,7 @@ public:
                                         const std::string& config,
                                         NameType nameType = NameNormal);
 
-  void Compute(cmLocalGenerator* lg);
+  void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
 
   cmGeneratorTarget* GetTarget() const { return this->Target; }
 
@@ -63,10 +62,9 @@ public:
   std::string GetDestination(std::string const& config) const;
 
 protected:
-  virtual void GenerateScript(std::ostream& os);
-  virtual void GenerateScriptForConfig(std::ostream& os,
-                                       const std::string& config,
-                                       Indent const& indent);
+  void GenerateScript(std::ostream& os) CM_OVERRIDE;
+  void GenerateScriptForConfig(std::ostream& os, const std::string& config,
+                               Indent const& indent) CM_OVERRIDE;
   typedef void (cmInstallTargetGenerator::*TweakMethod)(std::ostream&,
                                                         Indent const&,
                                                         const std::string&,
diff --git a/Source/cmInstallTargetsCommand.cxx b/Source/cmInstallTargetsCommand.cxx
index 056ea24..fca0bf1 100644
--- a/Source/cmInstallTargetsCommand.cxx
+++ b/Source/cmInstallTargetsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallTargetsCommand.h"
 
 // cmExecutableCommand
@@ -37,14 +28,17 @@ bool cmInstallTargetsCommand::InitialPass(std::vector<std::string> const& args,
       }
 
       runtime_dir = *s;
-    } else if (tgts.find(*s) != tgts.end()) {
-      tgts[*s].SetInstallPath(args[0].c_str());
-      tgts[*s].SetRuntimeInstallPath(runtime_dir.c_str());
-      tgts[*s].SetHaveInstallRule(true);
     } else {
-      std::string str = "Cannot find target: \"" + *s + "\" to install.";
-      this->SetError(str);
-      return false;
+      cmTargets::iterator ti = tgts.find(*s);
+      if (ti != tgts.end()) {
+        ti->second.SetInstallPath(args[0].c_str());
+        ti->second.SetRuntimeInstallPath(runtime_dir.c_str());
+        ti->second.SetHaveInstallRule(true);
+      } else {
+        std::string str = "Cannot find target: \"" + *s + "\" to install.";
+        this->SetError(str);
+        return false;
+      }
     }
   }
 
diff --git a/Source/cmInstallTargetsCommand.h b/Source/cmInstallTargetsCommand.h
index b0d04b0..2ddeaf0 100644
--- a/Source/cmInstallTargetsCommand.h
+++ b/Source/cmInstallTargetsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallTargetsCommand_h
 #define cmInstallTargetsCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmInstallTargetsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmInstallTargetsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "install_targets"; }
+  std::string GetName() const CM_OVERRIDE { return "install_targets"; }
 
   cmTypeMacro(cmInstallTargetsCommand, cmCommand);
 };
diff --git a/Source/cmInstallType.h b/Source/cmInstallType.h
index a837368..e2602cb 100644
--- a/Source/cmInstallType.h
+++ b/Source/cmInstallType.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstallType_h
 #define cmInstallType_h
 
diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx
index ed0f74b..8dd42b6 100644
--- a/Source/cmInstalledFile.cxx
+++ b/Source/cmInstalledFile.cxx
@@ -1,22 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstalledFile.h"
 
 #include "cmAlgorithms.h"
+#include "cmListFileCache.h"
 #include "cmMakefile.h"
 #include "cmSystemTools.h"
 
+#include <cmConfigure.h>
+#include <utility>
+
 cmInstalledFile::cmInstalledFile()
-  : NameExpression(0)
+  : NameExpression(CM_NULLPTR)
 {
 }
 
diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h
index d000891..4fe8134 100644
--- a/Source/cmInstalledFile.h
+++ b/Source/cmInstalledFile.h
@@ -1,18 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmInstalledFile_h
 #define cmInstalledFile_h
 
 #include "cmGeneratorExpression.h"
+#include "cm_auto_ptr.hxx"
+
+#include <map>
+#include <string>
+#include <vector>
+
+class cmMakefile;
 
 /** \class cmInstalledFile
  * \brief Represents a file intended for installation.
@@ -22,7 +20,7 @@
 class cmInstalledFile
 {
 public:
-  typedef cmsys::auto_ptr<cmCompiledGeneratorExpression>
+  typedef CM_AUTO_PTR<cmCompiledGeneratorExpression>
     CompiledGeneratorExpressionPtrType;
 
   typedef std::vector<cmCompiledGeneratorExpression*> ExpressionVectorType;
diff --git a/Source/cmLinkDirectoriesCommand.cxx b/Source/cmLinkDirectoriesCommand.cxx
index a33b429..fc6bf29 100644
--- a/Source/cmLinkDirectoriesCommand.cxx
+++ b/Source/cmLinkDirectoriesCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLinkDirectoriesCommand.h"
 
 // cmLinkDirectoriesCommand
 bool cmLinkDirectoriesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmLinkDirectoriesCommand.h b/Source/cmLinkDirectoriesCommand.h
index 7014a69..cd6d2de 100644
--- a/Source/cmLinkDirectoriesCommand.h
+++ b/Source/cmLinkDirectoriesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLinkDirectoriesCommand_h
 #define cmLinkDirectoriesCommand_h
 
@@ -28,19 +19,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmLinkDirectoriesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmLinkDirectoriesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "link_directories"; }
+  std::string GetName() const CM_OVERRIDE { return "link_directories"; }
 
   cmTypeMacro(cmLinkDirectoriesCommand, cmCommand);
 
diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h
index 0fbe093..74d6774 100644
--- a/Source/cmLinkItem.h
+++ b/Source/cmLinkItem.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLinkItem_h
 #define cmLinkItem_h
 
@@ -26,7 +16,7 @@ class cmLinkItem : public std::string
 public:
   cmLinkItem()
     : std_string()
-    , Target(0)
+    , Target(CM_NULLPTR)
   {
   }
   cmLinkItem(const std_string& n, cmGeneratorTarget const* t)
@@ -118,7 +108,7 @@ struct cmOptionalLinkInterface : public cmLinkInterface
     , AllDone(false)
     , Exists(false)
     , HadHeadSensitiveCondition(false)
-    , ExplicitLibraries(0)
+    , ExplicitLibraries(CM_NULLPTR)
   {
   }
   bool LibrariesDone;
diff --git a/Source/cmLinkLibrariesCommand.cxx b/Source/cmLinkLibrariesCommand.cxx
index 5d23d6a..bb0e27b 100644
--- a/Source/cmLinkLibrariesCommand.cxx
+++ b/Source/cmLinkLibrariesCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLinkLibrariesCommand.h"
 
 // cmLinkLibrariesCommand
 bool cmLinkLibrariesCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
   // add libraries, nothe that there is an optional prefix
diff --git a/Source/cmLinkLibrariesCommand.h b/Source/cmLinkLibrariesCommand.h
index 6ab50ce..b4943b6 100644
--- a/Source/cmLinkLibrariesCommand.h
+++ b/Source/cmLinkLibrariesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLinkLibrariesCommand_h
 #define cmLinkLibrariesCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmLinkLibrariesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmLinkLibrariesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "link_libraries"; }
+  std::string GetName() const CM_OVERRIDE { return "link_libraries"; }
 
   cmTypeMacro(cmLinkLibrariesCommand, cmCommand);
 };
diff --git a/Source/cmLinkedTree.h b/Source/cmLinkedTree.h
index 1a85396..d2c6f33 100644
--- a/Source/cmLinkedTree.h
+++ b/Source/cmLinkedTree.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLinkedTree_h
 #define cmLinkedTree_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include <assert.h>
@@ -56,7 +49,7 @@ public:
 
   public:
     iterator()
-      : Tree(0)
+      : Tree(CM_NULLPTR)
       , Position(0)
     {
     }
@@ -165,10 +158,10 @@ public:
 
   iterator Truncate()
   {
-    assert(this->UpPositions.size() > 0);
+    assert(!this->UpPositions.empty());
     this->UpPositions.erase(this->UpPositions.begin() + 1,
                             this->UpPositions.end());
-    assert(this->Data.size() > 0);
+    assert(!this->Data.empty());
     this->Data.erase(this->Data.begin() + 1, this->Data.end());
     return iterator(this, 1);
   }
diff --git a/Source/cmListCommand.cxx b/Source/cmListCommand.cxx
index 32e965d..98f3aa3 100644
--- a/Source/cmListCommand.cxx
+++ b/Source/cmListCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmListCommand.h"
 
 #include "cmAlgorithms.h"
diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h
index 56d9694..b6b0a47 100644
--- a/Source/cmListCommand.h
+++ b/Source/cmListCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmListCommand_h
 #define cmListCommand_h
 
@@ -24,24 +15,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmListCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmListCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "list"; }
+  std::string GetName() const CM_OVERRIDE { return "list"; }
 
   cmTypeMacro(cmListCommand, cmCommand);
 
diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx
index f47e9b6..5e6273c 100644
--- a/Source/cmListFileCache.cxx
+++ b/Source/cmListFileCache.cxx
@@ -1,34 +1,32 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmListFileCache.h"
 
 #include "cmListFileLexer.h"
-#include "cmMakefile.h"
+#include "cmMessenger.h"
 #include "cmOutputConverter.h"
 #include "cmSystemTools.h"
-#include "cmVersion.h"
+#include "cmake.h"
 
-#include <cmsys/RegularExpression.hxx>
+#include <algorithm>
+#include <assert.h>
+#include <cmConfigure.h>
+#include <sstream>
 
 struct cmListFileParser
 {
-  cmListFileParser(cmListFile* lf, cmMakefile* mf, const char* filename);
+  cmListFileParser(cmListFile* lf, cmListFileBacktrace lfbt,
+                   cmMessenger* messenger, const char* filename);
   ~cmListFileParser();
+  void IssueFileOpenError(std::string const& text) const;
+  void IssueError(std::string const& text) const;
   bool ParseFile();
   bool ParseFunction(const char* name, long line);
   bool AddArgument(cmListFileLexer_Token* token,
                    cmListFileArgument::Delimiter delim);
   cmListFile* ListFile;
-  cmMakefile* Makefile;
+  cmListFileBacktrace Backtrace;
+  cmMessenger* Messenger;
   const char* FileName;
   cmListFileLexer* Lexer;
   cmListFileFunction Function;
@@ -40,10 +38,12 @@ struct cmListFileParser
   } Separation;
 };
 
-cmListFileParser::cmListFileParser(cmListFile* lf, cmMakefile* mf,
+cmListFileParser::cmListFileParser(cmListFile* lf, cmListFileBacktrace lfbt,
+                                   cmMessenger* messenger,
                                    const char* filename)
   : ListFile(lf)
-  , Makefile(mf)
+  , Backtrace(lfbt)
+  , Messenger(messenger)
   , FileName(filename)
   , Lexer(cmListFileLexer_New())
 {
@@ -54,23 +54,36 @@ cmListFileParser::~cmListFileParser()
   cmListFileLexer_Delete(this->Lexer);
 }
 
+void cmListFileParser::IssueFileOpenError(const std::string& text) const
+{
+  this->Messenger->IssueMessage(cmake::FATAL_ERROR, text, this->Backtrace);
+}
+
+void cmListFileParser::IssueError(const std::string& text) const
+{
+  cmListFileContext lfc;
+  lfc.FilePath = this->FileName;
+  lfc.Line = cmListFileLexer_GetCurrentLine(this->Lexer);
+  cmListFileBacktrace lfbt = this->Backtrace;
+  lfbt = lfbt.Push(lfc);
+  this->Messenger->IssueMessage(cmake::FATAL_ERROR, text, lfbt);
+  cmSystemTools::SetFatalErrorOccured();
+}
+
 bool cmListFileParser::ParseFile()
 {
   // Open the file.
   cmListFileLexer_BOM bom;
   if (!cmListFileLexer_SetFileName(this->Lexer, this->FileName, &bom)) {
-    cmSystemTools::Error("cmListFileCache: error can not open file ",
-                         this->FileName);
+    this->IssueFileOpenError("cmListFileCache: error can not open file.");
     return false;
   }
 
   // Verify the Byte-Order-Mark, if any.
   if (bom != cmListFileLexer_BOM_None && bom != cmListFileLexer_BOM_UTF8) {
-    cmListFileLexer_SetFileName(this->Lexer, 0, 0);
-    std::ostringstream m;
-    m << "File\n  " << this->FileName << "\n"
-      << "starts with a Byte-Order-Mark that is not UTF-8.";
-    this->Makefile->IssueMessage(cmake::FATAL_ERROR, m.str());
+    cmListFileLexer_SetFileName(this->Lexer, CM_NULLPTR, CM_NULLPTR);
+    this->IssueFileOpenError(
+      "File starts with a Byte-Order-Mark that is not UTF-8.");
     return false;
   }
 
@@ -93,29 +106,26 @@ bool cmListFileParser::ParseFile()
         }
       } else {
         std::ostringstream error;
-        error << "Error in cmake code at\n"
-              << this->FileName << ":" << token->line << ":\n"
-              << "Parse error.  Expected a newline, got "
+        error << "Parse error.  Expected a newline, got "
               << cmListFileLexer_GetTypeAsString(this->Lexer, token->type)
               << " with text \"" << token->text << "\".";
-        cmSystemTools::Error(error.str().c_str());
+        this->IssueError(error.str());
         return false;
       }
     } else {
       std::ostringstream error;
-      error << "Error in cmake code at\n"
-            << this->FileName << ":" << token->line << ":\n"
-            << "Parse error.  Expected a command name, got "
+      error << "Parse error.  Expected a command name, got "
             << cmListFileLexer_GetTypeAsString(this->Lexer, token->type)
             << " with text \"" << token->text << "\".";
-      cmSystemTools::Error(error.str().c_str());
+      this->IssueError(error.str());
       return false;
     }
   }
   return true;
 }
 
-bool cmListFile::ParseFile(const char* filename, bool topLevel, cmMakefile* mf)
+bool cmListFile::ParseFile(const char* filename, cmMessenger* messenger,
+                           cmListFileBacktrace const& lfbt)
 {
   if (!cmSystemTools::FileExists(filename) ||
       cmSystemTools::FileIsDirectory(filename)) {
@@ -125,87 +135,11 @@ bool cmListFile::ParseFile(const char* filename, bool topLevel, cmMakefile* mf)
   bool parseError = false;
 
   {
-    cmListFileParser parser(this, mf, filename);
+    cmListFileParser parser(this, lfbt, messenger, filename);
     parseError = !parser.ParseFile();
   }
 
-  // do we need a cmake_policy(VERSION call?
-  if (topLevel) {
-    bool hasVersion = false;
-    // search for the right policy command
-    for (std::vector<cmListFileFunction>::iterator i = this->Functions.begin();
-         i != this->Functions.end(); ++i) {
-      if (cmSystemTools::LowerCase(i->Name) == "cmake_minimum_required") {
-        hasVersion = true;
-        break;
-      }
-    }
-    // if no policy command is found this is an error if they use any
-    // non advanced functions or a lot of functions
-    if (!hasVersion) {
-      bool isProblem = true;
-      if (this->Functions.size() < 30) {
-        // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
-        // these commands must have backwards compatibility forever and
-        // and that is a lot longer than your tiny mind can comprehend mortal
-        std::set<std::string> allowedCommands;
-        allowedCommands.insert("project");
-        allowedCommands.insert("set");
-        allowedCommands.insert("if");
-        allowedCommands.insert("endif");
-        allowedCommands.insert("else");
-        allowedCommands.insert("elseif");
-        allowedCommands.insert("add_executable");
-        allowedCommands.insert("add_library");
-        allowedCommands.insert("target_link_libraries");
-        allowedCommands.insert("option");
-        allowedCommands.insert("message");
-        isProblem = false;
-        for (std::vector<cmListFileFunction>::iterator i =
-               this->Functions.begin();
-             i != this->Functions.end(); ++i) {
-          std::string name = cmSystemTools::LowerCase(i->Name);
-          if (allowedCommands.find(name) == allowedCommands.end()) {
-            isProblem = true;
-            break;
-          }
-        }
-      }
-
-      if (isProblem) {
-        // Tell the top level cmMakefile to diagnose
-        // this violation of CMP0000.
-        mf->SetCheckCMP0000(true);
-
-        // Implicitly set the version for the user.
-        mf->SetPolicyVersion("2.4");
-      }
-    }
-  }
-
-  if (topLevel) {
-    bool hasProject = false;
-    // search for a project command
-    for (std::vector<cmListFileFunction>::iterator i = this->Functions.begin();
-         i != this->Functions.end(); ++i) {
-      if (cmSystemTools::LowerCase(i->Name) == "project") {
-        hasProject = true;
-        break;
-      }
-    }
-    // if no project command is found, add one
-    if (!hasProject) {
-      cmListFileFunction project;
-      project.Name = "PROJECT";
-      cmListFileArgument prj("Project", cmListFileArgument::Unquoted, 0);
-      project.Arguments.push_back(prj);
-      this->Functions.insert(this->Functions.begin(), project);
-    }
-  }
-  if (parseError) {
-    return false;
-  }
-  return true;
+  return !parseError;
 }
 
 bool cmListFileParser::ParseFunction(const char* name, long line)
@@ -223,22 +157,18 @@ bool cmListFileParser::ParseFunction(const char* name, long line)
   if (!token) {
     std::ostringstream error;
     /* clang-format off */
-    error << "Error in cmake code at\n" << this->FileName << ":"
-          << cmListFileLexer_GetCurrentLine(this->Lexer) << ":\n"
+    error << "Unexpected end of file.\n"
           << "Parse error.  Function missing opening \"(\".";
     /* clang-format on */
-    cmSystemTools::Error(error.str().c_str());
+    this->IssueError(error.str());
     return false;
   }
   if (token->type != cmListFileLexer_Token_ParenLeft) {
     std::ostringstream error;
-    error << "Error in cmake code at\n"
-          << this->FileName << ":"
-          << cmListFileLexer_GetCurrentLine(this->Lexer) << ":\n"
-          << "Parse error.  Expected \"(\", got "
+    error << "Parse error.  Expected \"(\", got "
           << cmListFileLexer_GetTypeAsString(this->Lexer, token->type)
           << " with text \"" << token->text << "\".";
-    cmSystemTools::Error(error.str().c_str());
+    this->IssueError(error.str());
     return false;
   }
 
@@ -290,25 +220,24 @@ bool cmListFileParser::ParseFunction(const char* name, long line)
     } else {
       // Error.
       std::ostringstream error;
-      error << "Error in cmake code at\n"
-            << this->FileName << ":"
-            << cmListFileLexer_GetCurrentLine(this->Lexer) << ":\n"
-            << "Parse error.  Function missing ending \")\".  "
+      error << "Parse error.  Function missing ending \")\".  "
             << "Instead found "
             << cmListFileLexer_GetTypeAsString(this->Lexer, token->type)
             << " with text \"" << token->text << "\".";
-      cmSystemTools::Error(error.str().c_str());
+      this->IssueError(error.str());
       return false;
     }
   }
 
   std::ostringstream error;
-  error << "Error in cmake code at\n"
-        << this->FileName << ":" << lastLine << ":\n"
-        << "Parse error.  Function missing ending \")\".  "
+  cmListFileContext lfc;
+  lfc.FilePath = this->FileName;
+  lfc.Line = lastLine;
+  cmListFileBacktrace lfbt = this->Backtrace;
+  lfbt = lfbt.Push(lfc);
+  error << "Parse error.  Function missing ending \")\".  "
         << "End of file reached.";
-  cmSystemTools::Error(error.str().c_str());
-
+  this->Messenger->IssueMessage(cmake::FATAL_ERROR, error.str(), lfbt);
   return false;
 }
 
@@ -323,19 +252,22 @@ bool cmListFileParser::AddArgument(cmListFileLexer_Token* token,
   bool isError = (this->Separation == SeparationError ||
                   delim == cmListFileArgument::Bracket);
   std::ostringstream m;
-  /* clang-format off */
-  m << "Syntax " << (isError? "Error":"Warning") << " in cmake code at\n"
-    << "  " << this->FileName << ":" << token->line << ":"
-    << token->column << "\n"
+  cmListFileContext lfc;
+  lfc.FilePath = this->FileName;
+  lfc.Line = token->line;
+  cmListFileBacktrace lfbt = this->Backtrace;
+  lfbt = lfbt.Push(lfc);
+
+  m << "Syntax " << (isError ? "Error" : "Warning") << " in cmake code at "
+    << "column " << token->column << "\n"
     << "Argument not separated from preceding token by whitespace.";
   /* clang-format on */
   if (isError) {
-    this->Makefile->IssueMessage(cmake::FATAL_ERROR, m.str());
+    this->Messenger->IssueMessage(cmake::FATAL_ERROR, m.str(), lfbt);
     return false;
-  } else {
-    this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, m.str());
-    return true;
   }
+  this->Messenger->IssueMessage(cmake::AUTHOR_WARNING, m.str(), lfbt);
+  return true;
 }
 
 struct cmListFileBacktrace::Entry : public cmListFileContext
@@ -387,13 +319,13 @@ cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot bottom, Entry* cur)
 
 cmListFileBacktrace::cmListFileBacktrace()
   : Bottom()
-  , Cur(0)
+  , Cur(CM_NULLPTR)
 {
 }
 
 cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot snapshot)
   : Bottom(snapshot.GetCallStackBottom())
-  , Cur(0)
+  , Cur(CM_NULLPTR)
 {
 }
 
@@ -450,10 +382,9 @@ cmListFileContext const& cmListFileBacktrace::Top() const
 {
   if (this->Cur) {
     return *this->Cur;
-  } else {
-    static cmListFileContext const empty;
-    return empty;
   }
+  static cmListFileContext const empty;
+  return empty;
 }
 
 void cmListFileBacktrace::PrintTitle(std::ostream& out) const
@@ -464,7 +395,8 @@ void cmListFileBacktrace::PrintTitle(std::ostream& out) const
   cmOutputConverter converter(this->Bottom);
   cmListFileContext lfc = *this->Cur;
   if (!this->Bottom.GetState()->GetIsInTryCompile()) {
-    lfc.FilePath = converter.Convert(lfc.FilePath, cmOutputConverter::HOME);
+    lfc.FilePath = converter.ConvertToRelativePath(
+      this->Bottom.GetState()->GetSourceDirectory(), lfc.FilePath);
   }
   out << (lfc.Line ? " at " : " in ") << lfc;
 }
@@ -489,7 +421,8 @@ void cmListFileBacktrace::PrintCallStack(std::ostream& out) const
     }
     cmListFileContext lfc = *i;
     if (!this->Bottom.GetState()->GetIsInTryCompile()) {
-      lfc.FilePath = converter.Convert(lfc.FilePath, cmOutputConverter::HOME);
+      lfc.FilePath = converter.ConvertToRelativePath(
+        this->Bottom.GetState()->GetSourceDirectory(), lfc.FilePath);
     }
     out << "  " << lfc << "\n";
   }
diff --git a/Source/cmListFileCache.h b/Source/cmListFileCache.h
index d72c360..4dacee0 100644
--- a/Source/cmListFileCache.h
+++ b/Source/cmListFileCache.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmListFileCache_h
 #define cmListFileCache_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
+#include <string>
+#include <vector>
 
 #include "cmState.h"
 
@@ -23,7 +18,7 @@
  * cmake list files.
  */
 
-class cmMakefile;
+class cmMessenger;
 
 struct cmCommandContext
 {
@@ -149,6 +144,7 @@ public:
 
 private:
   struct Entry;
+
   cmState::Snapshot Bottom;
   Entry* Cur;
   cmListFileBacktrace(cmState::Snapshot bottom, Entry* up,
@@ -158,7 +154,8 @@ private:
 
 struct cmListFile
 {
-  bool ParseFile(const char* path, bool topLevel, cmMakefile* mf);
+  bool ParseFile(const char* path, cmMessenger* messenger,
+                 cmListFileBacktrace const& lfbt);
 
   std::vector<cmListFileFunction> Functions;
 };
diff --git a/Source/cmListFileLexer.c b/Source/cmListFileLexer.c
index bc1666e..0f73c3d 100644
--- a/Source/cmListFileLexer.c
+++ b/Source/cmListFileLexer.c
@@ -549,17 +549,8 @@ static yyconst flex_int32_t yy_rule_can_match_eol[25] =
 #define YY_RESTORE_YY_MORE_OFFSET
 #line 1 "cmListFileLexer.in.l"
 #line 2 "cmListFileLexer.in.l"
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmListFileLexer.h b/Source/cmListFileLexer.h
index 88300e1..dfbad5e 100644
--- a/Source/cmListFileLexer.h
+++ b/Source/cmListFileLexer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmListFileLexer_h
 #define cmListFileLexer_h
 
diff --git a/Source/cmListFileLexer.in.l b/Source/cmListFileLexer.in.l
index 6d44814..75df1bc 100644
--- a/Source/cmListFileLexer.in.l
+++ b/Source/cmListFileLexer.in.l
@@ -1,15 +1,6 @@
 %{
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
 This file must be translated to C and modified to build everywhere.
diff --git a/Source/cmLoadCacheCommand.cxx b/Source/cmLoadCacheCommand.cxx
index 85188d1..3428a6c 100644
--- a/Source/cmLoadCacheCommand.cxx
+++ b/Source/cmLoadCacheCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLoadCacheCommand.h"
 
 #include <cmsys/FStream.hxx>
@@ -18,7 +9,7 @@
 bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args,
                                      cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with wrong number of arguments.");
   }
 
diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h
index 67d93ac..57f64cd 100644
--- a/Source/cmLoadCacheCommand.h
+++ b/Source/cmLoadCacheCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLoadCacheCommand_h
 #define cmLoadCacheCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmLoadCacheCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmLoadCacheCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "load_cache"; }
+  std::string GetName() const CM_OVERRIDE { return "load_cache"; }
 
   cmTypeMacro(cmLoadCacheCommand, cmCommand);
 
diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx
index 081c22e..bcfec79 100644
--- a/Source/cmLoadCommandCommand.cxx
+++ b/Source/cmLoadCommandCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLoadCommandCommand.h"
 
 #include "cmCPluginAPI.cxx"
@@ -37,12 +28,12 @@ public:
   }
 
   ///! clean up any memory allocated by the plugin
-  ~cmLoadedCommand();
+  ~cmLoadedCommand() CM_OVERRIDE;
 
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmLoadedCommand* newC = new cmLoadedCommand;
     // we must copy when we clone
@@ -54,8 +45,8 @@ public:
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus&);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called at the end after all the information
@@ -63,8 +54,8 @@ public:
    * not implement this method.  At this point, reading and
    * writing to the cache can be done.
    */
-  virtual void FinalPass();
-  virtual bool HasFinalPass() const
+  void FinalPass() CM_OVERRIDE;
+  bool HasFinalPass() const CM_OVERRIDE
   {
     return this->info.FinalPass ? true : false;
   }
@@ -72,7 +63,7 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return info.Name; }
+  std::string GetName() const CM_OVERRIDE { return info.Name; }
 
   static const char* LastName;
   static void TrapsForSignals(int sig)
@@ -94,11 +85,11 @@ public:
 #endif
       signal(SIGILL, TrapsForSignalsCFunction);
     } else {
-      signal(SIGSEGV, 0);
+      signal(SIGSEGV, CM_NULLPTR);
 #ifdef SIGBUS
-      signal(SIGBUS, 0);
+      signal(SIGBUS, CM_NULLPTR);
 #endif
-      signal(SIGILL, 0);
+      signal(SIGILL, CM_NULLPTR);
     }
   }
 
@@ -112,7 +103,7 @@ extern "C" void TrapsForSignalsCFunction(int sig)
   cmLoadedCommand::TrapsForSignals(sig);
 }
 
-const char* cmLoadedCommand::LastName = 0;
+const char* cmLoadedCommand::LastName = CM_NULLPTR;
 
 bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
@@ -128,7 +119,7 @@ bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args,
 
   // create argc and argv and then invoke the command
   int argc = static_cast<int>(args.size());
-  char** argv = 0;
+  char** argv = CM_NULLPTR;
   if (argc) {
     argv = (char**)malloc(argc * sizeof(char*));
   }
@@ -183,7 +174,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
         "The load_command command should not be called; see CMP0031.")) {
     return true;
   }
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmLoadCommandCommand.h b/Source/cmLoadCommandCommand.h
index e00a01e..e42d46a 100644
--- a/Source/cmLoadCommandCommand.h
+++ b/Source/cmLoadCommandCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLoadCommandCommand_h
 #define cmLoadCommandCommand_h
 
@@ -17,10 +8,10 @@
 class cmLoadCommandCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmLoadCommandCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "load_command"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmLoadCommandCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "load_command"; }
   cmTypeMacro(cmLoadCommandCommand, cmCommand);
 };
 
diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx
index 3ebd128..6b49f1e 100644
--- a/Source/cmLocalCommonGenerator.cxx
+++ b/Source/cmLocalCommonGenerator.cxx
@@ -1,21 +1,19 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalCommonGenerator.h"
 
+#include "cmGeneratorTarget.h"
 #include "cmMakefile.h"
 
+#include <vector>
+
+class cmGlobalGenerator;
+
 cmLocalCommonGenerator::cmLocalCommonGenerator(cmGlobalGenerator* gg,
-                                               cmMakefile* mf)
+                                               cmMakefile* mf,
+                                               std::string const& wd)
   : cmLocalGenerator(gg, mf)
+  , WorkingDirectory(wd)
 {
 }
 
@@ -34,3 +32,51 @@ void cmLocalCommonGenerator::SetConfigName()
     this->ConfigName = "";
   }
 }
+
+std::string cmLocalCommonGenerator::GetTargetFortranFlags(
+  cmGeneratorTarget const* target, std::string const& config)
+{
+  std::string flags;
+
+  // Enable module output if necessary.
+  if (const char* modout_flag =
+        this->Makefile->GetDefinition("CMAKE_Fortran_MODOUT_FLAG")) {
+    this->AppendFlags(flags, modout_flag);
+  }
+
+  // Add a module output directory flag if necessary.
+  std::string mod_dir =
+    target->GetFortranModuleDirectory(this->WorkingDirectory);
+  if (!mod_dir.empty()) {
+    mod_dir = this->ConvertToOutputFormat(
+      this->ConvertToRelativePath(this->WorkingDirectory, mod_dir),
+      cmOutputConverter::SHELL);
+  } else {
+    mod_dir =
+      this->Makefile->GetSafeDefinition("CMAKE_Fortran_MODDIR_DEFAULT");
+  }
+  if (!mod_dir.empty()) {
+    const char* moddir_flag =
+      this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG");
+    std::string modflag = moddir_flag;
+    modflag += mod_dir;
+    this->AppendFlags(flags, modflag);
+  }
+
+  // If there is a separate module path flag then duplicate the
+  // include path with it.  This compiler does not search the include
+  // path for modules.
+  if (const char* modpath_flag =
+        this->Makefile->GetDefinition("CMAKE_Fortran_MODPATH_FLAG")) {
+    std::vector<std::string> includes;
+    this->GetIncludeDirectories(includes, target, "C", config);
+    for (std::vector<std::string>::const_iterator idi = includes.begin();
+         idi != includes.end(); ++idi) {
+      std::string flg = modpath_flag;
+      flg += this->ConvertToOutputFormat(*idi, cmOutputConverter::SHELL);
+      this->AppendFlags(flags, flg);
+    }
+  }
+
+  return flags;
+}
diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h
index d282054..eb5f850 100644
--- a/Source/cmLocalCommonGenerator.h
+++ b/Source/cmLocalCommonGenerator.h
@@ -1,20 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalCommonGenerator_h
 #define cmLocalCommonGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmLocalGenerator.h"
+#include "cmOutputConverter.h"
+
+#include <string>
 
-class cmCommonTargetGenerator;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
 
 /** \class cmLocalCommonGenerator
  * \brief Common infrastructure for Makefile and Ninja local generators.
@@ -22,12 +20,20 @@ class cmCommonTargetGenerator;
 class cmLocalCommonGenerator : public cmLocalGenerator
 {
 public:
-  cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf);
-  ~cmLocalCommonGenerator();
+  cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf,
+                         std::string const& wd);
+  ~cmLocalCommonGenerator() CM_OVERRIDE;
 
   std::string const& GetConfigName() { return this->ConfigName; }
 
+  std::string GetWorkingDirectory() const { return this->WorkingDirectory; }
+
+  std::string GetTargetFortranFlags(cmGeneratorTarget const* target,
+                                    std::string const& config) CM_OVERRIDE;
+
 protected:
+  std::string WorkingDirectory;
+
   void SetConfigName();
   std::string ConfigName;
 
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index e91eb46..f24b717 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalGenerator.h"
 
 #include "cmAlgorithms.h"
@@ -16,14 +7,15 @@
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorExpressionEvaluationFile.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
-#include "cmInstallFilesGenerator.h"
 #include "cmInstallGenerator.h"
 #include "cmInstallScriptGenerator.h"
 #include "cmInstallTargetGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmTest.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTestGenerator.h"
 #include "cmVersion.h"
 #include "cmake.h"
@@ -33,9 +25,14 @@
 #include <cmsys/MD5.h>
 #endif
 
-#include <ctype.h> // for isalpha
-
+#include <algorithm>
 #include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <ctype.h>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
 
 #if defined(__HAIKU__)
 #include <FindDirectory.h>
@@ -45,6 +42,7 @@
 cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
   : cmOutputConverter(makefile->GetStateSnapshot())
   , StateSnapshot(makefile->GetStateSnapshot())
+  , DirectoryBacktrace(makefile->GetBacktrace())
 {
   this->GlobalGenerator = gg;
 
@@ -68,7 +66,7 @@ cmLocalGenerator::~cmLocalGenerator()
 void cmLocalGenerator::IssueMessage(cmake::MessageType t,
                                     std::string const& text) const
 {
-  this->Makefile->IssueMessage(t, text);
+  this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
 }
 
 void cmLocalGenerator::ComputeObjectMaxPath()
@@ -168,15 +166,15 @@ void cmLocalGenerator::GenerateTestFiles()
     (*gi)->Compute(this);
     (*gi)->Generate(fout, config, configurationTypes);
   }
-  size_t i;
-  std::vector<cmState::Snapshot> children =
-    this->Makefile->GetStateSnapshot().GetChildren();
-  for (i = 0; i < children.size(); ++i) {
+  typedef std::vector<cmState::Snapshot> vec_t;
+  vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
+  std::string parentBinDir = this->GetCurrentBinaryDirectory();
+  for (vec_t::const_iterator i = children.begin(); i != children.end(); ++i) {
     // TODO: Use add_subdirectory instead?
-    fout << "subdirs(";
-    std::string outP = children[i].GetDirectory().GetCurrentBinary();
-    fout << this->Convert(outP, START_OUTPUT);
-    fout << ")" << std::endl;
+    std::string outP = i->GetDirectory().GetCurrentBinary();
+    outP = this->ConvertToRelativePath(parentBinDir, outP);
+    outP = cmOutputConverter::EscapeForCMake(outP);
+    fout << "subdirs(" << outP << ")" << std::endl;
   }
 }
 
@@ -271,7 +269,7 @@ void cmLocalGenerator::GenerateInstallRules()
   // Choose a default install configuration.
   std::string default_config = config;
   const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
-                                  "DEBUG", 0 };
+                                  "DEBUG", CM_NULLPTR };
   for (const char** c = default_order; *c && default_config.empty(); ++c) {
     for (std::vector<std::string>::iterator i = configurationTypes.begin();
          i != configurationTypes.end(); ++i) {
@@ -444,7 +442,7 @@ cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
   if (ti != this->GeneratorTargets.end()) {
     return *ti;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmLocalGenerator::ComputeTargetManifest()
@@ -507,7 +505,7 @@ static const char* ruleReplaceVars[] = {
   "CMAKE_RANLIB",
   "CMAKE_LINKER",
   "CMAKE_CL_SHOWINCLUDES_PREFIX",
-  0
+  CM_NULLPTR
 };
 
 std::string cmLocalGenerator::ExpandRuleVariable(
@@ -625,16 +623,14 @@ std::string cmLocalGenerator::ExpandRuleVariable(
     if (variable == "TARGET_VERSION_MAJOR") {
       if (replaceValues.TargetVersionMajor) {
         return replaceValues.TargetVersionMajor;
-      } else {
-        return "0";
       }
+      return "0";
     }
     if (variable == "TARGET_VERSION_MINOR") {
       if (replaceValues.TargetVersionMinor) {
         return replaceValues.TargetVersionMinor;
-      } else {
-        return "0";
       }
+      return "0";
     }
     if (replaceValues.Target) {
       if (variable == "TARGET_BASE") {
@@ -643,9 +639,8 @@ std::string cmLocalGenerator::ExpandRuleVariable(
         std::string::size_type pos = targetBase.rfind('.');
         if (pos != targetBase.npos) {
           return targetBase.substr(0, pos);
-        } else {
-          return targetBase;
         }
+        return targetBase;
       }
     }
   }
@@ -690,7 +685,9 @@ std::string cmLocalGenerator::ExpandRuleVariable(
     }
   }
   if (variable == "CMAKE_COMMAND") {
-    return this->Convert(cmSystemTools::GetCMakeCommand(), FULL, SHELL);
+    return this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
+      SHELL);
   }
   std::vector<std::string> enabledLanguages =
     this->GetState()->GetEnabledLanguages();
@@ -703,13 +700,13 @@ std::string cmLocalGenerator::ExpandRuleVariable(
       std::string actualReplace = ruleReplaceVars[pos];
       // If this is the compiler then look for the extra variable
       // _COMPILER_ARG1 which must be the first argument to the compiler
-      const char* compilerArg1 = 0;
-      const char* compilerTarget = 0;
-      const char* compilerOptionTarget = 0;
-      const char* compilerExternalToolchain = 0;
-      const char* compilerOptionExternalToolchain = 0;
-      const char* compilerSysroot = 0;
-      const char* compilerOptionSysroot = 0;
+      const char* compilerArg1 = CM_NULLPTR;
+      const char* compilerTarget = CM_NULLPTR;
+      const char* compilerOptionTarget = CM_NULLPTR;
+      const char* compilerExternalToolchain = CM_NULLPTR;
+      const char* compilerOptionExternalToolchain = CM_NULLPTR;
+      const char* compilerSysroot = CM_NULLPTR;
+      const char* compilerOptionSysroot = CM_NULLPTR;
       if (actualReplace == "CMAKE_${LANG}_COMPILER") {
         std::string arg1 = actualReplace + "_ARG1";
         cmSystemTools::ReplaceString(arg1, "${LANG}", lang);
@@ -812,9 +809,8 @@ const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
 {
   if (target) {
     return target->GetProperty(prop);
-  } else {
-    return this->Makefile->GetProperty(prop);
   }
+  return this->Makefile->GetProperty(prop);
 }
 
 void cmLocalGenerator::InsertRuleLauncher(std::string& s,
@@ -831,8 +827,8 @@ void cmLocalGenerator::InsertRuleLauncher(std::string& s,
 std::string cmLocalGenerator::ConvertToIncludeReference(
   std::string const& path, OutputFormat format, bool forceFullPaths)
 {
-  return this->ConvertToOutputForExisting(
-    path, forceFullPaths ? FULL : START_OUTPUT, format);
+  static_cast<void>(forceFullPaths);
+  return this->ConvertToOutputForExisting(path, format);
 }
 
 std::string cmLocalGenerator::GetIncludeFlags(
@@ -871,7 +867,7 @@ std::string cmLocalGenerator::GetIncludeFlags(
   // normal flag is repeated for each directory.
   std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_";
   sysFlagVar += lang;
-  const char* sysIncludeFlag = 0;
+  const char* sysIncludeFlag = CM_NULLPTR;
   if (repeatFlag) {
     sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar);
   }
@@ -943,7 +939,7 @@ std::string cmLocalGenerator::GetIncludeFlags(
 void cmLocalGenerator::AddCompileDefinitions(std::set<std::string>& defines,
                                              cmGeneratorTarget const* target,
                                              const std::string& config,
-                                             const std::string& lang)
+                                             const std::string& lang) const
 {
   std::vector<std::string> targetDefines;
   target->GetCompileDefinitions(targetDefines, config, lang);
@@ -1152,13 +1148,11 @@ void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
 }
 
 void cmLocalGenerator::GetTargetFlags(
-  std::string& linkLibs, std::string& flags, std::string& linkFlags,
-  std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target,
-  bool useWatcomQuote)
+  const std::string& config, std::string& linkLibs, std::string& flags,
+  std::string& linkFlags, std::string& frameworkPath, std::string& linkPath,
+  cmGeneratorTarget* target, bool useWatcomQuote)
 {
-  std::string buildType =
-    this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-  buildType = cmSystemTools::UpperCase(buildType);
+  const std::string buildType = cmSystemTools::UpperCase(config);
   const char* libraryLinkVariable =
     "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
 
@@ -1188,7 +1182,8 @@ void cmLocalGenerator::GetTargetFlags(
           if (sf->GetExtension() == "def") {
             linkFlags +=
               this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
-            linkFlags += this->Convert(sf->GetFullPath(), FULL, SHELL);
+            linkFlags += this->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
             linkFlags += " ";
           }
         }
@@ -1273,6 +1268,112 @@ void cmLocalGenerator::GetTargetFlags(
   }
 }
 
+void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
+                                             std::string const& config,
+                                             std::string const& lang,
+                                             std::string& flags)
+{
+  cmMakefile* mf = this->GetMakefile();
+
+  // Add language-specific flags.
+  this->AddLanguageFlags(flags, lang, config);
+
+  if (target->GetFeatureAsBool("INTERPROCEDURAL_OPTIMIZATION", config)) {
+    this->AppendFeatureOptions(flags, lang, "IPO");
+  }
+
+  this->AddArchitectureFlags(flags, target, lang, config);
+
+  if (lang == "Fortran") {
+    this->AppendFlags(flags, this->GetTargetFortranFlags(target, config));
+  }
+
+  this->AddCMP0018Flags(flags, target, lang, config);
+  this->AddVisibilityPresetFlags(flags, target, lang);
+  this->AppendFlags(flags, mf->GetDefineFlags());
+  this->AppendFlags(flags, this->GetFrameworkFlags(lang, config, target));
+  this->AddCompileOptions(flags, target, lang, config);
+}
+
+static std::string GetFrameworkFlags(const std::string& lang,
+                                     const std::string& config,
+                                     cmGeneratorTarget* target)
+{
+  cmLocalGenerator* lg = target->GetLocalGenerator();
+  cmMakefile* mf = lg->GetMakefile();
+
+  if (!mf->IsOn("APPLE")) {
+    return std::string();
+  }
+
+  std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
+  const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
+  if (!(fwSearchFlag && *fwSearchFlag)) {
+    return std::string();
+  }
+
+  std::set<std::string> emitted;
+#ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
+  emitted.insert("/System/Library/Frameworks");
+#endif
+  std::vector<std::string> includes;
+
+  lg->GetIncludeDirectories(includes, target, "C", config);
+  // check all include directories for frameworks as this
+  // will already have added a -F for the framework
+  for (std::vector<std::string>::iterator i = includes.begin();
+       i != includes.end(); ++i) {
+    if (lg->GetGlobalGenerator()->NameResolvesToFramework(*i)) {
+      std::string frameworkDir = *i;
+      frameworkDir += "/../";
+      frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
+      emitted.insert(frameworkDir);
+    }
+  }
+
+  std::string flags;
+  if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
+    std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
+    for (std::vector<std::string>::const_iterator i = frameworks.begin();
+         i != frameworks.end(); ++i) {
+      if (emitted.insert(*i).second) {
+        flags += fwSearchFlag;
+        flags += lg->ConvertToOutputFormat(*i, cmOutputConverter::SHELL);
+        flags += " ";
+      }
+    }
+  }
+  return flags;
+}
+
+std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
+                                                std::string const& config,
+                                                cmGeneratorTarget* target)
+{
+  return ::GetFrameworkFlags(l, config, target);
+}
+
+void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
+                                        std::string const& config,
+                                        std::string const& lang,
+                                        std::set<std::string>& defines) const
+{
+  // Add the export symbol definition for shared library objects.
+  if (const char* exportMacro = target->GetExportMacro()) {
+    this->AppendDefines(defines, exportMacro);
+  }
+
+  // Add preprocessor definitions for this target and configuration.
+  this->AddCompileDefinitions(defines, target, config, lang);
+}
+
+std::string cmLocalGenerator::GetTargetFortranFlags(
+  cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
+{
+  // Implemented by specific generators that override this.
+  return std::string();
+}
+
 std::string cmLocalGenerator::ConvertToLinkReference(std::string const& lib,
                                                      OutputFormat format)
 {
@@ -1292,14 +1393,16 @@ std::string cmLocalGenerator::ConvertToLinkReference(std::string const& lib,
         sp += lib.substr(pos);
 
         // Convert to an output path.
-        return this->Convert(sp.c_str(), NONE, format);
+        return this->ConvertToOutputFormat(sp.c_str(), format);
       }
     }
   }
 #endif
 
   // Normal behavior.
-  return this->Convert(lib, START_OUTPUT, format);
+  return this->ConvertToOutputFormat(
+    this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), lib),
+    format);
 }
 
 /**
@@ -1350,7 +1453,7 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
           w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
             "For compatibility with older versions of CMake, "
             "additional flags may be added to export symbols on all "
-            "executables regardless of thier ENABLE_EXPORTS property.";
+            "executables regardless of their ENABLE_EXPORTS property.";
           /* clang-format on */
           this->IssueMessage(cmake::AUTHOR_WARNING, w.str());
         }
@@ -1388,7 +1491,7 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
     for (std::vector<std::string>::const_iterator fdi = fwDirs.begin();
          fdi != fwDirs.end(); ++fdi) {
       frameworkPath += fwSearchFlag;
-      frameworkPath += this->Convert(*fdi, NONE, shellFormat);
+      frameworkPath += this->ConvertToOutputFormat(*fdi, shellFormat);
       frameworkPath += " ";
     }
   }
@@ -1398,7 +1501,7 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
   for (std::vector<std::string>::const_iterator libDir = libDirs.begin();
        libDir != libDirs.end(); ++libDir) {
     std::string libpath =
-      this->ConvertToOutputForExisting(*libDir, START_OUTPUT, shellFormat);
+      this->ConvertToOutputForExisting(*libDir, shellFormat);
     linkPath += " " + libPathFlag;
     linkPath += libpath;
     linkPath += libPathTerminator;
@@ -1421,9 +1524,6 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
     linkLibs += " ";
   }
 
-  // Write the library flags to the build rule.
-  fout << linkLibs;
-
   // Check what kind of rpath flags to use.
   if (cli.GetRuntimeSep().empty()) {
     // Each rpath entry gets its own option ("-R a -R b -R c")
@@ -1434,7 +1534,7 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
     for (std::vector<std::string>::iterator ri = runtimeDirs.begin();
          ri != runtimeDirs.end(); ++ri) {
       rpath += cli.GetRuntimeFlag();
-      rpath += this->Convert(*ri, NONE, shellFormat);
+      rpath += this->ConvertToOutputFormat(*ri, shellFormat);
       rpath += " ";
     }
     fout << rpath;
@@ -1450,6 +1550,9 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
     }
   }
 
+  // Write the library flags to the build rule.
+  fout << linkLibs;
+
   // Add the linker runtime search path if any.
   std::string rpath_link = cli.GetRPathLinkString();
   if (!cli.GetRPathLinkFlag().empty() && !rpath_link.empty()) {
@@ -1475,16 +1578,12 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
                                             const std::string& config)
 {
   // Only add Mac OS X specific flags on Darwin platforms (OSX and iphone):
-  if (!this->Makefile->IsOn("APPLE")) {
-    return;
-  }
-
-  if (this->EmitUniversalBinaryFlags) {
+  if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
     std::vector<std::string> archs;
     target->GetAppleArchs(config, archs);
     const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
     if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
-      sysroot = 0;
+      sysroot = CM_NULLPTR;
     }
     std::string sysrootFlagVar =
       std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
@@ -1508,7 +1607,7 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
       flags += " ";
       flags += sysrootFlag;
       flags += " ";
-      flags += this->Convert(sysroot, NONE, SHELL);
+      flags += this->ConvertToOutputFormat(sysroot, SHELL);
     }
 
     if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
@@ -1824,7 +1923,7 @@ void cmLocalGenerator::AddVisibilityPresetFlags(
   }
 
   std::string warnCMP0063;
-  std::string* pWarnCMP0063 = 0;
+  std::string* pWarnCMP0063 = CM_NULLPTR;
   if (target->GetType() != cmState::SHARED_LIBRARY &&
       target->GetType() != cmState::MODULE_LIBRARY &&
       !target->IsExecutableWithExports()) {
@@ -1935,7 +2034,7 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
                                                    std::string const& lang,
                                                    int targetType)
 {
-  const char* picFlags = 0;
+  const char* picFlags = CM_NULLPTR;
 
   if (targetType == cmState::EXECUTABLE) {
     std::string flagsVar = "CMAKE_";
@@ -1999,7 +2098,7 @@ void cmLocalGenerator::AppendFlagEscape(std::string& flags,
 }
 
 void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
-                                     const char* defines_list)
+                                     const char* defines_list) const
 {
   // Short-circuit if there are no definitions.
   if (!defines_list) {
@@ -2013,7 +2112,8 @@ void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
 }
 
 void cmLocalGenerator::AppendDefines(
-  std::set<std::string>& defines, const std::vector<std::string>& defines_vec)
+  std::set<std::string>& defines,
+  const std::vector<std::string>& defines_vec) const
 {
   for (std::vector<std::string>::const_iterator di = defines_vec.begin();
        di != defines_vec.end(); ++di) {
@@ -2115,7 +2215,7 @@ const char* cmLocalGenerator::GetFeature(const std::string& feature,
     }
     snp = snp.GetBuildsystemDirectoryParent();
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 std::string cmLocalGenerator::GetProjectName() const
@@ -2136,10 +2236,11 @@ std::string cmLocalGenerator::ConstructComment(
     std::string comment;
     comment = "Generating ";
     const char* sep = "";
+    std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
     for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin();
          o != ccg.GetOutputs().end(); ++o) {
       comment += sep;
-      comment += this->Convert(*o, cmOutputConverter::START_OUTPUT);
+      comment += this->ConvertToRelativePath(currentBinaryDir, *o);
       sep = ", ";
     }
     return comment;
@@ -2178,7 +2279,7 @@ void cmLocalGenerator::GenerateTargetInstallRules(
 
     // Include the user-specified pre-install script for this target.
     if (const char* preinstall = (*l)->GetProperty("PRE_INSTALL_SCRIPT")) {
-      cmInstallScriptGenerator g(preinstall, false, 0, false);
+      cmInstallScriptGenerator g(preinstall, false, CM_NULLPTR, false);
       g.Generate(os, config, configurationTypes);
     }
 
@@ -2231,7 +2332,7 @@ void cmLocalGenerator::GenerateTargetInstallRules(
 
     // Include the user-specified post-install script for this target.
     if (const char* postinstall = (*l)->GetProperty("POST_INSTALL_SCRIPT")) {
-      cmInstallScriptGenerator g(postinstall, false, 0, false);
+      cmInstallScriptGenerator g(postinstall, false, CM_NULLPTR, false);
       g.Generate(os, config, configurationTypes);
     }
   }
@@ -2263,10 +2364,9 @@ static bool cmLocalGeneratorShortenObjectName(std::string& objName,
 
     // The object name is now short enough.
     return true;
-  } else {
-    // The object name could not be shortened enough.
-    return false;
   }
+  // The object name could not be shortened enough.
+  return false;
 }
 
 bool cmLocalGeneratorCheckObjectName(std::string& objName,
@@ -2280,15 +2380,13 @@ bool cmLocalGeneratorCheckObjectName(std::string& objName,
     if (objName.size() > max_obj_len) {
       // The current object file name is too long.  Try to shorten it.
       return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
-    } else {
-      // The object file name is short enough.
-      return true;
     }
-  } else {
-    // The build directory in which the object will be stored is
-    // already too deep.
-    return false;
+    // The object file name is short enough.
+    return true;
   }
+  // The build directory in which the object will be stored is
+  // already too deep.
+  return false;
 }
 #endif
 
@@ -2376,7 +2474,8 @@ std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
 }
 
 void cmLocalGenerator::ComputeObjectFilenames(
-  std::map<cmSourceFile const*, std::string>&, cmGeneratorTarget const*)
+  std::map<cmSourceFile const*, std::string>& /*unused*/,
+  cmGeneratorTarget const* /*unused*/)
 {
 }
 
@@ -2409,13 +2508,15 @@ std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
   const char* fullPath = source.GetFullPath().c_str();
 
   // Try referencing the source relative to the source tree.
-  std::string relFromSource = this->Convert(fullPath, START);
+  std::string relFromSource =
+    this->ConvertToRelativePath(this->GetCurrentSourceDirectory(), fullPath);
   assert(!relFromSource.empty());
   bool relSource = !cmSystemTools::FileIsFullPath(relFromSource.c_str());
   bool subSource = relSource && relFromSource[0] != '.';
 
   // Try referencing the source relative to the binary tree.
-  std::string relFromBinary = this->Convert(fullPath, START_OUTPUT);
+  std::string relFromBinary =
+    this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), fullPath);
   assert(!relFromBinary.empty());
   bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary.c_str());
   bool subBinary = relBinary && relFromBinary[0] != '.';
@@ -2511,7 +2612,7 @@ const char* cmLocalGenerator::GetCurrentSourceDirectory() const
 }
 
 std::string cmLocalGenerator::GetTargetDirectory(
-  const cmGeneratorTarget*) const
+  const cmGeneratorTarget* /*unused*/) const
 {
   cmSystemTools::Error("GetTargetDirectory"
                        " called on cmLocalGenerator");
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index 5c603a6..19469be 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -1,30 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalGenerator_h
 #define cmLocalGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
+#include "cmListFileCache.h"
 #include "cmOutputConverter.h"
+#include "cmPolicies.h"
 #include "cmState.h"
 #include "cmake.h"
 
-class cmMakefile;
-class cmGlobalGenerator;
+#include <cm_kwiml.h>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string.h>
+#include <string>
+#include <vector>
+
+class cmCustomCommandGenerator;
 class cmGeneratorTarget;
-class cmTargetManifest;
+class cmGlobalGenerator;
+class cmMakefile;
 class cmSourceFile;
-class cmCustomCommand;
-class cmCustomCommandGenerator;
 
 /** \class cmLocalGenerator
  * \brief Create required build files for a directory.
@@ -138,13 +137,15 @@ public:
    * Encode a list of preprocessor definitions for the compiler
    * command line.
    */
-  void AppendDefines(std::set<std::string>& defines, const char* defines_list);
-  void AppendDefines(std::set<std::string>& defines, std::string defines_list)
+  void AppendDefines(std::set<std::string>& defines,
+                     const char* defines_list) const;
+  void AppendDefines(std::set<std::string>& defines,
+                     std::string defines_list) const
   {
     this->AppendDefines(defines, defines_list.c_str());
   }
   void AppendDefines(std::set<std::string>& defines,
-                     const std::vector<std::string>& defines_vec);
+                     const std::vector<std::string>& defines_vec) const;
 
   /**
    * Join a set of defines into a definesString with a space separator.
@@ -200,7 +201,7 @@ public:
   void AddCompileDefinitions(std::set<std::string>& defines,
                              cmGeneratorTarget const* target,
                              const std::string& config,
-                             const std::string& lang);
+                             const std::string& lang) const;
 
   std::string GetProjectName() const;
 
@@ -298,9 +299,9 @@ public:
   std::string ConstructComment(cmCustomCommandGenerator const& ccg,
                                const char* default_comment = "");
   // Compute object file names.
-  std::string GetObjectFileNameWithoutTarget(const cmSourceFile& source,
-                                             std::string const& dir_max,
-                                             bool* hasSourceExtension = 0);
+  std::string GetObjectFileNameWithoutTarget(
+    const cmSourceFile& source, std::string const& dir_max,
+    bool* hasSourceExtension = CM_NULLPTR);
 
   /** Fill out the static linker flags for the given target.  */
   void GetStaticLibraryFlags(std::string& flags, std::string const& config,
@@ -308,14 +309,26 @@ public:
 
   /** Fill out these strings for the given target.  Libraries to link,
    *  flags, and linkflags. */
-  void GetTargetFlags(std::string& linkLibs, std::string& flags,
-                      std::string& linkFlags, std::string& frameworkPath,
-                      std::string& linkPath, cmGeneratorTarget* target,
-                      bool useWatcomQuote);
+  void GetTargetFlags(const std::string& config, std::string& linkLibs,
+                      std::string& flags, std::string& linkFlags,
+                      std::string& frameworkPath, std::string& linkPath,
+                      cmGeneratorTarget* target, bool useWatcomQuote);
+  void GetTargetDefines(cmGeneratorTarget const* target,
+                        std::string const& config, std::string const& lang,
+                        std::set<std::string>& defines) const;
+  void GetTargetCompileFlags(cmGeneratorTarget* target,
+                             std::string const& config,
+                             std::string const& lang, std::string& flags);
+
+  std::string GetFrameworkFlags(std::string const& l,
+                                std::string const& config,
+                                cmGeneratorTarget* target);
+  virtual std::string GetTargetFortranFlags(cmGeneratorTarget const* target,
+                                            std::string const& config);
 
   virtual void ComputeObjectFilenames(
     std::map<cmSourceFile const*, std::string>& mapping,
-    cmGeneratorTarget const* gt = 0);
+    cmGeneratorTarget const* gt = CM_NULLPTR);
 
   bool IsWindowsShell() const;
   bool IsWatcomWMake() const;
@@ -364,6 +377,7 @@ protected:
 
   cmMakefile* Makefile;
   cmState::Snapshot StateSnapshot;
+  cmListFileBacktrace DirectoryBacktrace;
   cmGlobalGenerator* GlobalGenerator;
   std::map<std::string, std::string> UniqueObjectNamesMap;
   std::string::size_type ObjectPathMax;
diff --git a/Source/cmLocalGhsMultiGenerator.cxx b/Source/cmLocalGhsMultiGenerator.cxx
index 01537dd..157b32e 100644
--- a/Source/cmLocalGhsMultiGenerator.cxx
+++ b/Source/cmLocalGhsMultiGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalGhsMultiGenerator.h"
 
 #include "cmGeneratedFileStream.h"
diff --git a/Source/cmLocalGhsMultiGenerator.h b/Source/cmLocalGhsMultiGenerator.h
index b6a9a33..aa842d7 100644
--- a/Source/cmLocalGhsMultiGenerator.h
+++ b/Source/cmLocalGhsMultiGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Geoffrey Viola <geoffrey.viola at asirobots.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalGhsMultiGenerator_h
 #define cmLocalGhsMultiGenerator_h
 
diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx
index 6c231c3..11b87e3 100644
--- a/Source/cmLocalNinjaGenerator.cxx
+++ b/Source/cmLocalNinjaGenerator.cxx
@@ -1,31 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalNinjaGenerator.h"
 
+#include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
 #include "cmGlobalNinjaGenerator.h"
 #include "cmMakefile.h"
 #include "cmNinjaTargetGenerator.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
+#include <algorithm>
 #include <assert.h>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
 
 cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
                                              cmMakefile* mf)
-  : cmLocalCommonGenerator(gg, mf)
+  : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
   , HomeRelativeOutputPath("")
 {
   this->TargetImplib = "$TARGET_IMPLIB";
@@ -41,8 +40,8 @@ void cmLocalNinjaGenerator::Generate()
 {
   // Compute the path to use when referencing the current output
   // directory from the top output directory.
-  this->HomeRelativeOutputPath = this->Convert(
-    this->GetCurrentBinaryDirectory(), cmOutputConverter::HOME_OUTPUT);
+  this->HomeRelativeOutputPath = this->ConvertToRelativePath(
+    this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
   if (this->HomeRelativeOutputPath == ".") {
     this->HomeRelativeOutputPath = "";
   }
@@ -81,8 +80,9 @@ void cmLocalNinjaGenerator::Generate()
       tg->Generate();
       // Add the target to "all" if required.
       if (!this->GetGlobalNinjaGenerator()->IsExcluded(
-            this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t))
+            this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t)) {
         this->GetGlobalNinjaGenerator()->AddDependencyToAll(*t);
+      }
       delete tg;
     }
   }
@@ -131,9 +131,12 @@ std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
   std::string const& path, cmOutputConverter::OutputFormat format,
   bool forceFullPaths)
 {
-  return this->Convert(path, forceFullPaths ? cmOutputConverter::FULL
-                                            : cmOutputConverter::HOME_OUTPUT,
-                       format);
+  if (forceFullPaths) {
+    return this->ConvertToOutputFormat(cmSystemTools::CollapseFullPath(path),
+                                       format);
+  }
+  return this->ConvertToOutputFormat(
+    this->ConvertToRelativePath(this->GetBinaryDirectory(), path), format);
 }
 
 // Private methods.
@@ -257,8 +260,9 @@ void cmLocalNinjaGenerator::WriteProcessedMakefile(std::ostream& os)
   os << "# Write statements declared in CMakeLists.txt:" << std::endl
      << "# " << this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")
      << std::endl;
-  if (this->IsRootMakefile())
+  if (this->IsRootMakefile()) {
     os << "# Which is the root file." << std::endl;
+  }
   cmGlobalNinjaGenerator::WriteDivider(os);
   os << std::endl;
 }
@@ -282,9 +286,10 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps(
   for (std::vector<std::string>::const_iterator i = deps.begin();
        i != deps.end(); ++i) {
     std::string dep;
-    if (this->GetRealDependency(*i, this->GetConfigName(), dep))
+    if (this->GetRealDependency(*i, this->GetConfigName(), dep)) {
       ninjaDeps.push_back(
         this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
+    }
   }
 }
 
@@ -294,12 +299,13 @@ std::string cmLocalNinjaGenerator::BuildCommandLine(
   // If we have no commands but we need to build a command anyway, use ":".
   // This happens when building a POST_BUILD value for link targets that
   // don't use POST_BUILD.
-  if (cmdLines.empty())
+  if (cmdLines.empty()) {
 #ifdef _WIN32
     return "cd .";
 #else
     return ":";
 #endif
+  }
 
   std::ostringstream cmd;
   for (std::vector<std::string>::const_iterator li = cmdLines.begin();
@@ -332,8 +338,9 @@ void cmLocalNinjaGenerator::AppendCustomCommandLines(
 {
   if (ccg.GetNumberOfCommands() > 0) {
     std::string wd = ccg.GetWorkingDirectory();
-    if (wd.empty())
+    if (wd.empty()) {
       wd = this->GetCurrentBinaryDirectory();
+    }
 
     std::ostringstream cdCmd;
 #ifdef _WIN32
@@ -361,8 +368,9 @@ void cmLocalNinjaGenerator::AppendCustomCommandLines(
 void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
   cmCustomCommand const* cc, const cmNinjaDeps& orderOnlyDeps)
 {
-  if (this->GetGlobalNinjaGenerator()->SeenCustomCommand(cc))
+  if (this->GetGlobalNinjaGenerator()->SeenCustomCommand(cc)) {
     return;
+  }
 
   cmCustomCommandGenerator ccg(*cc, this->GetConfigName(), this);
 
@@ -391,8 +399,9 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
   this->AppendCustomCommandDeps(ccg, ninjaDeps);
 
   for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end();
-       ++i)
+       ++i) {
     this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i);
+  }
 
   std::vector<std::string> cmdLines;
   this->AppendCustomCommandLines(ccg, cmdLines);
@@ -405,7 +414,8 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
   } else {
     this->GetGlobalNinjaGenerator()->WriteCustomCommandBuild(
       this->BuildCommandLine(cmdLines), this->ConstructComment(ccg),
-      "Custom command for " + ninjaOutputs[0], cc->GetUsesTerminal(),
+      "Custom command for " + ninjaOutputs[0], cc->GetDepfile(),
+      cc->GetUsesTerminal(),
       /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, ninjaDeps,
       orderOnlyDeps);
   }
@@ -443,13 +453,14 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
     std::set<cmGeneratorTarget*>::iterator j = i->second.begin();
     assert(j != i->second.end());
     std::vector<std::string> ccTargetDeps;
-    this->AppendTargetDepends(*j, ccTargetDeps);
+    this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j,
+                                                                ccTargetDeps);
     std::sort(ccTargetDeps.begin(), ccTargetDeps.end());
     ++j;
 
     for (; j != i->second.end(); ++j) {
       std::vector<std::string> jDeps, depsIntersection;
-      this->AppendTargetDepends(*j, jDeps);
+      this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps);
       std::sort(jDeps.begin(), jDeps.end());
       std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(),
                             jDeps.begin(), jDeps.end(),
@@ -478,12 +489,15 @@ std::string cmLocalNinjaGenerator::MakeCustomLauncher(
   std::string output;
   const std::vector<std::string>& outputs = ccg.GetOutputs();
   if (!outputs.empty()) {
-    cmOutputConverter::RelativeRoot relative_root =
-      ccg.GetWorkingDirectory().empty() ? cmOutputConverter::START_OUTPUT
-                                        : cmOutputConverter::NONE;
-
-    output =
-      this->Convert(outputs[0], relative_root, cmOutputConverter::SHELL);
+    if (ccg.GetWorkingDirectory().empty()) {
+      output = this->ConvertToOutputFormat(
+        this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
+                                    outputs[0]),
+        cmOutputConverter::SHELL);
+    } else {
+      output =
+        this->ConvertToOutputFormat(outputs[0], cmOutputConverter::SHELL);
+    }
   }
   vars.Output = output.c_str();
 
diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h
index 9899360..875f8c6 100644
--- a/Source/cmLocalNinjaGenerator.h
+++ b/Source/cmLocalNinjaGenerator.h
@@ -1,25 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalNinjaGenerator_h
 #define cmLocalNinjaGenerator_h
 
-#include "cmLocalCommonGenerator.h"
+#include <cmConfigure.h>
 
+#include "cmLocalCommonGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmNinjaTypes.h"
+#include "cmOutputConverter.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
+class cmCustomCommand;
 class cmCustomCommandGenerator;
-class cmGlobalNinjaGenerator;
 class cmGeneratedFileStream;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmGlobalNinjaGenerator;
+class cmMakefile;
+class cmSourceFile;
 class cmake;
 
 /**
@@ -34,12 +38,12 @@ class cmLocalNinjaGenerator : public cmLocalCommonGenerator
 public:
   cmLocalNinjaGenerator(cmGlobalGenerator* gg, cmMakefile* mf);
 
-  virtual ~cmLocalNinjaGenerator();
+  ~cmLocalNinjaGenerator() CM_OVERRIDE;
 
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
-  virtual std::string GetTargetDirectory(
-    cmGeneratorTarget const* target) const;
+  std::string GetTargetDirectory(cmGeneratorTarget const* target) const
+    CM_OVERRIDE;
 
   const cmGlobalNinjaGenerator* GetGlobalNinjaGenerator() const;
   cmGlobalNinjaGenerator* GetGlobalNinjaGenerator();
@@ -72,19 +76,19 @@ public:
   void AppendCustomCommandDeps(cmCustomCommandGenerator const& ccg,
                                cmNinjaDeps& ninjaDeps);
 
-  virtual std::string ConvertToLinkReference(
-    std::string const& lib,
-    cmOutputConverter::OutputFormat format = cmOutputConverter::SHELL);
+  std::string ConvertToLinkReference(std::string const& lib,
+                                     cmOutputConverter::OutputFormat format =
+                                       cmOutputConverter::SHELL) CM_OVERRIDE;
 
-  virtual void ComputeObjectFilenames(
+  void ComputeObjectFilenames(
     std::map<cmSourceFile const*, std::string>& mapping,
-    cmGeneratorTarget const* gt = 0);
+    cmGeneratorTarget const* gt = CM_NULLPTR) CM_OVERRIDE;
 
 protected:
-  virtual std::string ConvertToIncludeReference(
+  std::string ConvertToIncludeReference(
     std::string const& path,
     cmOutputConverter::OutputFormat format = cmOutputConverter::SHELL,
-    bool forceFullPaths = false);
+    bool forceFullPaths = false) CM_OVERRIDE;
 
 private:
   cmGeneratedFileStream& GetBuildFileStream() const;
diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx
index f60a595..8825b46 100644
--- a/Source/cmLocalUnixMakefileGenerator3.cxx
+++ b/Source/cmLocalUnixMakefileGenerator3.cxx
@@ -1,24 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalUnixMakefileGenerator3.h"
 
 #include "cmAlgorithms.h"
+#include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmFileTimeComparison.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmMakefileTargetGenerator.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmVersion.h"
 #include "cmake.h"
 
@@ -30,11 +28,14 @@
 #include "cmDependsJava.h"
 #endif
 
-#include <cmsys/Terminal.h>
-#include <cmsys/auto_ptr.hxx>
-
 #include <algorithm>
-#include <queue>
+#include <cm_auto_ptr.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Terminal.h>
+#include <functional>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
 
 // Escape special characters in Makefile dependency lines
 class cmMakeSafe
@@ -84,7 +85,7 @@ static std::string cmSplitExtension(std::string const& in, std::string& base)
 
 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
   cmGlobalGenerator* gg, cmMakefile* mf)
-  : cmLocalCommonGenerator(gg, mf)
+  : cmLocalCommonGenerator(gg, mf, mf->GetCurrentBinaryDirectory())
 {
   this->MakefileVariableSize = 0;
   this->ColorMakefile = false;
@@ -121,7 +122,7 @@ void cmLocalUnixMakefileGenerator3::Generate()
     if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
       continue;
     }
-    cmsys::auto_ptr<cmMakefileTargetGenerator> tg(
+    CM_AUTO_PTR<cmMakefileTargetGenerator> tg(
       cmMakefileTargetGenerator::New(*t));
     if (tg.get()) {
       tg->WriteRuleFiles();
@@ -140,8 +141,8 @@ void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
 {
   // Compute the path to use when referencing the current output
   // directory from the top output directory.
-  this->HomeRelativeOutputPath = this->Convert(
-    this->GetCurrentBinaryDirectory(), cmOutputConverter::HOME_OUTPUT);
+  this->HomeRelativeOutputPath = this->ConvertToRelativePath(
+    this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
   if (this->HomeRelativeOutputPath == ".") {
     this->HomeRelativeOutputPath = "";
   }
@@ -340,8 +341,8 @@ void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
     std::vector<std::string> depends;
     depends.push_back(output);
     std::vector<std::string> no_commands;
-    this->WriteMakeRule(ruleFileStream, 0, outNoExt, depends, no_commands,
-                        true, true);
+    this->WriteMakeRule(ruleFileStream, CM_NULLPTR, outNoExt, depends,
+                        no_commands, true, true);
     inHelp = false;
   }
 
@@ -358,7 +359,7 @@ void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
       this->GetRecursiveMakeCall(tgtMakefileName.c_str(), targetName));
   }
   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                        cmOutputConverter::START_OUTPUT);
+                        this->GetCurrentBinaryDirectory());
 
   // Write the rule to the makefile.
   std::vector<std::string> no_depends;
@@ -398,7 +399,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
       commands.push_back(
         this->GetRecursiveMakeCall(makefile2.c_str(), localName));
       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                            cmOutputConverter::START_OUTPUT);
+                            this->GetCurrentBinaryDirectory());
       this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
                           localName, depends, commands, true);
 
@@ -423,7 +424,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
       commands.push_back(
         this->GetRecursiveMakeCall(makefileName.c_str(), makeTargetName));
       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                            cmOutputConverter::START_OUTPUT);
+                            this->GetCurrentBinaryDirectory());
       this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
                           localName, depends, commands, true);
 
@@ -439,7 +440,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
         commands.push_back(
           this->GetRecursiveMakeCall(makefile2.c_str(), makeTargetName));
         this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                              cmOutputConverter::START_OUTPUT);
+                              this->GetCurrentBinaryDirectory());
         this->WriteMakeRule(ruleFileStream,
                             "Manual pre-install relink rule for target.",
                             localName, depends, commands, true);
@@ -546,8 +547,8 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
   }
 
   // Construct the left hand side of the rule.
-  std::string tgt = this->Convert(target, cmOutputConverter::HOME_OUTPUT,
-                                  cmOutputConverter::MAKERULE);
+  std::string tgt = cmSystemTools::ConvertToOutputPath(
+    this->ConvertToRelativePath(this->GetBinaryDirectory(), target).c_str());
 
   const char* space = "";
   if (tgt.size() == 1) {
@@ -571,11 +572,12 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
   } else {
     // Split dependencies into multiple rule lines.  This allows for
     // very long dependency lists even on older make implementations.
+    std::string binDir = this->GetBinaryDirectory();
     for (std::vector<std::string>::const_iterator dep = depends.begin();
          dep != depends.end(); ++dep) {
       replace = *dep;
-      replace = this->Convert(replace, cmOutputConverter::HOME_OUTPUT,
-                              cmOutputConverter::MAKERULE);
+      replace = cmSystemTools::ConvertToOutputPath(
+        this->ConvertToRelativePath(binDir, replace).c_str());
       os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n";
     }
   }
@@ -592,8 +594,8 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
   }
 }
 
-std::string cmLocalUnixMakefileGenerator3::ConvertShellCommand(
-  std::string const& cmd, cmOutputConverter::RelativeRoot root)
+std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
+  std::string const& cmd)
 {
   if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd.c_str()) &&
       cmd.find_first_of("( )") != cmd.npos) {
@@ -602,11 +604,10 @@ std::string cmLocalUnixMakefileGenerator3::ConvertShellCommand(
     // lines with shell redirection operators.
     std::string scmd;
     if (cmSystemTools::GetShortPath(cmd, scmd)) {
-      return this->Convert(scmd, cmOutputConverter::NONE,
-                           cmOutputConverter::SHELL);
+      return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
     }
   }
-  return this->Convert(cmd, root, cmOutputConverter::SHELL);
+  return std::string();
 }
 
 void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
@@ -638,19 +639,25 @@ void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
 #endif
   }
 
+  std::string cmakeShellCommand =
+    this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
+  if (cmakeShellCommand.empty()) {
+    cmakeShellCommand = this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
+      cmOutputConverter::SHELL);
+  }
+
   /* clang-format off */
   makefileStream
     << "# The CMake executable.\n"
     << "CMAKE_COMMAND = "
-    << this->ConvertShellCommand(cmSystemTools::GetCMakeCommand(),
-                                 cmOutputConverter::FULL)
+    << cmakeShellCommand
     << "\n"
     << "\n";
   makefileStream
     << "# The command to remove a file.\n"
     << "RM = "
-    << this->ConvertShellCommand(cmSystemTools::GetCMakeCommand(),
-                                 cmOutputConverter::FULL)
+    << cmakeShellCommand
     << " -E remove -f\n"
     << "\n";
   makefileStream
@@ -660,16 +667,16 @@ void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
   makefileStream
     << "# The top-level source directory on which CMake was run.\n"
     << "CMAKE_SOURCE_DIR = "
-    << this->Convert(this->GetSourceDirectory(),
-                     cmOutputConverter::FULL,
+    << this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(this->GetSourceDirectory()),
                      cmOutputConverter::SHELL)
     << "\n"
     << "\n";
   makefileStream
     << "# The top-level build directory on which CMake was run.\n"
     << "CMAKE_BINARY_DIR = "
-    << this->Convert(this->GetBinaryDirectory(),
-                     cmOutputConverter::FULL,
+    << this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(this->GetBinaryDirectory()),
                      cmOutputConverter::SHELL)
     << "\n"
     << "\n";
@@ -703,8 +710,8 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
   // Add a fake suffix to keep HP happy.  Must be max 32 chars for SGI make.
   std::vector<std::string> depends;
   depends.push_back(".hpux_make_needs_suffix_list");
-  this->WriteMakeRule(makefileStream, 0, ".SUFFIXES", depends, no_commands,
-                      false);
+  this->WriteMakeRule(makefileStream, CM_NULLPTR, ".SUFFIXES", depends,
+                      no_commands, false);
   if (this->IsWatcomWMake()) {
     // Switch on WMake feature, if an error or interrupt occurs during
     // makefile processing, the current target being made may be deleted
@@ -784,8 +791,8 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
     std::string runRule =
       "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
     runRule += " --check-build-system ";
-    runRule += this->Convert(cmakefileName, cmOutputConverter::NONE,
-                             cmOutputConverter::SHELL);
+    runRule +=
+      this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
     runRule += " 0";
 
     std::vector<std::string> no_depends;
@@ -793,7 +800,7 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
     commands.push_back(runRule);
     if (!this->IsRootMakefile()) {
       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                            cmOutputConverter::START_OUTPUT);
+                            this->GetCurrentBinaryDirectory());
     }
     this->WriteMakeRule(
       makefileStream, "Special rule to run CMake to check the build system "
@@ -829,8 +836,7 @@ std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
 {
   std::string dir = this->HomeRelativeOutputPath;
   dir += this->GetTargetDirectory(target);
-  return this->Convert(dir, cmOutputConverter::NONE,
-                       cmOutputConverter::UNCHANGED);
+  return dir;
 }
 
 void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
@@ -900,19 +906,19 @@ void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
 
 void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
   std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
-  cmGeneratorTarget* target, cmOutputConverter::RelativeRoot relative)
+  cmGeneratorTarget* target, std::string const& relative)
 {
   for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
        i != ccs.end(); ++i) {
     cmCustomCommandGenerator ccg(*i, this->ConfigName, this);
-    this->AppendCustomCommand(commands, ccg, target, true, relative);
+    this->AppendCustomCommand(commands, ccg, target, relative, true);
   }
 }
 
 void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
   std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
-  cmGeneratorTarget* target, bool echo_comment,
-  cmOutputConverter::RelativeRoot relative, std::ostream* content)
+  cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
+  std::ostream* content)
 {
   // Optionally create a command to display the custom command's
   // comment text.  This is used for pre-build, pre-link, and
@@ -938,6 +944,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
 
   // Add each command line to the set of commands.
   std::vector<std::string> commands1;
+  std::string currentBinDir = this->GetCurrentBinaryDirectory();
   for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
     // Build the command line in a single string.
     std::string cmd = ccg.GetCommand(c);
@@ -962,7 +969,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
       // working directory will be the start-output directory.
       bool had_slash = cmd.find('/') != cmd.npos;
       if (workingDir.empty()) {
-        cmd = this->Convert(cmd, cmOutputConverter::START_OUTPUT);
+        cmd = this->ConvertToRelativePath(currentBinDir, cmd);
       }
       bool has_slash = cmd.find('/') != cmd.npos;
       if (had_slash && !has_slash) {
@@ -971,10 +978,45 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
         // without the current directory being in the search path.
         cmd = "./" + cmd;
       }
-      std::string launcher = this->MakeLauncher(
-        ccg, target, workingDir.empty() ? cmOutputConverter::START_OUTPUT
-                                        : cmOutputConverter::NONE);
-      cmd = launcher + this->ConvertShellCommand(cmd, cmOutputConverter::NONE);
+
+      std::string launcher;
+      // Short-circuit if there is no launcher.
+      const char* prop = "RULE_LAUNCH_CUSTOM";
+      const char* val = this->GetRuleLauncher(target, prop);
+      if (val && *val) {
+        // Expand rules in the empty string.  It may insert the launcher and
+        // perform replacements.
+        RuleVariables vars;
+        vars.RuleLauncher = prop;
+        vars.CMTarget = target;
+        std::string output;
+        const std::vector<std::string>& outputs = ccg.GetOutputs();
+        if (!outputs.empty()) {
+          if (workingDir.empty()) {
+            output = this->ConvertToOutputFormat(
+              this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
+                                          outputs[0]),
+              cmOutputConverter::SHELL);
+
+          } else {
+            output = this->ConvertToOutputFormat(outputs[0],
+                                                 cmOutputConverter::SHELL);
+          }
+        }
+        vars.Output = output.c_str();
+
+        this->ExpandRuleVariables(launcher, vars);
+        if (!launcher.empty()) {
+          launcher += " ";
+        }
+      }
+
+      std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
+      if (shellCommand.empty()) {
+        shellCommand =
+          this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
+      }
+      cmd = launcher + shellCommand;
 
       ccg.AppendArguments(c, cmd);
       if (content) {
@@ -1017,42 +1059,12 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
   commands.insert(commands.end(), commands1.begin(), commands1.end());
 }
 
-std::string cmLocalUnixMakefileGenerator3::MakeLauncher(
-  cmCustomCommandGenerator const& ccg, cmGeneratorTarget* target,
-  cmOutputConverter::RelativeRoot relative)
-{
-  // Short-circuit if there is no launcher.
-  const char* prop = "RULE_LAUNCH_CUSTOM";
-  const char* val = this->GetRuleLauncher(target, prop);
-  if (!(val && *val)) {
-    return "";
-  }
-
-  // Expand rules in the empty string.  It may insert the launcher and
-  // perform replacements.
-  RuleVariables vars;
-  vars.RuleLauncher = prop;
-  vars.CMTarget = target;
-  std::string output;
-  const std::vector<std::string>& outputs = ccg.GetOutputs();
-  if (!outputs.empty()) {
-    output = this->Convert(outputs[0], relative, cmOutputConverter::SHELL);
-  }
-  vars.Output = output.c_str();
-
-  std::string launcher;
-  this->ExpandRuleVariables(launcher, vars);
-  if (!launcher.empty()) {
-    launcher += " ";
-  }
-  return launcher;
-}
-
 void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
   std::vector<std::string>& commands, const std::vector<std::string>& files,
   cmGeneratorTarget* target, const char* filename)
 {
-  std::string cleanfile = this->GetCurrentBinaryDirectory();
+  std::string currentBinDir = this->GetCurrentBinaryDirectory();
+  std::string cleanfile = currentBinDir;
   cleanfile += "/";
   cleanfile += this->GetTargetDirectory(target);
   cleanfile += "/cmake_clean";
@@ -1061,8 +1073,7 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
     cleanfile += filename;
   }
   cleanfile += ".cmake";
-  std::string cleanfilePath =
-    this->Convert(cleanfile, cmOutputConverter::FULL);
+  std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile);
   cmsys::ofstream fout(cleanfilePath.c_str());
   if (!fout) {
     cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
@@ -1071,15 +1082,15 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
     fout << "file(REMOVE_RECURSE\n";
     for (std::vector<std::string>::const_iterator f = files.begin();
          f != files.end(); ++f) {
-      std::string fc = this->Convert(*f, cmOutputConverter::START_OUTPUT,
-                                     cmOutputConverter::UNCHANGED);
+      std::string fc = this->ConvertToRelativePath(currentBinDir, *f);
       fout << "  " << cmOutputConverter::EscapeForCMake(fc) << "\n";
     }
     fout << ")\n";
   }
   std::string remove = "$(CMAKE_COMMAND) -P ";
-  remove += this->Convert(cleanfile, cmOutputConverter::START_OUTPUT,
-                          cmOutputConverter::SHELL);
+  remove += this->ConvertToOutputFormat(
+    this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), cleanfile),
+    cmOutputConverter::SHELL);
   commands.push_back(remove);
 
   // For the main clean rule add per-language cleaning.
@@ -1148,8 +1159,9 @@ void cmLocalUnixMakefileGenerator3::AppendEcho(
           cmd += color_name;
           if (progress) {
             cmd += "--progress-dir=";
-            cmd += this->Convert(progress->Dir, cmOutputConverter::FULL,
-                                 cmOutputConverter::SHELL);
+            cmd += this->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(progress->Dir),
+              cmOutputConverter::SHELL);
             cmd += " ";
             cmd += "--progress-num=";
             cmd += progress->Arg;
@@ -1164,7 +1176,7 @@ void cmLocalUnixMakefileGenerator3::AppendEcho(
       line = "";
 
       // Progress appears only on first line.
-      progress = 0;
+      progress = CM_NULLPTR;
 
       // Terminate on end-of-string.
       if (*c == '\0') {
@@ -1322,7 +1334,7 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
   // not be considered.
   std::map<std::string, cmDepends::DependencyVector> validDependencies;
   bool needRescanDependencies = false;
-  if (needRescanDirInfo == false) {
+  if (!needRescanDirInfo) {
     cmDependsC checker;
     checker.SetVerbose(verbose);
     checker.SetFileComparison(ftc);
@@ -1433,7 +1445,7 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
     std::string lang = *li;
 
     // Create the scanner for this language
-    cmDepends* scanner = 0;
+    cmDepends* scanner = CM_NULLPTR;
     if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM") {
       // TODO: Handle RC (resource files) dependencies correctly.
       scanner = new cmDependsC(this, targetDir, lang, &validDeps);
@@ -1558,9 +1570,9 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
       this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
       this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
       this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt,
-                                 cmOutputConverter::START_OUTPUT);
+                                 this->GetCurrentBinaryDirectory());
       this->AppendCustomCommands(commands, gt->GetPostBuildCommands(), gt,
-                                 cmOutputConverter::START_OUTPUT);
+                                 this->GetCurrentBinaryDirectory());
       std::string targetName = gt->GetName();
       this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
                           depends, commands, true);
@@ -1597,15 +1609,16 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   {
     std::ostringstream progCmd;
     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
-    progCmd << this->Convert(progressDir, cmOutputConverter::FULL,
-                             cmOutputConverter::SHELL);
+    progCmd << this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
 
     std::string progressFile = cmake::GetCMakeFilesDirectory();
     progressFile += "/progress.marks";
     std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
     progCmd << " "
-            << this->Convert(progressFileNameFull, cmOutputConverter::FULL,
-                             cmOutputConverter::SHELL);
+            << this->ConvertToOutputFormat(
+                 cmSystemTools::CollapseFullPath(progressFileNameFull),
+                 cmOutputConverter::SHELL);
     commands.push_back(progCmd.str());
   }
   std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
@@ -1613,12 +1626,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   commands.push_back(
     this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                        cmOutputConverter::START_OUTPUT);
+                        this->GetCurrentBinaryDirectory());
   {
     std::ostringstream progCmd;
     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
-    progCmd << this->Convert(progressDir, cmOutputConverter::FULL,
-                             cmOutputConverter::SHELL);
+    progCmd << this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL);
     progCmd << " 0";
     commands.push_back(progCmd.str());
   }
@@ -1633,7 +1646,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   commands.push_back(
     this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                        cmOutputConverter::START_OUTPUT);
+                        this->GetCurrentBinaryDirectory());
   this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
                       depends, commands, true);
   commands.clear();
@@ -1659,7 +1672,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   commands.push_back(
     this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget));
   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                        cmOutputConverter::START_OUTPUT);
+                        this->GetCurrentBinaryDirectory());
   this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
                       "preinstall", depends, commands, true);
   depends.clear();
@@ -1674,12 +1687,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   std::string runRule =
     "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
   runRule += " --check-build-system ";
-  runRule += this->Convert(cmakefileName, cmOutputConverter::NONE,
-                           cmOutputConverter::SHELL);
+  runRule +=
+    this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL);
   runRule += " 1";
   commands.push_back(runRule);
   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
-                        cmOutputConverter::START_OUTPUT);
+                        this->GetCurrentBinaryDirectory());
   this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
                       commands, true);
 }
@@ -1835,9 +1848,9 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
     const std::string& config =
       this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
     this->GetIncludeDirectories(includes, target, l->first, config);
+    std::string binaryDir = this->GetState()->GetBinaryDirectory();
     if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
       const char* sourceDir = this->GetState()->GetSourceDirectory();
-      const char* binaryDir = this->GetState()->GetBinaryDirectory();
       std::vector<std::string>::iterator itr =
         std::remove_if(includes.begin(), includes.end(),
                        ::NotInProjectDir(sourceDir, binaryDir));
@@ -1845,8 +1858,7 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
     }
     for (std::vector<std::string>::iterator i = includes.begin();
          i != includes.end(); ++i) {
-      cmakefileStream << "  \""
-                      << this->Convert(*i, cmOutputConverter::HOME_OUTPUT)
+      cmakefileStream << "  \"" << this->ConvertToRelativePath(binaryDir, *i)
                       << "\"\n";
     }
     cmakefileStream << "  )\n";
@@ -1888,8 +1900,7 @@ std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
   // Call make on the given file.
   std::string cmd;
   cmd += "$(MAKE) -f ";
-  cmd +=
-    this->Convert(makefile, cmOutputConverter::NONE, cmOutputConverter::SHELL);
+  cmd += this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL);
   cmd += " ";
 
   cmGlobalUnixMakefileGenerator3* gg =
@@ -1911,7 +1922,8 @@ std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
   // Add the target.
   if (!tgt.empty()) {
     // The make target is always relative to the top of the build tree.
-    std::string tgt2 = this->Convert(tgt, cmOutputConverter::HOME_OUTPUT);
+    std::string tgt2 =
+      this->ConvertToRelativePath(this->GetBinaryDirectory(), tgt);
 
     // The target may have been written with windows paths.
     cmSystemTools::ConvertToOutputSlashes(tgt2);
@@ -2046,12 +2058,10 @@ void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
 
 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
   std::vector<std::string>& commands, const char* tgtDir,
-  cmOutputConverter::RelativeRoot relRetDir)
+  std::string const& relDir)
 {
-  const char* retDir = this->GetRelativeRootPath(relRetDir);
-
   // do we need to cd?
-  if (!strcmp(tgtDir, retDir)) {
+  if (tgtDir == relDir) {
     return;
   }
 
@@ -2068,19 +2078,18 @@ void cmLocalUnixMakefileGenerator3::CreateCDCommand(
     // back because the shell keeps the working directory between
     // commands.
     std::string cmd = cd_cmd;
-    cmd += this->ConvertToOutputForExisting(tgtDir, relRetDir);
+    cmd += this->ConvertToOutputForExisting(tgtDir);
     commands.insert(commands.begin(), cmd);
 
     // Change back to the starting directory.
     cmd = cd_cmd;
-    cmd += this->ConvertToOutputForExisting(relRetDir, tgtDir);
+    cmd += this->ConvertToOutputForExisting(relDir);
     commands.push_back(cmd);
   } else {
     // On UNIX we must construct a single shell command to change
     // directory and build because make resets the directory between
     // each command.
-    std::string outputForExisting =
-      this->ConvertToOutputForExisting(tgtDir, relRetDir);
+    std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
     std::string prefix = cd_cmd + outputForExisting + " && ";
     std::transform(commands.begin(), commands.end(), commands.begin(),
                    std::bind1st(std::plus<std::string>(), prefix));
diff --git a/Source/cmLocalUnixMakefileGenerator3.h b/Source/cmLocalUnixMakefileGenerator3.h
index a65a1a1..fc5c8e7 100644
--- a/Source/cmLocalUnixMakefileGenerator3.h
+++ b/Source/cmLocalUnixMakefileGenerator3.h
@@ -1,26 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalUnixMakefileGenerator3_h
 #define cmLocalUnixMakefileGenerator3_h
 
-#include "cmLocalCommonGenerator.h"
+#include <cmConfigure.h>
 
-// for cmDepends::DependencyVector
 #include "cmDepends.h"
+#include "cmLocalCommonGenerator.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmCustomCommand;
 class cmCustomCommandGenerator;
-class cmDepends;
-class cmMakefileTargetGenerator;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
 class cmSourceFile;
 
 /** \class cmLocalUnixMakefileGenerator3
@@ -33,14 +31,14 @@ class cmLocalUnixMakefileGenerator3 : public cmLocalCommonGenerator
 {
 public:
   cmLocalUnixMakefileGenerator3(cmGlobalGenerator* gg, cmMakefile* mf);
-  virtual ~cmLocalUnixMakefileGenerator3();
+  ~cmLocalUnixMakefileGenerator3() CM_OVERRIDE;
 
-  virtual void ComputeHomeRelativeOutputPath();
+  void ComputeHomeRelativeOutputPath() CM_OVERRIDE;
 
   /**
    * Generate the makefile for this directory.
    */
-  virtual void Generate();
+  void Generate() CM_OVERRIDE;
 
   // this returns the relative path between the HomeOutputDirectory and this
   // local generators StartOutputDirectory
@@ -90,8 +88,9 @@ public:
                                    const std::string& tgt);
 
   // append flags to a string
-  virtual void AppendFlags(std::string& flags, const std::string& newFlags);
-  virtual void AppendFlags(std::string& flags, const char* newFlags);
+  void AppendFlags(std::string& flags,
+                   const std::string& newFlags) CM_OVERRIDE;
+  void AppendFlags(std::string& flags, const char* newFlags) CM_OVERRIDE;
 
   // append an echo command
   enum EchoColor
@@ -109,18 +108,18 @@ public:
     std::string Arg;
   };
   void AppendEcho(std::vector<std::string>& commands, std::string const& text,
-                  EchoColor color = EchoNormal, EchoProgress const* = 0);
+                  EchoColor color = EchoNormal,
+                  EchoProgress const* = CM_NULLPTR);
 
   /** Get whether the makefile is to have color.  */
   bool GetColorMakefile() const { return this->ColorMakefile; }
 
-  virtual std::string GetTargetDirectory(
-    cmGeneratorTarget const* target) const;
+  std::string GetTargetDirectory(cmGeneratorTarget const* target) const
+    CM_OVERRIDE;
 
   // create a command that cds to the start dir then runs the commands
   void CreateCDCommand(std::vector<std::string>& commands,
-                       const char* targetDir,
-                       cmOutputConverter::RelativeRoot returnDir);
+                       const char* targetDir, std::string const& relDir);
 
   static std::string ConvertToQuotedOutputPath(const char* p,
                                                bool useWatcomQuote);
@@ -130,11 +129,11 @@ public:
 
   /** Called from command-line hook to bring dependencies up to date
       for a target.  */
-  virtual bool UpdateDependencies(const char* tgtInfo, bool verbose,
-                                  bool color);
+  bool UpdateDependencies(const char* tgtInfo, bool verbose,
+                          bool color) CM_OVERRIDE;
 
   /** Called from command-line hook to clear dependencies.  */
-  virtual void ClearDependencies(cmMakefile* mf, bool verbose);
+  void ClearDependencies(cmMakefile* mf, bool verbose) CM_OVERRIDE;
 
   /** write some extra rules such as make test etc */
   void WriteSpecialTargetsTop(std::ostream& makefileStream);
@@ -227,18 +226,20 @@ protected:
                            const std::vector<cmCustomCommand>& ccs);
   void AppendCustomDepend(std::vector<std::string>& depends,
                           cmCustomCommandGenerator const& cc);
-  void AppendCustomCommands(
-    std::vector<std::string>& commands,
-    const std::vector<cmCustomCommand>& ccs, cmGeneratorTarget* target,
-    cmOutputConverter::RelativeRoot relative = cmOutputConverter::HOME_OUTPUT);
-  void AppendCustomCommand(
-    std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
-    cmGeneratorTarget* target, bool echo_comment = false,
-    cmOutputConverter::RelativeRoot relative = cmOutputConverter::HOME_OUTPUT,
-    std::ostream* content = 0);
+  void AppendCustomCommands(std::vector<std::string>& commands,
+                            const std::vector<cmCustomCommand>& ccs,
+                            cmGeneratorTarget* target,
+                            std::string const& relative);
+  void AppendCustomCommand(std::vector<std::string>& commands,
+                           cmCustomCommandGenerator const& ccg,
+                           cmGeneratorTarget* target,
+                           std::string const& relative,
+                           bool echo_comment = false,
+                           std::ostream* content = CM_NULLPTR);
   void AppendCleanCommand(std::vector<std::string>& commands,
                           const std::vector<std::string>& files,
-                          cmGeneratorTarget* target, const char* filename = 0);
+                          cmGeneratorTarget* target,
+                          const char* filename = CM_NULLPTR);
 
   // Helper methods for dependeny updates.
   bool ScanDependencies(
@@ -247,15 +248,11 @@ protected:
   void CheckMultipleOutputs(bool verbose);
 
 private:
-  std::string ConvertShellCommand(std::string const& cmd,
-                                  cmOutputConverter::RelativeRoot root);
-  std::string MakeLauncher(cmCustomCommandGenerator const& ccg,
-                           cmGeneratorTarget* target,
-                           cmOutputConverter::RelativeRoot relative);
+  std::string MaybeConvertWatcomShellCommand(std::string const& cmd);
 
-  virtual void ComputeObjectFilenames(
+  void ComputeObjectFilenames(
     std::map<cmSourceFile const*, std::string>& mapping,
-    cmGeneratorTarget const* gt = 0);
+    cmGeneratorTarget const* gt = CM_NULLPTR) CM_OVERRIDE;
 
   friend class cmMakefileTargetGenerator;
   friend class cmMakefileExecutableTargetGenerator;
@@ -272,7 +269,7 @@ private:
     cmGeneratorTarget* Target;
     std::string Language;
     LocalObjectEntry()
-      : Target(0)
+      : Target(CM_NULLPTR)
       , Language()
     {
     }
diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx
index 37b5505..6f9f009 100644
--- a/Source/cmLocalVisualStudio10Generator.cxx
+++ b/Source/cmLocalVisualStudio10Generator.cxx
@@ -1,20 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalVisualStudio10Generator.h"
 
+#include "cmGeneratorTarget.h"
 #include "cmGlobalVisualStudio10Generator.h"
 #include "cmMakefile.h"
 #include "cmVisualStudio10TargetGenerator.h"
 #include "cmXMLParser.h"
+
 #include <cm_expat.h>
 
 class cmVS10XMLParser : public cmXMLParser
diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h
index 6ec894c..4becfee 100644
--- a/Source/cmLocalVisualStudio10Generator.h
+++ b/Source/cmLocalVisualStudio10Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalVisualStudio10Generator_h
 #define cmLocalVisualStudio10Generator_h
 
diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx
index 6e7d7d2..a4b28b5 100644
--- a/Source/cmLocalVisualStudio7Generator.cxx
+++ b/Source/cmLocalVisualStudio7Generator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalVisualStudio7Generator.h"
 
 #include "cmCustomCommandGenerator.h"
@@ -269,8 +260,8 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule()
   args += this->GetBinaryDirectory();
   commandLine.push_back(args);
   commandLine.push_back("--check-stamp-file");
-  std::string stampFilename = this->Convert(
-    stampName.c_str(), cmOutputConverter::FULL, cmOutputConverter::SHELL);
+  std::string stampFilename = this->ConvertToOutputFormat(
+    cmSystemTools::CollapseFullPath(stampName), cmOutputConverter::SHELL);
   commandLine.push_back(stampFilename.c_str());
 
   std::vector<std::string> const& listFiles = this->Makefile->GetListFiles();
@@ -278,8 +269,8 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule()
   cmCustomCommandLines commandLines;
   commandLines.push_back(commandLine);
   const char* no_working_directory = 0;
-  std::string fullpathStampName = this->Convert(
-    stampName.c_str(), cmOutputConverter::FULL, cmOutputConverter::UNCHANGED);
+  std::string fullpathStampName =
+    cmSystemTools::CollapseFullPath(stampName.c_str());
   this->Makefile->AddCustomCommandToOutput(
     fullpathStampName.c_str(), listFiles, makefileIn.c_str(), commandLines,
     comment.c_str(), no_working_directory, true);
@@ -683,7 +674,8 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(
   }
 
   if (this->FortranProject) {
-    switch (this->GetFortranFormat(target->GetProperty("Fortran_FORMAT"))) {
+    switch (cmOutputConverter::GetFortranFormat(
+      target->GetProperty("Fortran_FORMAT"))) {
       case cmOutputConverter::FortranFormatFixed:
         flags += " -fixed";
         break;
@@ -787,8 +779,8 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(
       target->GetProperty("Fortran_MODULE_DIRECTORY");
     std::string modDir;
     if (target_mod_dir) {
-      modDir = this->Convert(target_mod_dir, cmOutputConverter::START_OUTPUT,
-                             cmOutputConverter::UNCHANGED);
+      modDir = this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
+                                           target_mod_dir);
     } else {
       modDir = ".";
     }
@@ -1012,7 +1004,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
     linkOptions.AddFlag("ModuleDefinitionFile", defFile.c_str());
   }
 
-  if (target->GetType() == cmState::SHARED_LIBRARY &&
+  if ((target->GetType() == cmState::SHARED_LIBRARY ||
+       target->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (target->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
       linkOptions.AddFlag("ModuleDefinitionFile", "$(IntDir)/exportall.def");
@@ -1296,11 +1289,11 @@ void cmLocalVisualStudio7GeneratorInternals::OutputLibraries(
   std::ostream& fout, ItemVector const& libs)
 {
   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
+  std::string currentBinDir = lg->GetCurrentBinaryDirectory();
   for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
     if (l->IsPath) {
       std::string rel =
-        lg->Convert(l->Value.c_str(), cmOutputConverter::START_OUTPUT,
-                    cmOutputConverter::UNCHANGED);
+        lg->ConvertToRelativePath(currentBinDir, l->Value.c_str());
       fout << lg->ConvertToXMLOutputPath(rel.c_str()) << " ";
     } else if (!l->Target ||
                l->Target->GetType() != cmState::INTERFACE_LIBRARY) {
@@ -1315,13 +1308,13 @@ void cmLocalVisualStudio7GeneratorInternals::OutputObjects(
   // VS < 8 does not support per-config source locations so we
   // list object library content on the link line instead.
   cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
+  std::string currentBinDir = lg->GetCurrentBinaryDirectory();
   std::vector<std::string> objs;
   gt->UseObjectLibraries(objs, "");
   const char* sep = isep ? isep : "";
   for (std::vector<std::string>::const_iterator oi = objs.begin();
        oi != objs.end(); ++oi) {
-    std::string rel = lg->Convert(oi->c_str(), cmOutputConverter::START_OUTPUT,
-                                  cmOutputConverter::UNCHANGED);
+    std::string rel = lg->ConvertToRelativePath(currentBinDir, oi->c_str());
     fout << sep << lg->ConvertToXMLOutputPath(rel.c_str());
     sep = " ";
   }
@@ -1331,6 +1324,7 @@ void cmLocalVisualStudio7Generator::OutputLibraryDirectories(
   std::ostream& fout, std::vector<std::string> const& dirs)
 {
   const char* comma = "";
+  std::string currentBinDir = this->GetCurrentBinaryDirectory();
   for (std::vector<std::string>::const_iterator d = dirs.begin();
        d != dirs.end(); ++d) {
     // Remove any trailing slash and skip empty paths.
@@ -1345,8 +1339,7 @@ void cmLocalVisualStudio7Generator::OutputLibraryDirectories(
     // Switch to a relative path specification if it is shorter.
     if (cmSystemTools::FileIsFullPath(dir.c_str())) {
       std::string rel =
-        this->Convert(dir.c_str(), cmOutputConverter::START_OUTPUT,
-                      cmOutputConverter::UNCHANGED);
+        this->ConvertToRelativePath(currentBinDir, dir.c_str());
       if (rel.size() < dir.size()) {
         dir = rel;
       }
@@ -1474,7 +1467,8 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo(
       needfc = true;
     }
     if (lg->FortranProject) {
-      switch (lg->GetFortranFormat(sf.GetProperty("Fortran_FORMAT"))) {
+      switch (cmOutputConverter::GetFortranFormat(
+        sf.GetProperty("Fortran_FORMAT"))) {
         case cmOutputConverter::FortranFormatFixed:
           fc.CompileFlags = "-fixed " + fc.CompileFlags;
           needfc = true;
@@ -1686,12 +1680,12 @@ bool cmLocalVisualStudio7Generator::WriteGroup(
                                                       ppLang);
           }
           if (!fc.AdditionalDeps.empty()) {
-            fout << "\t\t\t\t\tAdditionalDependencies=\""
-                 << fc.AdditionalDeps.c_str() << "\"\n";
+            fout << "\t\t\t\t\tAdditionalDependencies=\"" << fc.AdditionalDeps
+                 << "\"\n";
           }
           if (!fc.ObjectName.empty()) {
-            fout << "\t\t\t\t\tObjectFile=\"$(IntDir)/"
-                 << fc.ObjectName.c_str() << "\"\n";
+            fout << "\t\t\t\t\tObjectFile=\"$(IntDir)/" << fc.ObjectName
+                 << "\"\n";
           }
           fout << "\t\t\t\t\t/>\n"
                << "\t\t\t\t</FileConfiguration>\n";
@@ -1834,7 +1828,8 @@ void cmLocalVisualStudio7Generator::OutputTargetRules(
   tool = this->FortranProject ? "VFPreLinkEventTool" : "VCPreLinkEventTool";
   event.Start(tool);
   bool addedPrelink = false;
-  if (target->GetType() == cmState::SHARED_LIBRARY &&
+  if ((target->GetType() == cmState::SHARED_LIBRARY ||
+       target->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (target->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
       addedPrelink = true;
@@ -1848,7 +1843,7 @@ void cmLocalVisualStudio7Generator::OutputTargetRules(
   if (!addedPrelink) {
     event.Write(target->GetPreLinkCommands());
   }
-  cmsys::auto_ptr<cmCustomCommand> pcc(
+  CM_AUTO_PTR<cmCustomCommand> pcc(
     this->MaybeCreateImplibDir(target, configName, this->FortranProject));
   if (pcc.get()) {
     event.Write(*pcc);
diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h
index 6d1d0fb..6665bb0 100644
--- a/Source/cmLocalVisualStudio7Generator.h
+++ b/Source/cmLocalVisualStudio7Generator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalVisualStudio7Generator_h
 #define cmLocalVisualStudio7Generator_h
 
diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx
index 85ab615..e2b3cd2 100644
--- a/Source/cmLocalVisualStudioGenerator.cxx
+++ b/Source/cmLocalVisualStudioGenerator.cxx
@@ -1,17 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalVisualStudioGenerator.h"
 
 #include "cmCustomCommandGenerator.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
@@ -74,12 +66,12 @@ void cmLocalVisualStudioGenerator::ComputeObjectFilenames(
   }
 }
 
-cmsys::auto_ptr<cmCustomCommand>
+CM_AUTO_PTR<cmCustomCommand>
 cmLocalVisualStudioGenerator::MaybeCreateImplibDir(cmGeneratorTarget* target,
                                                    const std::string& config,
                                                    bool isFortran)
 {
-  cmsys::auto_ptr<cmCustomCommand> pcc;
+  CM_AUTO_PTR<cmCustomCommand> pcc;
 
   // If an executable exports symbols then VS wants to create an
   // import library but forgets to create the output directory.
@@ -127,7 +119,6 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
 {
   bool useLocal = this->CustomCommandUseLocal();
   std::string workingDirectory = ccg.GetWorkingDirectory();
-  RelativeRoot relativeRoot = workingDirectory.empty() ? START_OUTPUT : NONE;
 
   // Avoid leading or trailing newlines.
   std::string newline = "";
@@ -156,7 +147,8 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
     script += newline;
     newline = newline_text;
     script += "cd ";
-    script += this->Convert(workingDirectory, FULL, SHELL);
+    script += this->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(workingDirectory), SHELL);
     script += check_error;
 
     // Change the working drive.
@@ -203,7 +195,13 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
       }
     }
 
-    script += this->Convert(cmd.c_str(), relativeRoot, SHELL);
+    if (workingDirectory.empty()) {
+      script += this->ConvertToOutputFormat(
+        this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), cmd),
+        cmOutputConverter::SHELL);
+    } else {
+      script += this->ConvertToOutputFormat(cmd.c_str(), SHELL);
+    }
     ccg.AppendArguments(c, script);
 
     // After each custom command, check for an error result.
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index c24d813..169ecaf 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalVisualStudioGenerator_h
 #define cmLocalVisualStudioGenerator_h
 
@@ -16,7 +7,7 @@
 
 #include "cmGlobalVisualStudioGenerator.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
 
 class cmSourceFile;
 class cmSourceGroup;
@@ -59,8 +50,9 @@ protected:
   virtual bool CustomCommandUseLocal() const { return false; }
 
   /** Construct a custom command to make exe import lib dir.  */
-  cmsys::auto_ptr<cmCustomCommand> MaybeCreateImplibDir(
-    cmGeneratorTarget* target, const std::string& config, bool isFortran);
+  CM_AUTO_PTR<cmCustomCommand> MaybeCreateImplibDir(cmGeneratorTarget* target,
+                                                    const std::string& config,
+                                                    bool isFortran);
 };
 
 #endif
diff --git a/Source/cmLocalXCodeGenerator.cxx b/Source/cmLocalXCodeGenerator.cxx
index db87946..b596a8f 100644
--- a/Source/cmLocalXCodeGenerator.cxx
+++ b/Source/cmLocalXCodeGenerator.cxx
@@ -1,16 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalXCodeGenerator.h"
 
+#include "cmGeneratorTarget.h"
 #include "cmGlobalXCodeGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
diff --git a/Source/cmLocalXCodeGenerator.h b/Source/cmLocalXCodeGenerator.h
index da3558e..3756b61 100644
--- a/Source/cmLocalXCodeGenerator.h
+++ b/Source/cmLocalXCodeGenerator.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocalXCodeGenerator_h
 #define cmLocalXCodeGenerator_h
 
diff --git a/Source/cmLocale.h b/Source/cmLocale.h
index e69c32e..f35e528 100644
--- a/Source/cmLocale.h
+++ b/Source/cmLocale.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmLocale_h
 #define cmLocale_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include <locale.h>
@@ -22,7 +15,7 @@ class cmLocaleRAII
 
 public:
   cmLocaleRAII()
-    : OldLocale(setlocale(LC_CTYPE, 0))
+    : OldLocale(setlocale(LC_CTYPE, CM_NULLPTR))
   {
     setlocale(LC_CTYPE, "");
   }
diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx
index 314760e..95518f9 100644
--- a/Source/cmMachO.cxx
+++ b/Source/cmMachO.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmStandardIncludes.h" // to get CMAKE_USE_MACH_PARSER first
 
 #include "cmMachO.h"
diff --git a/Source/cmMachO.h b/Source/cmMachO.h
index 327c1ce..a754c1f 100644
--- a/Source/cmMachO.h
+++ b/Source/cmMachO.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMachO_h
 #define cmMachO_h
 
diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx
index 2caa401..9917394 100644
--- a/Source/cmMacroCommand.cxx
+++ b/Source/cmMacroCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMacroCommand.h"
 
 #include "cmAlgorithms.h"
@@ -21,7 +12,7 @@ public:
   cmMacroHelperCommand() {}
 
   ///! clean up any memory allocated by the macro
-  ~cmMacroHelperCommand() {}
+  ~cmMacroHelperCommand() CM_OVERRIDE {}
 
   /**
    * This is used to avoid including this command
@@ -29,12 +20,12 @@ public:
    * cmMacroHelperCommand and cmFunctionHelperCommand
    * which cannot provide appropriate documentation.
    */
-  virtual bool ShouldAppearInDocumentation() const { return false; }
+  bool ShouldAppearInDocumentation() const CM_OVERRIDE { return false; }
 
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone()
+  cmCommand* Clone() CM_OVERRIDE
   {
     cmMacroHelperCommand* newC = new cmMacroHelperCommand;
     // we must copy when we clone
@@ -48,16 +39,17 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -65,7 +57,7 @@ public:
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return this->Args[0]; }
+  std::string GetName() const CM_OVERRIDE { return this->Args[0]; }
 
   cmTypeMacro(cmMacroHelperCommand, cmCommand);
 
@@ -202,10 +194,9 @@ bool cmMacroFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
       // remove the function blocker now that the macro is defined
       mf.RemoveFunctionBlocker(this, lff);
       return true;
-    } else {
-      // decrement for each nested macro that ends
-      this->Depth--;
     }
+    // decrement for each nested macro that ends
+    this->Depth--;
   }
 
   // if it wasn't an endmacro and we are not executing then we must be
@@ -235,7 +226,7 @@ bool cmMacroFunctionBlocker::ShouldRemove(const cmListFileFunction& lff,
 bool cmMacroCommand::InitialPass(std::vector<std::string> const& args,
                                  cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h
index 11d2e1c..362d272 100644
--- a/Source/cmMacroCommand.h
+++ b/Source/cmMacroCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMacroCommand_h
 #define cmMacroCommand_h
 
@@ -20,10 +11,10 @@ class cmMacroFunctionBlocker : public cmFunctionBlocker
 {
 public:
   cmMacroFunctionBlocker() { this->Depth = 0; }
-  virtual ~cmMacroFunctionBlocker() {}
-  virtual bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
-                                 cmExecutionStatus&);
-  virtual bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf);
+  ~cmMacroFunctionBlocker() CM_OVERRIDE {}
+  bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
+                         cmExecutionStatus&) CM_OVERRIDE;
+  bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE;
 
   std::vector<std::string> Args;
   std::vector<cmListFileFunction> Functions;
@@ -37,24 +28,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmMacroCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmMacroCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "macro"; }
+  std::string GetName() const CM_OVERRIDE { return "macro"; }
 
   cmTypeMacro(cmMacroCommand, cmCommand);
 };
diff --git a/Source/cmMakeDirectoryCommand.cxx b/Source/cmMakeDirectoryCommand.cxx
index 574dbf0..e0011bd 100644
--- a/Source/cmMakeDirectoryCommand.cxx
+++ b/Source/cmMakeDirectoryCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakeDirectoryCommand.h"
 
 // cmMakeDirectoryCommand
diff --git a/Source/cmMakeDirectoryCommand.h b/Source/cmMakeDirectoryCommand.h
index 1a86398..2117fae 100644
--- a/Source/cmMakeDirectoryCommand.h
+++ b/Source/cmMakeDirectoryCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakeDirectoryCommand_h
 #define cmMakeDirectoryCommand_h
 
@@ -29,24 +20,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmMakeDirectoryCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmMakeDirectoryCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "make_directory"; }
+  std::string GetName() const CM_OVERRIDE { return "make_directory"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmMakeDirectoryCommand, cmCommand);
 };
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index e684689..df993ce 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -1,47 +1,47 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefile.h"
 
+#include "cmAlgorithms.h"
 #include "cmCommand.h"
 #include "cmCommandArgumentParserHelper.h"
-#include "cmCommands.h"
+#include "cmCustomCommand.h"
+#include "cmCustomCommandLines.h"
+#include "cmExecutionStatus.h"
+#include "cmExpandedCommandArgument.h"
+#include "cmFileLockPool.h"
 #include "cmFunctionBlocker.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorExpressionEvaluationFile.h"
 #include "cmGlobalGenerator.h"
 #include "cmListFileCache.h"
-#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
 #include "cmSourceFileLocation.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmTest.h"
 #include "cmVersion.h"
+#include "cmake.h"
+
+#include "cmInstallGenerator.h" // IWYU pragma: keep
+#include "cmTestGenerator.h"    // IWYU pragma: keep
+
 #ifdef CMAKE_BUILD_WITH_CMAKE
 #include "cmVariableWatch.h"
 #endif
-#include "cmAlgorithms.h"
-#include "cmInstallGenerator.h"
-#include "cmTestGenerator.h"
-#include "cmake.h"
-#include <stdlib.h> // required for atoi
 
+#include <algorithm>
+#include <assert.h>
+#include <cm_auto_ptr.hxx>
 #include <cmsys/FStream.hxx>
 #include <cmsys/RegularExpression.hxx>
-#include <cmsys/auto_ptr.hxx>
+#include <ctype.h>
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
 
-#include <assert.h>
-#include <ctype.h> // for isspace
-#include <list>
+class cmMessenger;
 
 // default is not to be building executables
 cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
@@ -105,16 +105,15 @@ cmMakefile::~cmMakefile()
   cmDeleteAll(this->EvaluationFiles);
 }
 
-void cmMakefile::IssueMessage(cmake::MessageType t, std::string const& text,
-                              bool force) const
+void cmMakefile::IssueMessage(cmake::MessageType t,
+                              std::string const& text) const
 {
-  // Collect context information.
   if (!this->ExecutionStatusStack.empty()) {
     if ((t == cmake::FATAL_ERROR) || (t == cmake::INTERNAL_ERROR)) {
       this->ExecutionStatusStack.back()->SetNestedError(true);
     }
   }
-  this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace(), force);
+  this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
 }
 
 cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
@@ -175,8 +174,29 @@ cmListFileContext cmMakefile::GetExecutionContext() const
 
 void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
 {
+  // Check if current file in the list of requested to trace...
+  std::vector<std::string> const& trace_only_this_files =
+    this->GetCMakeInstance()->GetTraceSources();
+  std::string const& full_path = this->GetExecutionFilePath();
+  std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
+  bool trace = trace_only_this_files.empty();
+  if (!trace) {
+    for (std::vector<std::string>::const_iterator i =
+           trace_only_this_files.begin();
+         !trace && i != trace_only_this_files.end(); ++i) {
+      std::string::size_type const pos = full_path.rfind(*i);
+      trace = (pos != std::string::npos) &&
+        ((pos + i->size()) == full_path.size()) &&
+        (only_filename == cmSystemTools::GetFilenameName(*i));
+    }
+    // Do nothing if current file wasn't requested for trace...
+    if (!trace) {
+      return;
+    }
+  }
+
   std::ostringstream msg;
-  msg << this->GetExecutionFilePath() << "(" << lff.Line << "):  ";
+  msg << full_path << "(" << lff.Line << "):  ";
   msg << lff.Name << "(";
   bool expand = this->GetCMakeInstance()->GetTraceExpand();
   std::string temp;
@@ -240,7 +260,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
   // Lookup the command prototype.
   if (cmCommand* proto = this->GetState()->GetCommand(name)) {
     // Clone the prototype.
-    cmsys::auto_ptr<cmCommand> pcmd(proto->Clone());
+    CM_AUTO_PTR<cmCommand> pcmd(proto->Clone());
     pcmd->SetMakefile(this);
 
     // Decide whether to invoke the command.
@@ -254,9 +274,10 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
         this->PrintCommandTrace(lff);
       }
       // Try invoking the command.
-      if (!pcmd->InvokeInitialPass(lff.Arguments, status) ||
-          status.GetNestedError()) {
-        if (!status.GetNestedError()) {
+      bool invokeSucceeded = pcmd->InvokeInitialPass(lff.Arguments, status);
+      bool hadNestedError = status.GetNestedError();
+      if (!invokeSucceeded || hadNestedError) {
+        if (!hadNestedError) {
           // The command invocation requested that we report an error.
           this->IssueMessage(cmake::FATAL_ERROR, pcmd->GetError());
         }
@@ -426,7 +447,8 @@ bool cmMakefile::ReadDependentFile(const char* filename, bool noPolicyScope)
   IncludeScope incScope(this, filenametoread, noPolicyScope);
 
   cmListFile listFile;
-  if (!listFile.ParseFile(filenametoread.c_str(), false, this)) {
+  if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
+                          this->Backtrace)) {
     return false;
   }
 
@@ -475,7 +497,8 @@ bool cmMakefile::ReadListFile(const char* filename)
   ListFileScope scope(this, filenametoread);
 
   cmListFile listFile;
-  if (!listFile.ParseFile(filenametoread.c_str(), false, this)) {
+  if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
+                          this->Backtrace)) {
     return false;
   }
 
@@ -546,7 +569,8 @@ void cmMakefile::EnforceDirectoryLevelRules() const
       case cmPolicies::WARN:
         // Warn because the user did not provide a mimimum required
         // version.
-        this->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
+        this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING,
+                                               msg.str(), this->Backtrace);
       case cmPolicies::OLD:
         // OLD behavior is to use policy version 2.4 set in
         // cmListFileCache.
@@ -555,7 +579,8 @@ void cmMakefile::EnforceDirectoryLevelRules() const
       case cmPolicies::REQUIRED_ALWAYS:
       case cmPolicies::NEW:
         // NEW behavior is to issue an error.
-        this->IssueMessage(cmake::FATAL_ERROR, msg.str());
+        this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, msg.str(),
+                                               this->Backtrace);
         cmSystemTools::SetFatalErrorOccured();
         return;
     }
@@ -564,9 +589,8 @@ void cmMakefile::EnforceDirectoryLevelRules() const
 
 void cmMakefile::AddEvaluationFile(
   const std::string& inputFile,
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> outputName,
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> condition,
-  bool inputIsContent)
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName,
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent)
 {
   this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile(
     inputFile, outputName, condition, inputIsContent));
@@ -651,12 +675,13 @@ void cmMakefile::ConfigureFinalPass()
   const char* oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
   if (oldValue &&
       cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, oldValue, "2.4")) {
-    this->IssueMessage(
+    this->GetCMakeInstance()->IssueMessage(
       cmake::FATAL_ERROR,
       "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
       "than 2.4. This version of CMake only supports backwards compatibility "
       "with CMake 2.4 or later. For compatibility with older versions please "
-      "use any CMake 2.8.x release or lower.");
+      "use any CMake 2.8.x release or lower.",
+      this->Backtrace);
   }
 }
 
@@ -665,7 +690,7 @@ void cmMakefile::AddCustomCommandToTarget(
   const std::vector<std::string>& depends,
   const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
   const char* comment, const char* workingDir, bool escapeOldStyle,
-  bool uses_terminal)
+  bool uses_terminal, const std::string& depfile)
 {
   // Find the target to which to add the custom command.
   cmTargets::iterator ti = this->Targets.find(target);
@@ -737,6 +762,7 @@ void cmMakefile::AddCustomCommandToTarget(
   cc.SetEscapeOldStyle(escapeOldStyle);
   cc.SetEscapeAllowMakeVars(true);
   cc.SetUsesTerminal(uses_terminal);
+  cc.SetDepfile(depfile);
   switch (type) {
     case cmTarget::PRE_BUILD:
       ti->second.AddPreBuildCommand(cc);
@@ -756,12 +782,12 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
   const std::vector<std::string>& depends, const std::string& main_dependency,
   const cmCustomCommandLines& commandLines, const char* comment,
   const char* workingDir, bool replace, bool escapeOldStyle,
-  bool uses_terminal)
+  bool uses_terminal, const std::string& depfile)
 {
   // Make sure there is at least one output.
   if (outputs.empty()) {
     cmSystemTools::Error("Attempt to add a custom rule with no output!");
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Validate custom commands.  TODO: More strict?
@@ -772,12 +798,12 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
       std::ostringstream e;
       e << "COMMAND may not contain literal quotes:\n  " << cl[0] << "\n";
       this->IssueMessage(cmake::FATAL_ERROR, e.str());
-      return 0;
+      return CM_NULLPTR;
     }
   }
 
   // Choose a source file on which to store the custom command.
-  cmSourceFile* file = 0;
+  cmSourceFile* file = CM_NULLPTR;
   if (!commandLines.empty() && !main_dependency.empty()) {
     // The main dependency was specified.  Use it unless a different
     // custom command already used it.
@@ -788,11 +814,10 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
         // The existing custom command is identical.  Silently ignore
         // the duplicate.
         return file;
-      } else {
-        // The existing custom command is different.  We need to
-        // generate a rule file for this new command.
-        file = 0;
       }
+      // The existing custom command is different.  We need to
+      // generate a rule file for this new command.
+      file = CM_NULLPTR;
     } else if (!file) {
       file = this->CreateSource(main_dependency);
     }
@@ -851,6 +876,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
     cc->SetEscapeOldStyle(escapeOldStyle);
     cc->SetEscapeAllowMakeVars(true);
     cc->SetUsesTerminal(uses_terminal);
+    cc->SetDepfile(depfile);
     file->SetCustomCommand(cc);
     this->UpdateOutputToSourceMap(outputs, file);
   }
@@ -888,14 +914,14 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
   const std::string& output, const std::vector<std::string>& depends,
   const std::string& main_dependency, const cmCustomCommandLines& commandLines,
   const char* comment, const char* workingDir, bool replace,
-  bool escapeOldStyle, bool uses_terminal)
+  bool escapeOldStyle, bool uses_terminal, const std::string& depfile)
 {
   std::vector<std::string> outputs;
   outputs.push_back(output);
   std::vector<std::string> no_byproducts;
   return this->AddCustomCommandToOutput(
     outputs, no_byproducts, depends, main_dependency, commandLines, comment,
-    workingDir, replace, escapeOldStyle, uses_terminal);
+    workingDir, replace, escapeOldStyle, uses_terminal, depfile);
 }
 
 void cmMakefile::AddCustomCommandOldStyle(
@@ -912,7 +938,7 @@ void cmMakefile::AddCustomCommandOldStyle(
     std::vector<std::string> no_byproducts;
     this->AddCustomCommandToTarget(target, no_byproducts, depends,
                                    commandLines, cmTarget::POST_BUILD, comment,
-                                   0);
+                                   CM_NULLPTR);
     return;
   }
 
@@ -930,22 +956,23 @@ void cmMakefile::AddCustomCommandOldStyle(
     if (sourceFiles.find(source)) {
       // The source looks like a real file.  Use it as the main dependency.
       sf = this->AddCustomCommandToOutput(output, depends, source,
-                                          commandLines, comment, 0);
+                                          commandLines, comment, CM_NULLPTR);
     } else {
       // The source may not be a real file.  Do not use a main dependency.
       std::string no_main_dependency = "";
       std::vector<std::string> depends2 = depends;
       depends2.push_back(source);
       sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
-                                          commandLines, comment, 0);
+                                          commandLines, comment, CM_NULLPTR);
     }
 
     // If the rule was added to the source (and not a .rule file),
     // then add the source to the target to make sure the rule is
     // included.
     if (sf && !sf->GetPropertyAsBool("__CMAKE_RULE")) {
-      if (this->Targets.find(target) != this->Targets.end()) {
-        this->Targets[target].AddSource(sf->GetFullPath());
+      cmTargets::iterator ti = this->Targets.find(target);
+      if (ti != this->Targets.end()) {
+        ti->second.AddSource(sf->GetFullPath());
       } else {
         cmSystemTools::Error("Attempt to add a custom rule to a target "
                              "that does not exist yet for target ",
@@ -1420,10 +1447,82 @@ void cmMakefile::Configure()
   this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart.c_str());
 
   cmListFile listFile;
-  if (!listFile.ParseFile(currentStart.c_str(), this->IsRootMakefile(),
-                          this)) {
+  if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
+                          this->Backtrace)) {
     return;
   }
+  if (this->IsRootMakefile()) {
+    bool hasVersion = false;
+    // search for the right policy command
+    for (std::vector<cmListFileFunction>::iterator i =
+           listFile.Functions.begin();
+         i != listFile.Functions.end(); ++i) {
+      if (cmSystemTools::LowerCase(i->Name) == "cmake_minimum_required") {
+        hasVersion = true;
+        break;
+      }
+    }
+    // if no policy command is found this is an error if they use any
+    // non advanced functions or a lot of functions
+    if (!hasVersion) {
+      bool isProblem = true;
+      if (listFile.Functions.size() < 30) {
+        // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
+        // these commands must have backwards compatibility forever and
+        // and that is a lot longer than your tiny mind can comprehend mortal
+        std::set<std::string> allowedCommands;
+        allowedCommands.insert("project");
+        allowedCommands.insert("set");
+        allowedCommands.insert("if");
+        allowedCommands.insert("endif");
+        allowedCommands.insert("else");
+        allowedCommands.insert("elseif");
+        allowedCommands.insert("add_executable");
+        allowedCommands.insert("add_library");
+        allowedCommands.insert("target_link_libraries");
+        allowedCommands.insert("option");
+        allowedCommands.insert("message");
+        isProblem = false;
+        for (std::vector<cmListFileFunction>::iterator i =
+               listFile.Functions.begin();
+             i != listFile.Functions.end(); ++i) {
+          std::string name = cmSystemTools::LowerCase(i->Name);
+          if (allowedCommands.find(name) == allowedCommands.end()) {
+            isProblem = true;
+            break;
+          }
+        }
+      }
+
+      if (isProblem) {
+        // Tell the top level cmMakefile to diagnose
+        // this violation of CMP0000.
+        this->SetCheckCMP0000(true);
+
+        // Implicitly set the version for the user.
+        this->SetPolicyVersion("2.4");
+      }
+    }
+    bool hasProject = false;
+    // search for a project command
+    for (std::vector<cmListFileFunction>::iterator i =
+           listFile.Functions.begin();
+         i != listFile.Functions.end(); ++i) {
+      if (cmSystemTools::LowerCase(i->Name) == "project") {
+        hasProject = true;
+        break;
+      }
+    }
+    // if no project command is found, add one
+    if (!hasProject) {
+      cmListFileFunction project;
+      project.Name = "PROJECT";
+      cmListFileArgument prj("Project", cmListFileArgument::Unquoted, 0);
+      project.Arguments.push_back(prj);
+      listFile.Functions.insert(listFile.Functions.begin(), project);
+    }
+  }
+
   this->ReadListFile(listFile, currentStart);
   if (cmSystemTools::GetFatalErrorOccured()) {
     scope.Quiet();
@@ -1720,8 +1819,8 @@ void cmMakefile::RemoveDefinition(const std::string& name)
 #ifdef CMAKE_BUILD_WITH_CMAKE
   cmVariableWatch* vv = this->GetVariableWatch();
   if (vv) {
-    vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS, 0,
-                         this);
+    vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
+                         CM_NULLPTR, this);
   }
 #endif
 }
@@ -1817,11 +1916,12 @@ cmTarget* cmMakefile::AddNewTarget(cmState::TargetType type,
                                    const std::string& name)
 {
   cmTargets::iterator it =
-    this->Targets.insert(cmTargets::value_type(name, cmTarget())).first;
-  cmTarget& target = it->second;
-  target.SetType(type, name);
-  target.SetMakefile(this);
+    this->Targets
+      .insert(cmTargets::value_type(
+        name, cmTarget(name, type, cmTarget::VisibilityNormal, this)))
+      .first;
   this->GetGlobalGenerator()->IndexTarget(&it->second);
+  this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
   return &it->second;
 }
 
@@ -1854,7 +1954,7 @@ cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput(
   }
 
   // otherwise return NULL
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmSourceFile* cmMakefile::GetSourceFileWithOutput(
@@ -1870,14 +1970,14 @@ cmSourceFile* cmMakefile::GetSourceFileWithOutput(
   if (o != this->OutputToSource.end()) {
     return (*o).second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 cmSourceGroup* cmMakefile::GetSourceGroup(
   const std::vector<std::string>& name) const
 {
-  cmSourceGroup* sg = 0;
+  cmSourceGroup* sg = CM_NULLPTR;
 
   // first look for source group starting with the same as the one we want
   for (std::vector<cmSourceGroup>::const_iterator sgIt =
@@ -1890,11 +1990,11 @@ cmSourceGroup* cmMakefile::GetSourceGroup(
     }
   }
 
-  if (sg != 0) {
+  if (sg != CM_NULLPTR) {
     // iterate through its children to find match source group
     for (unsigned int i = 1; i < name.size(); ++i) {
       sg = sg->LookupChild(name[i].c_str());
-      if (sg == 0) {
+      if (sg == CM_NULLPTR) {
         break;
       }
     }
@@ -1912,14 +2012,14 @@ void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
 void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
                                 const char* regex)
 {
-  cmSourceGroup* sg = 0;
+  cmSourceGroup* sg = CM_NULLPTR;
   std::vector<std::string> currentName;
   int i = 0;
   const int lastElement = static_cast<int>(name.size() - 1);
   for (i = lastElement; i >= 0; --i) {
     currentName.assign(name.begin(), name.begin() + i + 1);
     sg = this->GetSourceGroup(currentName);
-    if (sg != 0) {
+    if (sg != CM_NULLPTR) {
       break;
     }
   }
@@ -1933,7 +2033,8 @@ void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
       sg->SetGroupRegex(regex);
     }
     return;
-  } else if (i == -1) {
+  }
+  if (i == -1) {
     // group does not exist nor belong to any existing group
     // add its first component
     this->SourceGroups.push_back(cmSourceGroup(name[0].c_str(), regex));
@@ -1946,7 +2047,8 @@ void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
   }
   // build the whole source group path
   for (++i; i <= lastElement; ++i) {
-    sg->AddChild(cmSourceGroup(name[i].c_str(), 0, sg->GetFullName()));
+    sg->AddChild(
+      cmSourceGroup(name[i].c_str(), CM_NULLPTR, sg->GetFullName()));
     sg = sg->LookupChild(name[i].c_str());
   }
 
@@ -2048,7 +2150,8 @@ void cmMakefile::ExpandVariablesCMP0019()
       << "The following variable evaluations were encountered:\n"
       << w.str();
     /* clang-format on */
-    this->IssueMessage(cmake::AUTHOR_WARNING, m.str());
+    this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, m.str(),
+                                           this->Backtrace);
   }
 }
 
@@ -2076,6 +2179,14 @@ bool cmMakefile::IsSet(const std::string& name) const
   return true;
 }
 
+bool cmMakefile::PlatformIs32Bit() const
+{
+  if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
+    return atoi(sizeof_dptr) == 4;
+  }
+  return false;
+}
+
 bool cmMakefile::PlatformIs64Bit() const
 {
   if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
@@ -2124,20 +2235,11 @@ bool cmMakefile::CanIWriteThisFile(const char* fileName) const
   // If we are doing an in-source build, then the test will always fail
   if (cmSystemTools::SameFile(this->GetHomeDirectory(),
                               this->GetHomeOutputDirectory())) {
-    if (this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD")) {
-      return false;
-    }
-    return true;
+    return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
   }
 
-  // Check if this is a subdirectory of the source tree but not a
-  // subdirectory of the build tree
-  if (cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) &&
-      !cmSystemTools::IsSubDirectory(fileName,
-                                     this->GetHomeOutputDirectory())) {
-    return false;
-  }
-  return true;
+  return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
+    cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory());
 }
 
 const char* cmMakefile::GetRequiredDefinition(const std::string& name) const
@@ -2166,7 +2268,7 @@ bool cmMakefile::IsDefinitionSet(const std::string& name) const
     }
   }
 #endif
-  return def ? true : false;
+  return def != CM_NULLPTR;
 }
 
 const char* cmMakefile::GetDefinition(const std::string& name) const
@@ -2473,8 +2575,9 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringNew(
           openstack.pop_back();
           result.append(last, in - last);
           std::string const& lookup = result.substr(var.loc);
-          const char* value = NULL;
+          const char* value = CM_NULLPTR;
           std::string varresult;
+          std::string svalue;
           static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
           switch (var.domain) {
             case NORMAL:
@@ -2487,7 +2590,9 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringNew(
               }
               break;
             case ENVIRONMENT:
-              value = cmSystemTools::GetEnv(lookup.c_str());
+              if (cmSystemTools::GetEnv(lookup, svalue)) {
+                value = svalue.c_str();
+              }
               break;
             case CACHE:
               value = state->GetCacheEntryValue(lookup);
@@ -2526,7 +2631,7 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringNew(
         if (!atOnly) {
           t_lookup lookup;
           const char* next = in + 1;
-          const char* start = NULL;
+          const char* start = CM_NULLPTR;
           char nextc = *next;
           if (nextc == '{') {
             // Looking for a variable.
@@ -2717,13 +2822,12 @@ std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs,
       cmSystemTools::ExpandListArgument(configTypes, configs);
     }
     return "";
-  } else {
-    const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
-    if (singleConfig && !buildType.empty()) {
-      configs.push_back(buildType);
-    }
-    return buildType;
   }
+  const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
+  if (singleConfig && !buildType.empty()) {
+    configs.push_back(buildType);
+  }
+  return buildType;
 }
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -2792,7 +2896,7 @@ void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
   FunctionBlockersType::size_type barrier =
     this->FunctionBlockerBarriers.back();
   while (this->FunctionBlockers.size() > barrier) {
-    cmsys::auto_ptr<cmFunctionBlocker> fb(this->FunctionBlockers.back());
+    CM_AUTO_PTR<cmFunctionBlocker> fb(this->FunctionBlockers.back());
     this->FunctionBlockers.pop_back();
     if (reportError) {
       // Report the context in which the unclosed block was opened.
@@ -2929,7 +3033,7 @@ void cmMakefile::AddFunctionBlocker(cmFunctionBlocker* fb)
   this->FunctionBlockers.push_back(fb);
 }
 
-cmsys::auto_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
+CM_AUTO_PTR<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
   cmFunctionBlocker* fb, const cmListFileFunction& lff)
 {
   // Find the function blocker stack barrier for the current scope.
@@ -2962,11 +3066,11 @@ cmsys::auto_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
       }
       cmFunctionBlocker* b = *pos;
       this->FunctionBlockers.erase(pos);
-      return cmsys::auto_ptr<cmFunctionBlocker>(b);
+      return CM_AUTO_PTR<cmFunctionBlocker>(b);
     }
   }
 
-  return cmsys::auto_ptr<cmFunctionBlocker>();
+  return CM_AUTO_PTR<cmFunctionBlocker>();
 }
 
 const char* cmMakefile::GetHomeDirectory() const
@@ -3010,7 +3114,7 @@ cmSourceFile* cmMakefile::GetSource(const std::string& sourceName) const
       return sf;
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
@@ -3029,9 +3133,8 @@ cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
 {
   if (cmSourceFile* esf = this->GetSource(sourceName)) {
     return esf;
-  } else {
-    return this->CreateSource(sourceName, generated);
   }
+  return this->CreateSource(sourceName, generated);
 }
 
 void cmMakefile::EnableLanguage(std::vector<std::string> const& lang,
@@ -3039,7 +3142,26 @@ void cmMakefile::EnableLanguage(std::vector<std::string> const& lang,
 {
   this->AddDefinition("CMAKE_CFG_INTDIR",
                       this->GetGlobalGenerator()->GetCMakeCFGIntDir());
-  this->GetGlobalGenerator()->EnableLanguage(lang, this, optional);
+  // If RC is explicitly listed we need to do it after other languages.
+  // On some platforms we enable RC implicitly while enabling others.
+  // Do not let that look like recursive enable_language(RC).
+  std::vector<std::string> langs;
+  std::vector<std::string> langsRC;
+  langs.reserve(lang.size());
+  for (std::vector<std::string>::const_iterator i = lang.begin();
+       i != lang.end(); ++i) {
+    if (i->compare("RC") == 0) {
+      langsRC.push_back(*i);
+    } else {
+      langs.push_back(*i);
+    }
+  }
+  if (!langs.empty()) {
+    this->GetGlobalGenerator()->EnableLanguage(langs, this, optional);
+  }
+  if (!langsRC.empty()) {
+    this->GetGlobalGenerator()->EnableLanguage(langsRC, this, optional);
+  }
 }
 
 int cmMakefile::TryCompile(const std::string& srcdir,
@@ -3168,6 +3290,11 @@ cmake* cmMakefile::GetCMakeInstance() const
   return this->GlobalGenerator->GetCMakeInstance();
 }
 
+cmMessenger* cmMakefile::GetMessenger() const
+{
+  return this->GetCMakeInstance()->GetMessenger();
+}
+
 cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
 {
   return this->GlobalGenerator;
@@ -3180,7 +3307,7 @@ cmVariableWatch* cmMakefile::GetVariableWatch() const
       this->GetCMakeInstance()->GetVariableWatch()) {
     return this->GetCMakeInstance()->GetVariableWatch();
   }
-  return 0;
+  return CM_NULLPTR;
 }
 #endif
 
@@ -3341,8 +3468,8 @@ void cmMakefile::ConfigureString(const std::string& input, std::string& output,
   }
 
   // Perform variable replacements.
-  this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, 0, -1,
-                                true, true);
+  this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, CM_NULLPTR,
+                                -1, true, true);
 }
 
 int cmMakefile::ConfigureFile(const char* infile, const char* outfile,
@@ -3384,7 +3511,7 @@ int cmMakefile::ConfigureFile(const char* infile, const char* outfile,
     }
   } else {
     std::string newLineCharacters;
-    std::ios_base::openmode omode = std::ios_base::out | std::ios_base::trunc;
+    std::ios::openmode omode = std::ios::out | std::ios::trunc;
     if (newLine.IsValid()) {
       newLineCharacters = newLine.GetCharacters();
       omode |= std::ios::binary;
@@ -3425,7 +3552,7 @@ int cmMakefile::ConfigureFile(const char* infile, const char* outfile,
     while (cmSystemTools::GetLineFromStream(fin, inLine)) {
       outLine = "";
       this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
-      fout << outLine.c_str() << newLineCharacters;
+      fout << outLine << newLineCharacters;
     }
     // close the files before attempting to copy
     fin.close();
@@ -3481,7 +3608,7 @@ cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
   if (i != this->Targets.end()) {
     return &i->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmTest* cmMakefile::CreateTest(const std::string& testName)
@@ -3503,7 +3630,7 @@ cmTest* cmMakefile::GetTest(const std::string& testName) const
   if (mi != this->Tests.end()) {
     return mi->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmMakefile::AddCMakeDependFilesFromUser()
@@ -3594,10 +3721,10 @@ cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
                                         cmState::TargetType type, bool global)
 {
   // Create the target.
-  cmsys::auto_ptr<cmTarget> target(new cmTarget);
-  target->SetType(type, name);
-  target->MarkAsImported(global);
-  target->SetMakefile(this);
+  CM_AUTO_PTR<cmTarget> target(
+    new cmTarget(name, type, global ? cmTarget::VisibilityImportedGlobally
+                                    : cmTarget::VisibilityImported,
+                 this));
 
   // Add to the set of available imported targets.
   this->ImportedTargets[name] = target.get();
@@ -3629,8 +3756,9 @@ cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
 
 bool cmMakefile::IsAlias(const std::string& name) const
 {
-  if (this->AliasTargets.find(name) != this->AliasTargets.end())
+  if (this->AliasTargets.find(name) != this->AliasTargets.end()) {
     return true;
+  }
   return this->GetGlobalGenerator()->IsAlias(name);
 }
 
@@ -3655,69 +3783,67 @@ bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
         << "\" because an imported target with the same name already exists.";
       msg = e.str();
       return false;
-    } else {
-      // target names must be globally unique
-      switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
-        case cmPolicies::WARN:
-          this->IssueMessage(
-            cmake::AUTHOR_WARNING,
-            cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
-        case cmPolicies::OLD:
-          return true;
-        case cmPolicies::REQUIRED_IF_USED:
-        case cmPolicies::REQUIRED_ALWAYS:
-          this->IssueMessage(
-            cmake::FATAL_ERROR,
-            cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
-          return true;
-        case cmPolicies::NEW:
-          break;
-      }
-
-      // The conflict is with a non-imported target.
-      // Allow this if the user has requested support.
-      cmake* cm = this->GetCMakeInstance();
-      if (isCustom && existing->GetType() == cmState::UTILITY &&
-          this != existing->GetMakefile() &&
-          cm->GetState()->GetGlobalPropertyAsBool(
-            "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
+    }
+    // target names must be globally unique
+    switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
+      case cmPolicies::WARN:
+        this->IssueMessage(cmake::AUTHOR_WARNING,
+                           cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
+      case cmPolicies::OLD:
         return true;
-      }
+      case cmPolicies::REQUIRED_IF_USED:
+      case cmPolicies::REQUIRED_ALWAYS:
+        this->IssueMessage(
+          cmake::FATAL_ERROR,
+          cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
+        return true;
+      case cmPolicies::NEW:
+        break;
+    }
 
-      // Produce an error that tells the user how to work around the
-      // problem.
-      std::ostringstream e;
-      e << "cannot create target \"" << name
-        << "\" because another target with the same name already exists.  "
-        << "The existing target is ";
-      switch (existing->GetType()) {
-        case cmState::EXECUTABLE:
-          e << "an executable ";
-          break;
-        case cmState::STATIC_LIBRARY:
-          e << "a static library ";
-          break;
-        case cmState::SHARED_LIBRARY:
-          e << "a shared library ";
-          break;
-        case cmState::MODULE_LIBRARY:
-          e << "a module library ";
-          break;
-        case cmState::UTILITY:
-          e << "a custom target ";
-          break;
-        case cmState::INTERFACE_LIBRARY:
-          e << "an interface library ";
-          break;
-        default:
-          break;
-      }
-      e << "created in source directory \""
-        << existing->GetMakefile()->GetCurrentSourceDirectory() << "\".  "
-        << "See documentation for policy CMP0002 for more details.";
-      msg = e.str();
-      return false;
+    // The conflict is with a non-imported target.
+    // Allow this if the user has requested support.
+    cmake* cm = this->GetCMakeInstance();
+    if (isCustom && existing->GetType() == cmState::UTILITY &&
+        this != existing->GetMakefile() &&
+        cm->GetState()->GetGlobalPropertyAsBool(
+          "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
+      return true;
     }
+
+    // Produce an error that tells the user how to work around the
+    // problem.
+    std::ostringstream e;
+    e << "cannot create target \"" << name
+      << "\" because another target with the same name already exists.  "
+      << "The existing target is ";
+    switch (existing->GetType()) {
+      case cmState::EXECUTABLE:
+        e << "an executable ";
+        break;
+      case cmState::STATIC_LIBRARY:
+        e << "a static library ";
+        break;
+      case cmState::SHARED_LIBRARY:
+        e << "a shared library ";
+        break;
+      case cmState::MODULE_LIBRARY:
+        e << "a module library ";
+        break;
+      case cmState::UTILITY:
+        e << "a custom target ";
+        break;
+      case cmState::INTERFACE_LIBRARY:
+        e << "an interface library ";
+        break;
+      default:
+        break;
+    }
+    e << "created in source directory \""
+      << existing->GetMakefile()->GetCurrentSourceDirectory() << "\".  "
+      << "See documentation for policy CMP0002 for more details.";
+    msg = e.str();
+    return false;
   }
   return true;
 }
@@ -3963,10 +4089,10 @@ bool cmMakefile::IgnoreErrorsCMP0061() const
 }
 
 #define FEATURE_STRING(F) , #F
-static const char* const C_FEATURES[] = { 0 FOR_EACH_C_FEATURE(
+static const char* const C_FEATURES[] = { CM_NULLPTR FOR_EACH_C_FEATURE(
   FEATURE_STRING) };
 
-static const char* const CXX_FEATURES[] = { 0 FOR_EACH_CXX_FEATURE(
+static const char* const CXX_FEATURES[] = { CM_NULLPTR FOR_EACH_CXX_FEATURE(
   FEATURE_STRING) };
 #undef FEATURE_STRING
 
@@ -4002,14 +4128,20 @@ bool cmMakefile::AddRequiredTargetFeature(cmTarget* target,
       << this->GetDefinition("CMAKE_" + lang + "_COMPILER_ID")
       << "\"\nversion "
       << this->GetDefinition("CMAKE_" + lang + "_COMPILER_VERSION") << ".";
-    this->IssueMessage(cmake::FATAL_ERROR, e.str());
+    if (error) {
+      *error = e.str();
+    } else {
+      this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
+                                             this->Backtrace);
+    }
     return false;
   }
 
   target->AppendProperty("COMPILE_FEATURES", feature.c_str());
 
-  return lang == "C" ? this->AddRequiredTargetCFeature(target, feature)
-                     : this->AddRequiredTargetCxxFeature(target, feature);
+  return lang == "C"
+    ? this->AddRequiredTargetCFeature(target, feature, error)
+    : this->AddRequiredTargetCxxFeature(target, feature, error);
 }
 
 bool cmMakefile::CompileFeatureKnown(cmTarget const* target,
@@ -4045,7 +4177,8 @@ bool cmMakefile::CompileFeatureKnown(cmTarget const* target,
   if (error) {
     *error = e.str();
   } else {
-    this->IssueMessage(cmake::FATAL_ERROR, e.str());
+    this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
+                                           this->Backtrace);
   }
   return false;
 }
@@ -4070,9 +4203,10 @@ const char* cmMakefile::CompileFeaturesAvailable(const std::string& lang,
     if (error) {
       *error = e.str();
     } else {
-      this->IssueMessage(cmake::FATAL_ERROR, e.str());
+      this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
+                                             this->Backtrace);
     }
-    return 0;
+    return CM_NULLPTR;
   }
   return featuresKnown;
 }
@@ -4137,15 +4271,15 @@ bool cmMakefile::HaveCStandardAvailable(cmTarget const* target,
       existingCIt < std::find_if(cmArrayBegin(C_STANDARDS),
                                  cmArrayEnd(C_STANDARDS), cmStrCmp("11"))) {
     return false;
-  } else if (needC99 && existingCStandard &&
-             existingCIt < std::find_if(cmArrayBegin(C_STANDARDS),
-                                        cmArrayEnd(C_STANDARDS),
-                                        cmStrCmp("99"))) {
+  }
+  if (needC99 && existingCStandard &&
+      existingCIt < std::find_if(cmArrayBegin(C_STANDARDS),
+                                 cmArrayEnd(C_STANDARDS), cmStrCmp("99"))) {
     return false;
-  } else if (needC90 && existingCStandard &&
-             existingCIt < std::find_if(cmArrayBegin(C_STANDARDS),
-                                        cmArrayEnd(C_STANDARDS),
-                                        cmStrCmp("90"))) {
+  }
+  if (needC90 && existingCStandard &&
+      existingCIt < std::find_if(cmArrayBegin(C_STANDARDS),
+                                 cmArrayEnd(C_STANDARDS), cmStrCmp("90"))) {
     return false;
   }
   return true;
@@ -4223,10 +4357,11 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target,
                                    cmArrayEnd(CXX_STANDARDS),
                                    cmStrCmp("11"))) {
     return false;
-  } else if (needCxx98 &&
-             existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
-                                          cmArrayEnd(CXX_STANDARDS),
-                                          cmStrCmp("98"))) {
+  }
+  if (needCxx98 &&
+      existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
+                                   cmArrayEnd(CXX_STANDARDS),
+                                   cmStrCmp("98"))) {
     return false;
   }
   return true;
@@ -4257,7 +4392,8 @@ void cmMakefile::CheckNeededCxxLanguage(const std::string& feature,
 }
 
 bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
-                                             const std::string& feature) const
+                                             const std::string& feature,
+                                             std::string* error) const
 {
   bool needCxx98 = false;
   bool needCxx11 = false;
@@ -4273,7 +4409,12 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
       std::ostringstream e;
       e << "The CXX_STANDARD property on target \"" << target->GetName()
         << "\" contained an invalid value: \"" << existingCxxStandard << "\".";
-      this->IssueMessage(cmake::FATAL_ERROR, e.str());
+      if (error) {
+        *error = e.str();
+      } else {
+        this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
+                                               this->Backtrace);
+      }
       return false;
     }
   }
@@ -4338,7 +4479,8 @@ void cmMakefile::CheckNeededCLanguage(const std::string& feature,
 }
 
 bool cmMakefile::AddRequiredTargetCFeature(cmTarget* target,
-                                           const std::string& feature) const
+                                           const std::string& feature,
+                                           std::string* error) const
 {
   bool needC90 = false;
   bool needC99 = false;
@@ -4353,7 +4495,12 @@ bool cmMakefile::AddRequiredTargetCFeature(cmTarget* target,
       std::ostringstream e;
       e << "The C_STANDARD property on target \"" << target->GetName()
         << "\" contained an invalid value: \"" << existingCStandard << "\".";
-      this->IssueMessage(cmake::FATAL_ERROR, e.str());
+      if (error) {
+        *error = e.str();
+      } else {
+        this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
+                                               this->Backtrace);
+      }
       return false;
     }
   }
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index c665b1f..40344ce 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -1,57 +1,55 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakefile_h
 #define cmMakefile_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include "cmAlgorithms.h"
-#include "cmExecutionStatus.h"
-#include "cmExpandedCommandArgument.h"
 #include "cmListFileCache.h"
 #include "cmNewLineStyle.h"
+#include "cmPolicies.h"
 #include "cmState.h"
-#include "cmSystemTools.h"
 #include "cmTarget.h"
+#include "cmTargetLinkLibraryType.h"
 #include "cmake.h"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmSourceGroup.h"
 #endif
 
+#include <cm_auto_ptr.hxx>
 #include <cmsys/RegularExpression.hxx>
-#include <cmsys/auto_ptr.hxx>
+
+#include <map>
+#include <set>
+#include <stack>
+#include <string>
+#include <vector>
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 #include <unordered_map>
 #else
 #include <cmsys/hash_map.hxx>
 #endif
 #endif
 
-#include <stack>
-
-class cmFunctionBlocker;
 class cmCommand;
+class cmCompiledGeneratorExpression;
+class cmCustomCommandLines;
+class cmExecutionStatus;
+class cmExpandedCommandArgument;
+class cmExportBuildFileGenerator;
+class cmFunctionBlocker;
+class cmGeneratorExpressionEvaluationFile;
+class cmGlobalGenerator;
 class cmInstallGenerator;
+class cmMessenger;
 class cmSourceFile;
 class cmTest;
 class cmTestGenerator;
 class cmVariableWatch;
-class cmake;
-class cmMakefileCall;
-class cmCMakePolicyCommand;
-class cmGeneratorExpressionEvaluationFile;
-class cmExportBuildFileGenerator;
 
 /** \class cmMakefile
  * \brief Process the input CMakeLists.txt file.
@@ -97,7 +95,7 @@ public:
    * Remove the function blocker whose scope ends with the given command.
    * This returns ownership of the function blocker object.
    */
-  cmsys::auto_ptr<cmFunctionBlocker> RemoveFunctionBlocker(
+  CM_AUTO_PTR<cmFunctionBlocker> RemoveFunctionBlocker(
     cmFunctionBlocker* fb, const cmListFileFunction& lff);
 
   /**
@@ -129,14 +127,12 @@ public:
   void FinalPass();
 
   /** Add a custom command to the build.  */
-  void AddCustomCommandToTarget(const std::string& target,
-                                const std::vector<std::string>& byproducts,
-                                const std::vector<std::string>& depends,
-                                const cmCustomCommandLines& commandLines,
-                                cmTarget::CustomCommandType type,
-                                const char* comment, const char* workingDir,
-                                bool escapeOldStyle = true,
-                                bool uses_terminal = false);
+  void AddCustomCommandToTarget(
+    const std::string& target, const std::vector<std::string>& byproducts,
+    const std::vector<std::string>& depends,
+    const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
+    const char* comment, const char* workingDir, bool escapeOldStyle = true,
+    bool uses_terminal = false, const std::string& depfile = "");
   cmSourceFile* AddCustomCommandToOutput(
     const std::vector<std::string>& outputs,
     const std::vector<std::string>& byproducts,
@@ -144,13 +140,13 @@ public:
     const std::string& main_dependency,
     const cmCustomCommandLines& commandLines, const char* comment,
     const char* workingDir, bool replace = false, bool escapeOldStyle = true,
-    bool uses_terminal = false);
+    bool uses_terminal = false, const std::string& depfile = "");
   cmSourceFile* AddCustomCommandToOutput(
     const std::string& output, const std::vector<std::string>& depends,
     const std::string& main_dependency,
     const cmCustomCommandLines& commandLines, const char* comment,
     const char* workingDir, bool replace = false, bool escapeOldStyle = true,
-    bool uses_terminal = false);
+    bool uses_terminal = false, const std::string& depfile = "");
   void AddCustomCommandOldStyle(const std::string& target,
                                 const std::vector<std::string>& outputs,
                                 const std::vector<std::string>& depends,
@@ -182,24 +178,23 @@ public:
    * Add a utility to the build.  A utiltity target is a command that
    * is run every time the target is built.
    */
-  cmTarget* AddUtilityCommand(const std::string& utilityName,
-                              bool excludeFromAll,
-                              const std::vector<std::string>& depends,
-                              const char* workingDirectory,
-                              const char* command, const char* arg1 = 0,
-                              const char* arg2 = 0, const char* arg3 = 0,
-                              const char* arg4 = 0);
+  cmTarget* AddUtilityCommand(
+    const std::string& utilityName, bool excludeFromAll,
+    const std::vector<std::string>& depends, const char* workingDirectory,
+    const char* command, const char* arg1 = CM_NULLPTR,
+    const char* arg2 = CM_NULLPTR, const char* arg3 = CM_NULLPTR,
+    const char* arg4 = CM_NULLPTR);
   cmTarget* AddUtilityCommand(
     const std::string& utilityName, bool excludeFromAll,
     const char* workingDirectory, const std::vector<std::string>& depends,
     const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
-    const char* comment = 0, bool uses_terminal = false);
+    const char* comment = CM_NULLPTR, bool uses_terminal = false);
   cmTarget* AddUtilityCommand(
     const std::string& utilityName, bool excludeFromAll,
     const char* workingDirectory, const std::vector<std::string>& byproducts,
     const std::vector<std::string>& depends,
     const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
-    const char* comment = 0, bool uses_terminal = false);
+    const char* comment = CM_NULLPTR, bool uses_terminal = false);
 
   /**
    * Add a link library to the build.
@@ -274,14 +269,14 @@ public:
   /**
    * Add a root source group for consideration when adding a new source.
    */
-  void AddSourceGroup(const std::string& name, const char* regex = 0);
+  void AddSourceGroup(const std::string& name, const char* regex = CM_NULLPTR);
 
   /**
    * Add a source group for consideration when adding a new source.
    * name is tokenized.
    */
   void AddSourceGroup(const std::vector<std::string>& name,
-                      const char* regex = 0);
+                      const char* regex = CM_NULLPTR);
 
 #endif
 
@@ -437,6 +432,9 @@ public:
   bool IsOn(const std::string& name) const;
   bool IsSet(const std::string& name) const;
 
+  /** Return whether the target platform is 32-bit. */
+  bool PlatformIs32Bit() const;
+
   /** Return whether the target platform is 64-bit.  */
   bool PlatformIs64Bit() const;
 
@@ -516,8 +514,8 @@ public:
   const char* ExpandVariablesInString(std::string& source) const;
   const char* ExpandVariablesInString(std::string& source, bool escapeQuotes,
                                       bool noEscapes, bool atOnly = false,
-                                      const char* filename = 0, long line = -1,
-                                      bool removeEmpty = false,
+                                      const char* filename = CM_NULLPTR,
+                                      long line = -1, bool removeEmpty = false,
                                       bool replaceAt = false) const;
 
   /**
@@ -589,16 +587,17 @@ public:
    */
   bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
                        std::vector<std::string>& outArgs,
-                       const char* filename = 0) const;
+                       const char* filename = CM_NULLPTR) const;
 
   bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
                        std::vector<cmExpandedCommandArgument>& outArgs,
-                       const char* filename = 0) const;
+                       const char* filename = CM_NULLPTR) const;
 
   /**
    * Get the instance
    */
   cmake* GetCMakeInstance() const;
+  cmMessenger* GetMessenger() const;
   cmGlobalGenerator* GetGlobalGenerator() const;
 
   /**
@@ -643,8 +642,9 @@ public:
 
   void AddInstallGenerator(cmInstallGenerator* g)
   {
-    if (g)
+    if (g) {
       this->InstallGenerators.push_back(g);
+    }
   }
   std::vector<cmInstallGenerator*>& GetInstallGenerators()
   {
@@ -653,8 +653,9 @@ public:
 
   void AddTestGenerator(cmTestGenerator* g)
   {
-    if (g)
+    if (g) {
       this->TestGenerators.push_back(g);
+    }
   }
   const std::vector<cmTestGenerator*>& GetTestGenerators() const
   {
@@ -715,8 +716,7 @@ public:
     cmMakefile* Makefile;
   };
 
-  void IssueMessage(cmake::MessageType t, std::string const& text,
-                    bool force = false) const;
+  void IssueMessage(cmake::MessageType t, std::string const& text) const;
 
   /** Set whether or not to report a CMP0000 violation.  */
   void SetCheckCMP0000(bool b) { this->CheckCMP0000 = b; }
@@ -739,7 +739,7 @@ public:
   bool PolicyOptionalWarningEnabled(std::string const& var);
 
   bool AddRequiredTargetFeature(cmTarget* target, const std::string& feature,
-                                std::string* error = 0) const;
+                                std::string* error = CM_NULLPTR) const;
 
   bool CompileFeatureKnown(cmTarget const* target, const std::string& feature,
                            std::string& lang, std::string* error) const;
@@ -768,11 +768,10 @@ public:
 
   void EnforceDirectoryLevelRules() const;
 
-  void AddEvaluationFile(
-    const std::string& inputFile,
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> outputName,
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> condition,
-    bool inputIsContent);
+  void AddEvaluationFile(const std::string& inputFile,
+                         CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName,
+                         CM_AUTO_PTR<cmCompiledGeneratorExpression> condition,
+                         bool inputIsContent);
   std::vector<cmGeneratorExpressionEvaluationFile*> GetEvaluationFiles() const;
 
   std::vector<cmExportBuildFileGenerator*> GetExportBuildFileGenerators()
@@ -792,7 +791,7 @@ protected:
   // libraries, classes, and executables
   mutable cmTargets Targets;
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
   typedef std::unordered_map<std::string, cmTarget*> TargetMap;
 #else
   typedef cmsys::hash_map<std::string, cmTarget*> TargetMap;
@@ -885,10 +884,13 @@ private:
   void PopSnapshot(bool reportError = true);
   friend class cmCMakePolicyCommand;
   class IncludeScope;
+
   friend class IncludeScope;
   class ListFileScope;
+
   friend class ListFileScope;
   class BuildsystemFileScope;
+
   friend class BuildsystemFileScope;
 
   // CMP0053 == old
@@ -911,7 +913,7 @@ private:
 
 // A map for fast output to input look up.
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
   typedef std::unordered_map<std::string, cmSourceFile*> OutputToSourceMap;
 #else
   typedef cmsys::hash_map<std::string, cmSourceFile*> OutputToSourceMap;
@@ -928,11 +930,12 @@ private:
 
   std::vector<cmSourceFile*> QtUiFilesWithOptions;
 
-  bool AddRequiredTargetCFeature(cmTarget* target,
-                                 const std::string& feature) const;
+  bool AddRequiredTargetCFeature(cmTarget* target, const std::string& feature,
+                                 std::string* error = CM_NULLPTR) const;
 
   bool AddRequiredTargetCxxFeature(cmTarget* target,
-                                   const std::string& feature) const;
+                                   const std::string& feature,
+                                   std::string* error = CM_NULLPTR) const;
 
   void CheckNeededCLanguage(const std::string& feature, bool& needC90,
                             bool& needC99, bool& needC11) const;
diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx
index 9d42257..4a6990e 100644
--- a/Source/cmMakefileExecutableTargetGenerator.cxx
+++ b/Source/cmMakefileExecutableTargetGenerator.cxx
@@ -1,23 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileExecutableTargetGenerator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
+#include "cmOSXBundleGenerator.h"
+#include "cmOutputConverter.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
+#include <sstream>
+#include <string>
+#include <vector>
+
 cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator(
   cmGeneratorTarget* target)
   : cmMakefileTargetGenerator(target)
@@ -127,17 +126,23 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   std::string targetFullPathReal = outpath + targetNameReal;
   std::string targetFullPathPDB = pdbOutputPath + targetNamePDB;
   std::string targetFullPathImport = outpathImp + targetNameImport;
-  std::string targetOutPathPDB = this->Convert(
-    targetFullPathPDB, cmOutputConverter::NONE, cmOutputConverter::SHELL);
+  std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
+    targetFullPathPDB, cmOutputConverter::SHELL);
   // Convert to the output path to use in constructing commands.
-  std::string targetOutPath = this->Convert(
-    targetFullPath, cmOutputConverter::START_OUTPUT, cmOutputConverter::SHELL);
-  std::string targetOutPathReal =
-    this->Convert(targetFullPathReal, cmOutputConverter::START_OUTPUT,
-                  cmOutputConverter::SHELL);
+  std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath),
+    cmOutputConverter::SHELL);
+  std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
+    cmOutputConverter::SHELL);
   std::string targetOutPathImport =
-    this->Convert(targetFullPathImport, cmOutputConverter::START_OUTPUT,
-                  cmOutputConverter::SHELL);
+    this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(),
+        targetFullPathImport),
+      cmOutputConverter::SHELL);
 
   // Get the language to use for linking this executable.
   std::string linkLanguage =
@@ -187,6 +192,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     this->LocalGenerator->AppendFlags(
       linkFlags, this->Makefile->GetDefinition(export_flag_var));
   }
+  if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
+    this->LocalGenerator->AppendFlags(linkFlags, " -Wl,--no-as-needed");
+  }
 
   // Add language feature flags.
   this->AddFeatureFlags(flags, linkLanguage);
@@ -207,49 +215,45 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   // Construct a list of files associated with this executable that
   // may need to be cleaned.
   std::vector<std::string> exeCleanFiles;
-  exeCleanFiles.push_back(this->Convert(targetFullPath,
-                                        cmOutputConverter::START_OUTPUT,
-                                        cmOutputConverter::UNCHANGED));
+  exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
 #ifdef _WIN32
   // There may be a manifest file for this target.  Add it to the
   // clean set just in case.
-  exeCleanFiles.push_back(this->Convert((targetFullPath + ".manifest").c_str(),
-                                        cmOutputConverter::START_OUTPUT,
-                                        cmOutputConverter::UNCHANGED));
+  exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(),
+    (targetFullPath + ".manifest").c_str()));
 #endif
   if (targetNameReal != targetName) {
-    exeCleanFiles.push_back(this->Convert(targetFullPathReal,
-                                          cmOutputConverter::START_OUTPUT,
-                                          cmOutputConverter::UNCHANGED));
+    exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
   }
   if (!targetNameImport.empty()) {
-    exeCleanFiles.push_back(this->Convert(targetFullPathImport,
-                                          cmOutputConverter::START_OUTPUT,
-                                          cmOutputConverter::UNCHANGED));
+    exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(),
+      targetFullPathImport));
     std::string implib;
     if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport,
                                                 implib)) {
-      exeCleanFiles.push_back(this->Convert(implib,
-                                            cmOutputConverter::START_OUTPUT,
-                                            cmOutputConverter::UNCHANGED));
+      exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), implib));
     }
   }
 
   // List the PDB for cleaning only when the whole target is
   // cleaned.  We do not want to delete the .pdb file just before
   // linking the target.
-  this->CleanFiles.push_back(this->Convert(targetFullPathPDB,
-                                           cmOutputConverter::START_OUTPUT,
-                                           cmOutputConverter::UNCHANGED));
+  this->CleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathPDB));
 
   // Add the pre-build and pre-link rules building but not when relinking.
   if (!relink) {
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPreBuildCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPreLinkCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
   }
 
   // Determine whether a link script will be used.
@@ -274,27 +278,10 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     }
   }
 
-  // Select whether to use a response file for objects.
-  bool useResponseFileForObjects = false;
-  {
-    std::string responseVar = "CMAKE_";
-    responseVar += linkLanguage;
-    responseVar += "_USE_RESPONSE_FILE_FOR_OBJECTS";
-    if (this->Makefile->IsOn(responseVar)) {
-      useResponseFileForObjects = true;
-    }
-  }
-
-  // Select whether to use a response file for libraries.
-  bool useResponseFileForLibs = false;
-  {
-    std::string responseVar = "CMAKE_";
-    responseVar += linkLanguage;
-    responseVar += "_USE_RESPONSE_FILE_FOR_LIBRARIES";
-    if (this->Makefile->IsOn(responseVar)) {
-      useResponseFileForLibs = true;
-    }
-  }
+  bool useResponseFileForObjects =
+    this->CheckUseResponseFileForObjects(linkLanguage);
+  bool const useResponseFileForLibs =
+    this->CheckUseResponseFileForLibraries(linkLanguage);
 
   // Expand the rule variables.
   {
@@ -315,6 +302,12 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     this->CreateObjectLists(useLinkScript, false, useResponseFileForObjects,
                             buildObjs, depends, useWatcomQuote);
 
+    // maybe create .def file from list of objects
+    if (this->GeneratorTarget->IsExecutableWithExports() &&
+        this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
+      this->GenDefFile(real_link_commands, linkFlags);
+    }
+
     std::string manifests = this->GetManifests();
 
     cmLocalGenerator::RuleVariables vars;
@@ -323,14 +316,19 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     vars.Language = linkLanguage.c_str();
     vars.Objects = buildObjs.c_str();
     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
-    objectDir = this->Convert(objectDir, cmOutputConverter::START_OUTPUT,
-                              cmOutputConverter::SHELL);
+
+    objectDir = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+      cmOutputConverter::SHELL);
     vars.ObjectDir = objectDir.c_str();
     cmOutputConverter::OutputFormat output = (useWatcomQuote)
       ? cmOutputConverter::WATCOMQUOTE
       : cmOutputConverter::SHELL;
-    std::string target = this->Convert(
-      targetFullPathReal, cmOutputConverter::START_OUTPUT, output);
+    std::string target = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
+      output);
     vars.Target = target.c_str();
     vars.TargetPDB = targetOutPathPDB.c_str();
 
@@ -356,6 +354,14 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     vars.LinkFlags = linkFlags.c_str();
     vars.Manifests = manifests.c_str();
 
+    if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
+      std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat(
+        cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
+      cmakeCommand += " -E __run_iwyu --lwyu=";
+      cmakeCommand += targetOutPathReal;
+      real_link_commands.push_back(cmakeCommand);
+    }
+
     // Expand placeholders in the commands.
     this->LocalGenerator->TargetImplib = targetOutPathImport;
     for (std::vector<std::string>::iterator i = real_link_commands.begin();
@@ -380,7 +386,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   }
   this->LocalGenerator->CreateCDCommand(
     commands1, this->Makefile->GetCurrentBinaryDirectory(),
-    cmOutputConverter::HOME_OUTPUT);
+    this->LocalGenerator->GetBinaryDirectory());
   commands.insert(commands.end(), commands1.begin(), commands1.end());
   commands1.clear();
 
@@ -393,7 +399,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     commands1.push_back(symlink);
     this->LocalGenerator->CreateCDCommand(
       commands1, this->Makefile->GetCurrentBinaryDirectory(),
-      cmOutputConverter::HOME_OUTPUT);
+      this->LocalGenerator->GetBinaryDirectory());
     commands.insert(commands.end(), commands1.begin(), commands1.end());
     commands1.clear();
   }
@@ -402,12 +408,13 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   if (!relink) {
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPostBuildCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
   }
 
   // Write the build rule.
-  this->LocalGenerator->WriteMakeRule(
-    *this->BuildFileStream, 0, targetFullPathReal, depends, commands, false);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      targetFullPathReal, depends, commands,
+                                      false);
 
   // The symlink name for the target should depend on the real target
   // so if the target version changes it rebuilds and recreates the
@@ -416,8 +423,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     depends.clear();
     commands.clear();
     depends.push_back(targetFullPathReal);
-    this->LocalGenerator->WriteMakeRule(
-      *this->BuildFileStream, 0, targetFullPath, depends, commands, false);
+    this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                        targetFullPath, depends, commands,
+                                        false);
   }
 
   // Write the main driver rule to build everything in this target.
diff --git a/Source/cmMakefileExecutableTargetGenerator.h b/Source/cmMakefileExecutableTargetGenerator.h
index 64cb17f..36cfe40 100644
--- a/Source/cmMakefileExecutableTargetGenerator.h
+++ b/Source/cmMakefileExecutableTargetGenerator.h
@@ -1,28 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakefileExecutableTargetGenerator_h
 #define cmMakefileExecutableTargetGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmMakefileTargetGenerator.h"
 
+class cmGeneratorTarget;
+
 class cmMakefileExecutableTargetGenerator : public cmMakefileTargetGenerator
 {
 public:
   cmMakefileExecutableTargetGenerator(cmGeneratorTarget* target);
-  virtual ~cmMakefileExecutableTargetGenerator();
+  ~cmMakefileExecutableTargetGenerator() CM_OVERRIDE;
 
   /* the main entry point for this class. Writes the Makefiles associated
      with this target */
-  virtual void WriteRuleFiles();
+  void WriteRuleFiles() CM_OVERRIDE;
 
 protected:
   virtual void WriteExecutableRule(bool relink);
diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx
index 8f7dd7e..2b1d7cc 100644
--- a/Source/cmMakefileLibraryTargetGenerator.cxx
+++ b/Source/cmMakefileLibraryTargetGenerator.cxx
@@ -1,24 +1,22 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileLibraryTargetGenerator.h"
 
-#include "cmAlgorithms.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
+#include "cmOSXBundleGenerator.h"
+#include "cmOutputConverter.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
+#include <sstream>
+#include <vector>
+
 cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
   cmGeneratorTarget* target)
   : cmMakefileTargetGenerator(target)
@@ -105,13 +103,13 @@ void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
   // Add post-build rules.
   this->LocalGenerator->AppendCustomCommands(
     commands, this->GeneratorTarget->GetPostBuildCommands(),
-    this->GeneratorTarget);
+    this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
 
   // Depend on the object files.
   this->AppendObjectDepends(depends);
 
   // Write the rule.
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0,
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
                                       this->GeneratorTarget->GetName(),
                                       depends, commands, true);
 
@@ -163,6 +161,9 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
     extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName);
   this->AddModuleDefinitionFlag(extraFlags);
 
+  if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
+    this->LocalGenerator->AppendFlags(extraFlags, " -Wl,--no-as-needed");
+  }
   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
 }
 
@@ -300,19 +301,27 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
 
   // Construct the output path version of the names for use in command
   // arguments.
-  std::string targetOutPathPDB = this->Convert(
-    targetFullPathPDB, cmOutputConverter::NONE, cmOutputConverter::SHELL);
-  std::string targetOutPath = this->Convert(
-    targetFullPath, cmOutputConverter::START_OUTPUT, cmOutputConverter::SHELL);
-  std::string targetOutPathSO =
-    this->Convert(targetFullPathSO, cmOutputConverter::START_OUTPUT,
-                  cmOutputConverter::SHELL);
-  std::string targetOutPathReal =
-    this->Convert(targetFullPathReal, cmOutputConverter::START_OUTPUT,
-                  cmOutputConverter::SHELL);
+  std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
+    targetFullPathPDB, cmOutputConverter::SHELL);
+
+  std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath),
+    cmOutputConverter::SHELL);
+  std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO),
+    cmOutputConverter::SHELL);
+  std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
+    cmOutputConverter::SHELL);
   std::string targetOutPathImport =
-    this->Convert(targetFullPathImport, cmOutputConverter::START_OUTPUT,
-                  cmOutputConverter::SHELL);
+    this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(),
+        targetFullPathImport),
+      cmOutputConverter::SHELL);
 
   this->NumberOfProgressActions++;
   if (!this->NoRuleMessages) {
@@ -329,8 +338,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
         buildEcho += " shared library ";
         break;
       case cmState::MODULE_LIBRARY:
-        if (this->GeneratorTarget->IsCFBundleOnApple())
+        if (this->GeneratorTarget->IsCFBundleOnApple()) {
           buildEcho += " CFBundle";
+        }
         buildEcho += " shared module ";
         break;
       default:
@@ -342,7 +352,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
   }
 
-  const char* forbiddenFlagVar = 0;
+  const char* forbiddenFlagVar = CM_NULLPTR;
   switch (this->GeneratorTarget->GetType()) {
     case cmState::SHARED_LIBRARY:
       forbiddenFlagVar = "_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS";
@@ -356,46 +366,41 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
 
   // Clean files associated with this library.
   std::vector<std::string> libCleanFiles;
-  libCleanFiles.push_back(this->Convert(targetFullPath,
-                                        cmOutputConverter::START_OUTPUT,
-                                        cmOutputConverter::UNCHANGED));
+  libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
   if (targetNameReal != targetName) {
-    libCleanFiles.push_back(this->Convert(targetFullPathReal,
-                                          cmOutputConverter::START_OUTPUT,
-                                          cmOutputConverter::UNCHANGED));
+    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
   }
   if (targetNameSO != targetName && targetNameSO != targetNameReal) {
-    libCleanFiles.push_back(this->Convert(targetFullPathSO,
-                                          cmOutputConverter::START_OUTPUT,
-                                          cmOutputConverter::UNCHANGED));
+    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO));
   }
   if (!targetNameImport.empty()) {
-    libCleanFiles.push_back(this->Convert(targetFullPathImport,
-                                          cmOutputConverter::START_OUTPUT,
-                                          cmOutputConverter::UNCHANGED));
+    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(),
+      targetFullPathImport));
     std::string implib;
     if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport,
                                                 implib)) {
-      libCleanFiles.push_back(this->Convert(implib,
-                                            cmOutputConverter::START_OUTPUT,
-                                            cmOutputConverter::UNCHANGED));
+      libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), implib));
     }
   }
 
   // List the PDB for cleaning only when the whole target is
   // cleaned.  We do not want to delete the .pdb file just before
   // linking the target.
-  this->CleanFiles.push_back(this->Convert(targetFullPathPDB,
-                                           cmOutputConverter::START_OUTPUT,
-                                           cmOutputConverter::UNCHANGED));
+  this->CleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathPDB));
 
 #ifdef _WIN32
   // There may be a manifest file for this target.  Add it to the
   // clean set just in case.
   if (this->GeneratorTarget->GetType() != cmState::STATIC_LIBRARY) {
-    libCleanFiles.push_back(this->Convert(
-      (targetFullPath + ".manifest").c_str(), cmOutputConverter::START_OUTPUT,
-      cmOutputConverter::UNCHANGED));
+    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(),
+      (targetFullPath + ".manifest").c_str()));
   }
 #endif
 
@@ -407,7 +412,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
                                              this->GeneratorTarget, "target");
     this->LocalGenerator->CreateCDCommand(
       commands1, this->Makefile->GetCurrentBinaryDirectory(),
-      cmOutputConverter::HOME_OUTPUT);
+      this->LocalGenerator->GetBinaryDirectory());
     commands.insert(commands.end(), commands1.begin(), commands1.end());
     commands1.clear();
   }
@@ -416,36 +421,19 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   if (!relink) {
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPreBuildCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPreLinkCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
   }
 
   // Determine whether a link script will be used.
   bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
 
-  // Select whether to use a response file for objects.
-  bool useResponseFileForObjects = false;
-  {
-    std::string responseVar = "CMAKE_";
-    responseVar += linkLanguage;
-    responseVar += "_USE_RESPONSE_FILE_FOR_OBJECTS";
-    if (this->Makefile->IsOn(responseVar)) {
-      useResponseFileForObjects = true;
-    }
-  }
-
-  // Select whether to use a response file for libraries.
-  bool useResponseFileForLibs = false;
-  {
-    std::string responseVar = "CMAKE_";
-    responseVar += linkLanguage;
-    responseVar += "_USE_RESPONSE_FILE_FOR_LIBRARIES";
-    if (this->Makefile->IsOn(responseVar)) {
-      useResponseFileForLibs = true;
-    }
-  }
+  bool useResponseFileForObjects =
+    this->CheckUseResponseFileForObjects(linkLanguage);
+  bool const useResponseFileForLibs =
+    this->CheckUseResponseFileForLibraries(linkLanguage);
 
   // For static libraries there might be archiving rules.
   bool haveStaticLibraryRule = false;
@@ -454,8 +442,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   std::vector<std::string> archiveFinishCommands;
   std::string::size_type archiveCommandLimit = std::string::npos;
   if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY) {
-    haveStaticLibraryRule =
-      this->Makefile->GetDefinition(linkRuleVar) ? true : false;
+    haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
     std::string arCreateVar = "CMAKE_";
     arCreateVar += linkLanguage;
     arCreateVar += "_ARCHIVE_CREATE";
@@ -518,48 +505,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     // maybe create .def file from list of objects
     if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY &&
         this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
-      if (this->GeneratorTarget->GetPropertyAsBool(
-            "WINDOWS_EXPORT_ALL_SYMBOLS")) {
-        std::string name_of_def_file =
-          this->GeneratorTarget->GetSupportDirectory();
-        name_of_def_file +=
-          std::string("/") + this->GeneratorTarget->GetName();
-        name_of_def_file += ".def";
-        std::string cmd = cmSystemTools::GetCMakeCommand();
-        cmd = this->Convert(cmd, cmOutputConverter::NONE,
-                            cmOutputConverter::SHELL);
-        cmd += " -E __create_def ";
-        cmd += this->Convert(name_of_def_file, cmOutputConverter::START_OUTPUT,
-                             cmOutputConverter::SHELL);
-        cmd += " ";
-        std::string objlist_file = name_of_def_file;
-        objlist_file += ".objs";
-        cmd += this->Convert(objlist_file, cmOutputConverter::START_OUTPUT,
-                             cmOutputConverter::SHELL);
-        real_link_commands.push_back(cmd);
-        // create a list of obj files for the -E __create_def to read
-        cmGeneratedFileStream fout(objlist_file.c_str());
-        for (std::vector<std::string>::const_iterator i =
-               this->Objects.begin();
-             i != this->Objects.end(); ++i) {
-          if (cmHasLiteralSuffix(*i, ".obj")) {
-            fout << *i << "\n";
-          }
-        }
-        for (std::vector<std::string>::const_iterator i =
-               this->ExternalObjects.begin();
-             i != this->ExternalObjects.end(); ++i) {
-          fout << *i << "\n";
-        }
-        // now add the def file link flag
-        linkFlags += " ";
-        linkFlags +=
-          this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
-        linkFlags +=
-          this->Convert(name_of_def_file, cmOutputConverter::START_OUTPUT,
-                        cmOutputConverter::SHELL);
-        linkFlags += " ";
-      }
+      this->GenDefFile(real_link_commands, linkFlags);
     }
 
     std::string manifests = this->GetManifests();
@@ -589,14 +535,20 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     vars.Language = linkLanguage.c_str();
     vars.Objects = buildObjs.c_str();
     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
-    objectDir = this->Convert(objectDir, cmOutputConverter::START_OUTPUT,
-                              cmOutputConverter::SHELL);
+
+    objectDir = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+      cmOutputConverter::SHELL);
+
     vars.ObjectDir = objectDir.c_str();
     cmOutputConverter::OutputFormat output = (useWatcomQuote)
       ? cmOutputConverter::WATCOMQUOTE
       : cmOutputConverter::SHELL;
-    std::string target = this->Convert(
-      targetFullPathReal, cmOutputConverter::START_OUTPUT, output);
+    std::string target = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
+      output);
     vars.Target = target.c_str();
     vars.LinkLibraries = linkLibs.c_str();
     vars.ObjectsQuoted = buildObjs.c_str();
@@ -620,8 +572,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
         vars.TargetInstallNameDir = "";
       } else {
         // Convert to a path for the native build tool.
-        install_name_dir = this->LocalGenerator->Convert(
-          install_name_dir, cmOutputConverter::NONE, cmOutputConverter::SHELL);
+        install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
+          install_name_dir, cmOutputConverter::SHELL);
         vars.TargetInstallNameDir = install_name_dir.c_str();
       }
     }
@@ -677,12 +629,23 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
            i != archiveFinishCommands.end(); ++i) {
         std::string cmd = *i;
         this->LocalGenerator->ExpandRuleVariables(cmd, vars);
-        real_link_commands.push_back(cmd);
+        // If there is no ranlib the command will be ":".  Skip it.
+        if (!cmd.empty() && cmd[0] != ':') {
+          real_link_commands.push_back(cmd);
+        }
       }
     } else {
       // Get the set of commands.
       std::string linkRule = this->GetLinkRule(linkRuleVar);
       cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
+      if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
+          (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY)) {
+        std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat(
+          cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
+        cmakeCommand += " -E __run_iwyu --lwyu=";
+        cmakeCommand += targetOutPathReal;
+        real_link_commands.push_back(cmakeCommand);
+      }
 
       // Expand placeholders.
       for (std::vector<std::string>::iterator i = real_link_commands.begin();
@@ -708,7 +671,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   }
   this->LocalGenerator->CreateCDCommand(
     commands1, this->Makefile->GetCurrentBinaryDirectory(),
-    cmOutputConverter::HOME_OUTPUT);
+    this->LocalGenerator->GetBinaryDirectory());
   commands.insert(commands.end(), commands1.begin(), commands1.end());
   commands1.clear();
 
@@ -725,15 +688,16 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     commands1.push_back(symlink);
     this->LocalGenerator->CreateCDCommand(
       commands1, this->Makefile->GetCurrentBinaryDirectory(),
-      cmOutputConverter::HOME_OUTPUT);
+      this->LocalGenerator->GetBinaryDirectory());
     commands.insert(commands.end(), commands1.begin(), commands1.end());
     commands1.clear();
   }
+
   // Add the post-build rules when building but not when relinking.
   if (!relink) {
     this->LocalGenerator->AppendCustomCommands(
       commands, this->GeneratorTarget->GetPostBuildCommands(),
-      this->GeneratorTarget);
+      this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
   }
 
   // Compute the list of outputs.
@@ -746,8 +710,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   }
 
   // Write the build rule.
-  this->WriteMakeRule(*this->BuildFileStream, 0, outputs, depends, commands,
-                      false);
+  this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+                      commands, false);
 
   // Write the main driver rule to build everything in this target.
   this->WriteTargetDriverRule(targetFullPath, relink);
diff --git a/Source/cmMakefileLibraryTargetGenerator.h b/Source/cmMakefileLibraryTargetGenerator.h
index f72dbd7..dda41b8 100644
--- a/Source/cmMakefileLibraryTargetGenerator.h
+++ b/Source/cmMakefileLibraryTargetGenerator.h
@@ -1,28 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakefileLibraryTargetGenerator_h
 #define cmMakefileLibraryTargetGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmMakefileTargetGenerator.h"
 
+#include <string>
+
+class cmGeneratorTarget;
+
 class cmMakefileLibraryTargetGenerator : public cmMakefileTargetGenerator
 {
 public:
   cmMakefileLibraryTargetGenerator(cmGeneratorTarget* target);
-  virtual ~cmMakefileLibraryTargetGenerator();
+  ~cmMakefileLibraryTargetGenerator() CM_OVERRIDE;
 
   /* the main entry point for this class. Writes the Makefiles associated
      with this target */
-  virtual void WriteRuleFiles();
+  void WriteRuleFiles() CM_OVERRIDE;
 
 protected:
   void WriteObjectLibraryRules();
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index 93f9e49..e70f09e 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -1,44 +1,46 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileTargetGenerator.h"
 
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
+#include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
-#include "cmState.h"
-#include "cmake.h"
-
 #include "cmMakefileExecutableTargetGenerator.h"
 #include "cmMakefileLibraryTargetGenerator.h"
 #include "cmMakefileUtilityTargetGenerator.h"
+#include "cmOutputConverter.h"
+#include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
+#include <algorithm>
 #include <ctype.h>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
+#ifndef _WIN32
+#include <unistd.h>
+#endif
 
 cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
-  : cmCommonTargetGenerator(cmOutputConverter::START_OUTPUT, target)
-  , OSXBundleGenerator(0)
-  , MacOSXContentGenerator(0)
+  : cmCommonTargetGenerator(target)
+  , OSXBundleGenerator(CM_NULLPTR)
+  , MacOSXContentGenerator(CM_NULLPTR)
 {
-  this->BuildFileStream = 0;
-  this->InfoFileStream = 0;
-  this->FlagFileStream = 0;
+  this->BuildFileStream = CM_NULLPTR;
+  this->InfoFileStream = CM_NULLPTR;
+  this->FlagFileStream = CM_NULLPTR;
   this->CustomCommandDriver = OnBuild;
   this->LocalGenerator =
     static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
@@ -61,7 +63,7 @@ cmMakefileTargetGenerator::~cmMakefileTargetGenerator()
 cmMakefileTargetGenerator* cmMakefileTargetGenerator::New(
   cmGeneratorTarget* tgt)
 {
-  cmMakefileTargetGenerator* result = 0;
+  cmMakefileTargetGenerator* result = CM_NULLPTR;
 
   switch (tgt->GetType()) {
     case cmState::EXECUTABLE:
@@ -134,12 +136,12 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
   if (const char* additional_clean_files =
         this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
       ge.Parse(additional_clean_files);
 
     cmSystemTools::ExpandListArgument(
       cge->Evaluate(this->LocalGenerator, config, false, this->GeneratorTarget,
-                    0, 0),
+                    CM_NULLPTR, CM_NULLPTR),
       this->CleanFiles);
   }
 
@@ -151,6 +153,8 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
   // files for this target.
   std::vector<cmSourceFile const*> customCommands;
   this->GeneratorTarget->GetCustomCommands(customCommands, config);
+  std::string currentBinDir =
+    this->LocalGenerator->GetCurrentBinaryDirectory();
   for (std::vector<cmSourceFile const*>::const_iterator si =
          customCommands.begin();
        si != customCommands.end(); ++si) {
@@ -161,8 +165,8 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
       const std::vector<std::string>& outputs = ccg.GetOutputs();
       for (std::vector<std::string>::const_iterator o = outputs.begin();
            o != outputs.end(); ++o) {
-        this->CleanFiles.push_back(this->Convert(
-          *o, cmOutputConverter::START_OUTPUT, cmOutputConverter::UNCHANGED));
+        this->CleanFiles.push_back(
+          this->LocalGenerator->ConvertToRelativePath(currentBinDir, *o));
       }
     }
   }
@@ -203,8 +207,11 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
   *this->BuildFileStream
     << "# Include any dependencies generated for this target.\n"
     << this->GlobalGenerator->IncludeDirective << " " << root
-    << this->Convert(dependFileNameFull, cmOutputConverter::HOME_OUTPUT,
-                     cmOutputConverter::MAKERULE)
+    << cmSystemTools::ConvertToOutputPath(
+         this->LocalGenerator
+           ->ConvertToRelativePath(this->LocalGenerator->GetBinaryDirectory(),
+                                   dependFileNameFull)
+           .c_str())
     << "\n\n";
 
   if (!this->NoRuleMessages) {
@@ -212,9 +219,12 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
     *this->BuildFileStream
       << "# Include the progress variables for this target.\n"
       << this->GlobalGenerator->IncludeDirective << " " << root
-      << this->Convert(this->ProgressFileNameFull,
-                       cmOutputConverter::HOME_OUTPUT,
-                       cmOutputConverter::MAKERULE)
+      << cmSystemTools::ConvertToOutputPath(
+           this->LocalGenerator
+             ->ConvertToRelativePath(
+               this->LocalGenerator->GetBinaryDirectory(),
+               this->ProgressFileNameFull)
+             .c_str())
       << "\n\n";
   }
 
@@ -244,8 +254,11 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
   *this->BuildFileStream
     << "# Include the compile flags for this target's objects.\n"
     << this->GlobalGenerator->IncludeDirective << " " << root
-    << this->Convert(this->FlagFileNameFull, cmOutputConverter::HOME_OUTPUT,
-                     cmOutputConverter::MAKERULE)
+    << cmSystemTools::ConvertToOutputPath(
+         this->LocalGenerator
+           ->ConvertToRelativePath(this->LocalGenerator->GetBinaryDirectory(),
+                                   this->FlagFileNameFull)
+           .c_str())
     << "\n\n";
 }
 
@@ -301,8 +314,10 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
   output += "/";
   output += cmSystemTools::GetFilenameName(input);
   this->Generator->CleanFiles.push_back(
-    this->Generator->Convert(output, cmOutputConverter::START_OUTPUT));
-  output = this->Generator->Convert(output, cmOutputConverter::HOME_OUTPUT);
+    this->Generator->LocalGenerator->ConvertToRelativePath(
+      this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output));
+  output = this->Generator->LocalGenerator->ConvertToRelativePath(
+    this->Generator->LocalGenerator->GetBinaryDirectory(), output);
 
   // Create a rule to copy the content into the bundle.
   std::vector<std::string> depends;
@@ -313,14 +328,15 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
   this->Generator->LocalGenerator->AppendEcho(
     commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
   std::string copyCommand = "$(CMAKE_COMMAND) -E copy ";
-  copyCommand += this->Generator->Convert(input, cmOutputConverter::NONE,
-                                          cmOutputConverter::SHELL);
+  copyCommand += this->Generator->LocalGenerator->ConvertToOutputFormat(
+    input, cmOutputConverter::SHELL);
   copyCommand += " ";
-  copyCommand += this->Generator->Convert(output, cmOutputConverter::NONE,
-                                          cmOutputConverter::SHELL);
+  copyCommand += this->Generator->LocalGenerator->ConvertToOutputFormat(
+    output, cmOutputConverter::SHELL);
   commands.push_back(copyCommand);
   this->Generator->LocalGenerator->WriteMakeRule(
-    *this->Generator->BuildFileStream, 0, output, depends, commands, false);
+    *this->Generator->BuildFileStream, CM_NULLPTR, output, depends, commands,
+    false);
   this->Generator->ExtraFiles.insert(output);
 }
 
@@ -381,9 +397,9 @@ void cmMakefileTargetGenerator::WriteObjectRuleFiles(
   std::string objFullPath = this->LocalGenerator->GetCurrentBinaryDirectory();
   objFullPath += "/";
   objFullPath += obj;
-  objFullPath = this->Convert(objFullPath, cmOutputConverter::FULL);
+  objFullPath = cmSystemTools::CollapseFullPath(objFullPath);
   std::string srcFullPath =
-    this->Convert(source.GetFullPath(), cmOutputConverter::FULL);
+    cmSystemTools::CollapseFullPath(source.GetFullPath());
   this->LocalGenerator->AddImplicitDepends(
     this->GeneratorTarget, lang, objFullPath.c_str(), srcFullPath.c_str());
 }
@@ -452,8 +468,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   }
 
   // Get the output paths for source and object files.
-  std::string sourceFile = this->Convert(
-    source.GetFullPath(), cmOutputConverter::NONE, cmOutputConverter::SHELL);
+  std::string sourceFile = this->LocalGenerator->ConvertToOutputFormat(
+    source.GetFullPath(), cmOutputConverter::SHELL);
 
   // Construct the build message.
   std::vector<std::string> no_commands;
@@ -501,14 +517,17 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
       }
     }
 
-    targetOutPathReal =
-      this->Convert(targetFullPathReal, cmOutputConverter::START_OUTPUT,
-                    cmOutputConverter::SHELL);
-    targetOutPathPDB = this->Convert(
-      targetFullPathPDB, cmOutputConverter::NONE, cmOutputConverter::SHELL);
-    targetOutPathCompilePDB =
-      this->Convert(targetFullPathCompilePDB, cmOutputConverter::START_OUTPUT,
-                    cmOutputConverter::SHELL);
+    targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
+      cmOutputConverter::SHELL);
+    targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
+      targetFullPathPDB, cmOutputConverter::SHELL);
+    targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(),
+        targetFullPathCompilePDB),
+      cmOutputConverter::SHELL);
 
     if (this->LocalGenerator->IsMinGWMake() &&
         cmHasLiteralSuffix(targetOutPathCompilePDB, "\\")) {
@@ -527,15 +546,19 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
   vars.Source = sourceFile.c_str();
   std::string shellObj =
-    this->Convert(obj, cmOutputConverter::NONE, cmOutputConverter::SHELL);
+    this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
   vars.Object = shellObj.c_str();
   std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
-  objectDir = this->Convert(objectDir, cmOutputConverter::START_OUTPUT,
-                            cmOutputConverter::SHELL);
+  objectDir = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+    cmOutputConverter::SHELL);
   vars.ObjectDir = objectDir.c_str();
   std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
-  objectFileDir = this->Convert(objectFileDir, cmOutputConverter::START_OUTPUT,
-                                cmOutputConverter::SHELL);
+  objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), objectFileDir),
+    cmOutputConverter::SHELL);
   vars.ObjectFileDir = objectFileDir.c_str();
   vars.Flags = flags.c_str();
 
@@ -572,9 +595,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         lang_can_export_cmds && compileCommands.size() == 1) {
       std::string compileCommand = compileCommands[0];
       this->LocalGenerator->ExpandRuleVariables(compileCommand, vars);
-      std::string workingDirectory = this->LocalGenerator->Convert(
-        this->LocalGenerator->GetCurrentBinaryDirectory(),
-        cmOutputConverter::FULL);
+      std::string workingDirectory = cmSystemTools::CollapseFullPath(
+        this->LocalGenerator->GetCurrentBinaryDirectory());
       compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
                              this->GetFlags(lang));
       std::string langDefines = std::string("$(") + lang + "_DEFINES)";
@@ -637,7 +659,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
     // Change the command working directory to the local build tree.
     this->LocalGenerator->CreateCDCommand(
       compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
-      cmOutputConverter::HOME_OUTPUT);
+      this->LocalGenerator->GetBinaryDirectory());
     commands.insert(commands.end(), compileCommands.begin(),
                     compileCommands.end());
   }
@@ -652,7 +674,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   }
 
   // Write the rule.
-  this->WriteMakeRule(*this->BuildFileStream, 0, outputs, depends, commands);
+  this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+                      commands);
 
   bool do_preprocess_rules = lang_has_preprocessor &&
     this->LocalGenerator->GetCreatePreprocessedSourceRules();
@@ -686,8 +709,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         std::vector<std::string> preprocessCommands;
         cmSystemTools::ExpandListArgument(preprocessRule, preprocessCommands);
 
-        std::string shellObjI = this->Convert(objI, cmOutputConverter::NONE,
-                                              cmOutputConverter::SHELL);
+        std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
+          objI, cmOutputConverter::SHELL);
         vars.PreprocessedSource = shellObjI.c_str();
 
         // Expand placeholders in the commands.
@@ -699,7 +722,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         this->LocalGenerator->CreateCDCommand(
           preprocessCommands,
           this->LocalGenerator->GetCurrentBinaryDirectory(),
-          cmOutputConverter::HOME_OUTPUT);
+          this->LocalGenerator->GetBinaryDirectory());
         commands.insert(commands.end(), preprocessCommands.begin(),
                         preprocessCommands.end());
       } else {
@@ -708,7 +731,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         commands.push_back(cmd);
       }
 
-      this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0,
+      this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
                                           relativeObjI, force_depends,
                                           commands, false);
     }
@@ -733,8 +756,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         std::vector<std::string> assemblyCommands;
         cmSystemTools::ExpandListArgument(assemblyRule, assemblyCommands);
 
-        std::string shellObjS = this->Convert(objS, cmOutputConverter::NONE,
-                                              cmOutputConverter::SHELL);
+        std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
+          objS, cmOutputConverter::SHELL);
         vars.AssemblySource = shellObjS.c_str();
 
         // Expand placeholders in the commands.
@@ -745,7 +768,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
 
         this->LocalGenerator->CreateCDCommand(
           assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
-          cmOutputConverter::HOME_OUTPUT);
+          this->LocalGenerator->GetBinaryDirectory());
         commands.insert(commands.end(), assemblyCommands.begin(),
                         assemblyCommands.end());
       } else {
@@ -754,7 +777,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         commands.push_back(cmd);
       }
 
-      this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0,
+      this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
                                           relativeObjS, force_depends,
                                           commands, false);
     }
@@ -766,8 +789,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   objectRequires += ".requires";
   std::vector<std::string> p_depends;
   // always provide an empty requires target
-  this->LocalGenerator->WriteMakeRule(
-    *this->BuildFileStream, 0, objectRequires, p_depends, no_commands, true);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      objectRequires, p_depends, no_commands,
+                                      true);
 
   // write a build rule to recursively build what this obj provides
   std::string objectProvides = relativeObj;
@@ -783,13 +807,14 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
 
   p_depends.clear();
   p_depends.push_back(objectRequires);
-  this->LocalGenerator->WriteMakeRule(
-    *this->BuildFileStream, 0, objectProvides, p_depends, r_commands, true);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      objectProvides, p_depends, r_commands,
+                                      true);
 
   // write the provides.build rule dependency on the obj file
   p_depends.clear();
   p_depends.push_back(relativeObj);
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0, temp,
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, temp,
                                       p_depends, no_commands, false);
 }
 
@@ -815,8 +840,8 @@ void cmMakefileTargetGenerator::WriteTargetRequiresRules()
   }
 
   // Write the rule.
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0, depTarget,
-                                      depends, no_commands, true);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      depTarget, depends, no_commands, true);
 }
 
 void cmMakefileTargetGenerator::WriteTargetCleanRules()
@@ -834,11 +859,11 @@ void cmMakefileTargetGenerator::WriteTargetCleanRules()
                                            this->GeneratorTarget);
   this->LocalGenerator->CreateCDCommand(
     commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
-    cmOutputConverter::HOME_OUTPUT);
+    this->LocalGenerator->GetBinaryDirectory());
 
   // Write the rule.
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0, cleanTarget,
-                                      depends, commands, true);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      cleanTarget, depends, commands, true);
 }
 
 bool cmMakefileTargetGenerator::WriteMakeRule(
@@ -848,7 +873,7 @@ bool cmMakefileTargetGenerator::WriteMakeRule(
   const std::vector<std::string>& commands, bool in_help)
 {
   bool symbolic = false;
-  if (outputs.size() == 0) {
+  if (outputs.empty()) {
     return symbolic;
   }
 
@@ -873,12 +898,14 @@ bool cmMakefileTargetGenerator::WriteMakeRule(
 
   // For multiple outputs, make the extra ones depend on the first one.
   std::vector<std::string> const output_depends(1, outputs[0]);
+  std::string binDir = this->LocalGenerator->GetBinaryDirectory();
   for (std::vector<std::string>::const_iterator o = outputs.begin() + 1;
        o != outputs.end(); ++o) {
     // Touch the extra output so "make" knows that it was updated,
     // but only if the output was acually created.
-    std::string const out = this->Convert(*o, cmOutputConverter::HOME_OUTPUT,
-                                          cmOutputConverter::SHELL);
+    std::string const out = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(binDir, *o),
+      cmOutputConverter::SHELL);
     std::vector<std::string> output_commands;
 
     bool o_symbolic = false;
@@ -892,7 +919,7 @@ bool cmMakefileTargetGenerator::WriteMakeRule(
     if (!o_symbolic) {
       output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
     }
-    this->LocalGenerator->WriteMakeRule(os, 0, *o, output_depends,
+    this->LocalGenerator->WriteMakeRule(os, CM_NULLPTR, *o, output_depends,
                                         output_commands, o_symbolic, in_help);
 
     if (!o_symbolic) {
@@ -957,12 +984,16 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
     *this->InfoFileStream << "  )\n";
   }
 
+  std::string const& working_dir =
+    this->LocalGenerator->GetCurrentBinaryDirectory();
+
   /* clang-format off */
   *this->InfoFileStream
     << "\n"
     << "# Fortran module output directory.\n"
     << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
-    << this->GetFortranModuleDirectory() << "\")\n";
+    << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
+    << "\")\n";
   /* clang-format on */
 
   // and now write the rule to use it
@@ -984,9 +1015,10 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
   // paths.  Make sure PWD is set to the original name of the home
   // output directory to help cmSystemTools to create the same
   // translation table for the dependency scanning process.
-  depCmd << "cd " << (this->LocalGenerator->Convert(
-                       this->LocalGenerator->GetBinaryDirectory(),
-                       cmOutputConverter::FULL, cmOutputConverter::SHELL))
+  depCmd << "cd " << (this->LocalGenerator->ConvertToOutputFormat(
+                       cmSystemTools::CollapseFullPath(
+                         this->LocalGenerator->GetBinaryDirectory()),
+                       cmOutputConverter::SHELL))
          << " && ";
 #endif
   // Generate a call this signature:
@@ -1000,20 +1032,29 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
   // the state of our local generator sufficiently for its needs.
   depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
          << this->GlobalGenerator->GetName() << "\" "
-         << this->Convert(this->LocalGenerator->GetSourceDirectory(),
-                          cmOutputConverter::FULL, cmOutputConverter::SHELL)
+         << this->LocalGenerator->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(
+                this->LocalGenerator->GetSourceDirectory()),
+              cmOutputConverter::SHELL)
          << " "
-         << this->Convert(this->LocalGenerator->GetCurrentSourceDirectory(),
-                          cmOutputConverter::FULL, cmOutputConverter::SHELL)
+         << this->LocalGenerator->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(
+                this->LocalGenerator->GetCurrentSourceDirectory()),
+              cmOutputConverter::SHELL)
          << " "
-         << this->Convert(this->LocalGenerator->GetBinaryDirectory(),
-                          cmOutputConverter::FULL, cmOutputConverter::SHELL)
+         << this->LocalGenerator->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(
+                this->LocalGenerator->GetBinaryDirectory()),
+              cmOutputConverter::SHELL)
          << " "
-         << this->Convert(this->LocalGenerator->GetCurrentBinaryDirectory(),
-                          cmOutputConverter::FULL, cmOutputConverter::SHELL)
+         << this->LocalGenerator->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(
+                this->LocalGenerator->GetCurrentBinaryDirectory()),
+              cmOutputConverter::SHELL)
          << " "
-         << this->Convert(this->InfoFileNameFull, cmOutputConverter::FULL,
-                          cmOutputConverter::SHELL);
+         << this->LocalGenerator->ConvertToOutputFormat(
+              cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
+              cmOutputConverter::SHELL);
   if (this->LocalGenerator->GetColorMakefile()) {
     depCmd << " --color=$(COLOR)";
   }
@@ -1025,8 +1066,8 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
   }
 
   // Write the rule.
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0, depTarget,
-                                      depends, commands, true);
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      depTarget, depends, commands, true);
 }
 
 void cmMakefileTargetGenerator::DriveCustomCommands(
@@ -1079,8 +1120,8 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile(
   // Now append the actual user-specified commands.
   std::ostringstream content;
   this->LocalGenerator->AppendCustomCommand(
-    commands, ccg, this->GeneratorTarget, false,
-    cmOutputConverter::HOME_OUTPUT, &content);
+    commands, ccg, this->GeneratorTarget,
+    this->LocalGenerator->GetBinaryDirectory(), false, &content);
 
   // Collect the dependencies.
   std::vector<std::string> depends;
@@ -1088,8 +1129,8 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile(
 
   // Write the rule.
   const std::vector<std::string>& outputs = ccg.GetOutputs();
-  bool symbolic =
-    this->WriteMakeRule(*this->BuildFileStream, 0, outputs, depends, commands);
+  bool symbolic = this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      outputs, depends, commands);
 
   // If the rule has changed make sure the output is rebuilt.
   if (!symbolic) {
@@ -1100,10 +1141,8 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile(
   for (cmCustomCommand::ImplicitDependsList::const_iterator idi =
          ccg.GetCC().GetImplicitDepends().begin();
        idi != ccg.GetCC().GetImplicitDepends().end(); ++idi) {
-    std::string objFullPath =
-      this->Convert(outputs[0], cmOutputConverter::FULL);
-    std::string srcFullPath =
-      this->Convert(idi->second, cmOutputConverter::FULL);
+    std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]);
+    std::string srcFullPath = cmSystemTools::CollapseFullPath(idi->second);
     this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi->first,
                                              objFullPath.c_str(),
                                              srcFullPath.c_str());
@@ -1156,10 +1195,12 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
     << this->GeneratorTarget->GetName() << "\n"
     << variableNameExternal << " =";
   /* clang-format on */
+  std::string currentBinDir =
+    this->LocalGenerator->GetCurrentBinaryDirectory();
   for (std::vector<std::string>::const_iterator i =
          this->ExternalObjects.begin();
        i != this->ExternalObjects.end(); ++i) {
-    object = this->Convert(*i, cmOutputConverter::START_OUTPUT);
+    object = this->LocalGenerator->ConvertToRelativePath(currentBinDir, *i);
     *this->BuildFileStream << " " << lineContinue << "\n"
                            << this->Makefile->GetSafeDefinition(
                                 "CMAKE_OBJECT_NAME");
@@ -1192,8 +1233,10 @@ public:
   void Feed(std::string const& obj)
   {
     // Construct the name of the next object.
-    this->NextObject = this->LocalGenerator->Convert(
-      obj, cmOutputConverter::START_OUTPUT, cmOutputConverter::RESPONSE);
+    this->NextObject = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), obj),
+      cmOutputConverter::RESPONSE);
 
     // Roll over to next string if the limit will be exceeded.
     if (this->LengthLimit != std::string::npos &&
@@ -1246,15 +1289,14 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule(
     this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
   std::string buildTargetRuleName = dir;
   buildTargetRuleName += relink ? "/preinstall" : "/build";
-  buildTargetRuleName =
-    this->Convert(buildTargetRuleName, cmOutputConverter::HOME_OUTPUT,
-                  cmOutputConverter::UNCHANGED);
+  buildTargetRuleName = this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
 
   // Build the list of target outputs to drive.
   std::vector<std::string> depends;
   depends.push_back(main_output);
 
-  const char* comment = 0;
+  const char* comment = CM_NULLPTR;
   if (relink) {
     // Setup the comment for the preinstall driver.
     comment = "Rule to relink during preinstall.";
@@ -1436,13 +1478,82 @@ void cmMakefileTargetGenerator::CreateLinkScript(
 
   // Create the makefile command to invoke the link script.
   std::string link_command = "$(CMAKE_COMMAND) -E cmake_link_script ";
-  link_command += this->Convert(
-    linkScriptName, cmOutputConverter::START_OUTPUT, cmOutputConverter::SHELL);
+  link_command += this->LocalGenerator->ConvertToOutputFormat(
+    this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
+    cmOutputConverter::SHELL);
   link_command += " --verbose=$(VERBOSE)";
   makefile_commands.push_back(link_command);
   makefile_depends.push_back(linkScriptName);
 }
 
+static size_t calculateCommandLineLengthLimit()
+{
+#if defined(_SC_ARG_MAX)
+  return ((size_t)sysconf(_SC_ARG_MAX)) - 1000;
+#else
+  return 0;
+#endif
+}
+
+bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
+  std::string const& l) const
+{
+  // Check for an explicit setting one way or the other.
+  std::string const responseVar =
+    "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
+  if (const char* val = this->Makefile->GetDefinition(responseVar)) {
+    if (*val) {
+      return cmSystemTools::IsOn(val);
+    }
+  }
+
+  // Check for a system limit.
+  if (size_t const limit = calculateCommandLineLengthLimit()) {
+    // Compute the total length of our list of object files with room
+    // for argument separation and quoting.  This does not convert paths
+    // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so the
+    // actual list will likely be much shorter than this.  However, in the
+    // worst case all objects will remain as absolute paths.
+    size_t length = 0;
+    for (std::vector<std::string>::const_iterator i = this->Objects.begin();
+         i != this->Objects.end(); ++i) {
+      length += i->size() + 3;
+    }
+    for (std::vector<std::string>::const_iterator i =
+           this->ExternalObjects.begin();
+         i != this->ExternalObjects.end(); ++i) {
+      length += i->size() + 3;
+    }
+
+    // We need to guarantee room for both objects and libraries, so
+    // if the objects take up more than half then use a response file
+    // for them.
+    if (length > (limit / 2)) {
+      return true;
+    }
+  }
+
+  // We do not need a response file for objects.
+  return false;
+}
+
+bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
+  std::string const& l) const
+{
+  // Check for an explicit setting one way or the other.
+  std::string const responseVar =
+    "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
+  if (const char* val = this->Makefile->GetDefinition(responseVar)) {
+    if (*val) {
+      return cmSystemTools::IsOn(val);
+    }
+  }
+
+  // We do not need a response file for libraries.
+  return false;
+}
+
 std::string cmMakefileTargetGenerator::CreateResponseFile(
   const char* name, std::string const& options,
   std::vector<std::string>& makefile_depends)
@@ -1494,8 +1605,8 @@ void cmMakefileTargetGenerator::CreateLinkLibs(
 
     // Reference the response file.
     linkLibs = responseFlag;
-    linkLibs += this->Convert(link_rsp, cmOutputConverter::NONE,
-                              cmOutputConverter::SHELL);
+    linkLibs += this->LocalGenerator->ConvertToOutputFormat(
+      link_rsp, cmOutputConverter::SHELL);
   }
 }
 
@@ -1543,8 +1654,8 @@ void cmMakefileTargetGenerator::CreateObjectLists(
 
       // Reference the response file.
       buildObjs += responseFlag;
-      buildObjs += this->Convert(objects_rsp, cmOutputConverter::NONE,
-                                 cmOutputConverter::SHELL);
+      buildObjs += this->LocalGenerator->ConvertToOutputFormat(
+        objects_rsp, cmOutputConverter::SHELL);
     }
   } else if (useLinkScript) {
     if (!useArchiveRules) {
@@ -1591,3 +1702,51 @@ void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
     this->LocalGenerator->AppendFlags(flags, includeFlags);
   }
 }
+
+void cmMakefileTargetGenerator::GenDefFile(
+  std::vector<std::string>& real_link_commands, std::string& linkFlags)
+{
+  if (this->GeneratorTarget->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
+    std::string name_of_def_file =
+      this->GeneratorTarget->GetSupportDirectory();
+    name_of_def_file += std::string("/") + this->GeneratorTarget->GetName();
+    name_of_def_file += ".def";
+    std::string cmd = cmSystemTools::GetCMakeCommand();
+    cmd = this->LocalGenerator->ConvertToOutputFormat(
+      cmd, cmOutputConverter::SHELL);
+    cmd += " -E __create_def ";
+    cmd += this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), name_of_def_file),
+      cmOutputConverter::SHELL);
+    cmd += " ";
+    std::string objlist_file = name_of_def_file;
+    objlist_file += ".objs";
+    cmd += this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
+      cmOutputConverter::SHELL);
+    real_link_commands.insert(real_link_commands.begin(), cmd);
+    // create a list of obj files for the -E __create_def to read
+    cmGeneratedFileStream fout(objlist_file.c_str());
+    for (std::vector<std::string>::const_iterator i = this->Objects.begin();
+         i != this->Objects.end(); ++i) {
+      if (cmHasLiteralSuffix(*i, ".obj")) {
+        fout << *i << "\n";
+      }
+    }
+    for (std::vector<std::string>::const_iterator i =
+           this->ExternalObjects.begin();
+         i != this->ExternalObjects.end(); ++i) {
+      fout << *i << "\n";
+    }
+    // now add the def file link flag
+    linkFlags += " ";
+    linkFlags += this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
+    linkFlags += this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->ConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), name_of_def_file),
+      cmOutputConverter::SHELL);
+    linkFlags += " ";
+  }
+}
diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h
index c513026..df7b6aa 100644
--- a/Source/cmMakefileTargetGenerator.h
+++ b/Source/cmMakefileTargetGenerator.h
@@ -1,29 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakefileTargetGenerator_h
 #define cmMakefileTargetGenerator_h
 
-#include "cmCommonTargetGenerator.h"
+#include <cmConfigure.h>
 
+#include "cmCommonTargetGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmOSXBundleGenerator.h"
 
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 class cmCustomCommandGenerator;
-class cmDepends;
-class cmGeneratorTarget;
 class cmGeneratedFileStream;
+class cmGeneratorTarget;
 class cmGlobalUnixMakefileGenerator3;
-class cmLocalUnixMakefileGenerator3;
-class cmMakefile;
 class cmSourceFile;
 
 /** \class cmMakefileTargetGenerator
@@ -35,7 +30,7 @@ class cmMakefileTargetGenerator : public cmCommonTargetGenerator
 public:
   // constructor to set the ivars
   cmMakefileTargetGenerator(cmGeneratorTarget* target);
-  virtual ~cmMakefileTargetGenerator();
+  ~cmMakefileTargetGenerator() CM_OVERRIDE;
 
   // construct using this factory call
   static cmMakefileTargetGenerator* New(cmGeneratorTarget* tgt);
@@ -83,7 +78,8 @@ protected:
     {
     }
 
-    void operator()(cmSourceFile const& source, const char* pkgloc);
+    void operator()(cmSourceFile const& source,
+                    const char* pkgloc) CM_OVERRIDE;
 
   private:
     cmMakefileTargetGenerator* Generator;
@@ -150,6 +146,9 @@ protected:
   std::string CreateResponseFile(const char* name, std::string const& options,
                                  std::vector<std::string>& makefile_depends);
 
+  bool CheckUseResponseFileForObjects(std::string const& l) const;
+  bool CheckUseResponseFileForLibraries(std::string const& l) const;
+
   /** Create list of flags for link libraries. */
   void CreateLinkLibs(std::string& linkLibs, bool relink, bool useResponseFile,
                       std::vector<std::string>& makefile_depends,
@@ -161,7 +160,12 @@ protected:
                          std::vector<std::string>& makefile_depends,
                          bool useWatcomQuote);
 
-  void AddIncludeFlags(std::string& flags, const std::string& lang);
+  /** Add commands for generate def files */
+  void GenDefFile(std::vector<std::string>& real_link_commands,
+                  std::string& linkFlags);
+
+  void AddIncludeFlags(std::string& flags,
+                       const std::string& lang) CM_OVERRIDE;
 
   virtual void CloseFileStreams();
   void RemoveForbiddenFlags(const char* flagVar, const std::string& linkLang,
diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx
index 6e44e8f..f40c8fa 100644
--- a/Source/cmMakefileUtilityTargetGenerator.cxx
+++ b/Source/cmMakefileUtilityTargetGenerator.cxx
@@ -1,21 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileUtilityTargetGenerator.h"
 
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
+#include "cmOSXBundleGenerator.h"
+#include "cmOutputConverter.h"
+
+#include <ostream>
+#include <string>
+#include <vector>
 
 cmMakefileUtilityTargetGenerator::cmMakefileUtilityTargetGenerator(
   cmGeneratorTarget* target)
@@ -47,9 +44,12 @@ void cmMakefileUtilityTargetGenerator::WriteRuleFiles()
     *this->BuildFileStream
       << "# Include the progress variables for this target.\n"
       << this->GlobalGenerator->IncludeDirective << " " << root
-      << this->Convert(this->ProgressFileNameFull,
-                       cmOutputConverter::HOME_OUTPUT,
-                       cmOutputConverter::MAKERULE)
+      << cmSystemTools::ConvertToOutputPath(
+           this->LocalGenerator
+             ->ConvertToRelativePath(
+               this->LocalGenerator->GetBinaryDirectory(),
+               this->ProgressFileNameFull)
+             .c_str())
       << "\n\n";
   }
 
@@ -69,14 +69,14 @@ void cmMakefileUtilityTargetGenerator::WriteRuleFiles()
 
   this->LocalGenerator->AppendCustomCommands(
     commands, this->GeneratorTarget->GetPreBuildCommands(),
-    this->GeneratorTarget);
+    this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
 
   // Depend on all custom command outputs for sources
   this->DriveCustomCommands(depends);
 
   this->LocalGenerator->AppendCustomCommands(
     commands, this->GeneratorTarget->GetPostBuildCommands(),
-    this->GeneratorTarget);
+    this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
 
   // Add dependencies on targets that must be built first.
   this->AppendTargetDepends(depends);
@@ -95,7 +95,7 @@ void cmMakefileUtilityTargetGenerator::WriteRuleFiles()
   }
 
   // Write the rule.
-  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0,
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
                                       this->GeneratorTarget->GetName(),
                                       depends, commands, true);
 
diff --git a/Source/cmMakefileUtilityTargetGenerator.h b/Source/cmMakefileUtilityTargetGenerator.h
index dbb312c..332c04e 100644
--- a/Source/cmMakefileUtilityTargetGenerator.h
+++ b/Source/cmMakefileUtilityTargetGenerator.h
@@ -1,28 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMakefileUtilityTargetGenerator_h
 #define cmMakefileUtilityTargetGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmMakefileTargetGenerator.h"
 
+class cmGeneratorTarget;
+
 class cmMakefileUtilityTargetGenerator : public cmMakefileTargetGenerator
 {
 public:
   cmMakefileUtilityTargetGenerator(cmGeneratorTarget* target);
-  virtual ~cmMakefileUtilityTargetGenerator();
+  ~cmMakefileUtilityTargetGenerator() CM_OVERRIDE;
 
   /* the main entry point for this class. Writes the Makefiles associated
      with this target */
-  virtual void WriteRuleFiles();
+  void WriteRuleFiles() CM_OVERRIDE;
 
 protected:
 };
diff --git a/Source/cmMarkAsAdvancedCommand.cxx b/Source/cmMarkAsAdvancedCommand.cxx
index 07f1fa8..5ec1620 100644
--- a/Source/cmMarkAsAdvancedCommand.cxx
+++ b/Source/cmMarkAsAdvancedCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMarkAsAdvancedCommand.h"
 
 // cmMarkAsAdvancedCommand
 bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -35,7 +26,7 @@ bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args,
     cmState* state = this->Makefile->GetState();
     if (!state->GetCacheEntryValue(variable)) {
       this->Makefile->GetCMakeInstance()->AddCacheEntry(
-        variable, 0, 0, cmState::UNINITIALIZED);
+        variable, CM_NULLPTR, CM_NULLPTR, cmState::UNINITIALIZED);
       overwrite = true;
     }
     if (!state->GetCacheEntryValue(variable)) {
diff --git a/Source/cmMarkAsAdvancedCommand.h b/Source/cmMarkAsAdvancedCommand.h
index add43c9..54fa78a 100644
--- a/Source/cmMarkAsAdvancedCommand.h
+++ b/Source/cmMarkAsAdvancedCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMarkAsAdvancedCommand_h
 #define cmMarkAsAdvancedCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmMarkAsAdvancedCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmMarkAsAdvancedCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "mark_as_advanced"; }
+  std::string GetName() const CM_OVERRIDE { return "mark_as_advanced"; }
 
   /**
    * This determines if the command is invoked when in script mode.
@@ -45,7 +36,7 @@ public:
    * make many of the modules usable in cmake/ctest scripts, (among them
    * FindUnixMake.cmake used by the CTEST_BUILD command.
   */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmMarkAsAdvancedCommand, cmCommand);
 };
diff --git a/Source/cmMathCommand.cxx b/Source/cmMathCommand.cxx
index ca8b926..42e6b90 100644
--- a/Source/cmMathCommand.cxx
+++ b/Source/cmMathCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMathCommand.h"
 
 #include "cmExprParserHelper.h"
@@ -16,7 +7,7 @@
 bool cmMathCommand::InitialPass(std::vector<std::string> const& args,
                                 cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("must be called with at least one argument.");
     return false;
   }
diff --git a/Source/cmMathCommand.h b/Source/cmMathCommand.h
index 3ac6f41..6fa7389 100644
--- a/Source/cmMathCommand.h
+++ b/Source/cmMathCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMathCommand_h
 #define cmMathCommand_h
 
@@ -21,24 +12,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmMathCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmMathCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "math"; }
+  std::string GetName() const CM_OVERRIDE { return "math"; }
 
   cmTypeMacro(cmMathCommand, cmCommand);
 
diff --git a/Source/cmMessageCommand.cxx b/Source/cmMessageCommand.cxx
index f4458a7..9a83cd9 100644
--- a/Source/cmMessageCommand.cxx
+++ b/Source/cmMessageCommand.cxx
@@ -1,21 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMessageCommand.h"
 
+#include "cmMessenger.h"
+
 // cmLibraryCommand
 bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -24,7 +17,6 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
   cmake::MessageType type = cmake::MESSAGE;
   bool status = false;
   bool fatal = false;
-  cmake* cm = this->Makefile->GetCMakeInstance();
   if (*i == "SEND_ERROR") {
     type = cmake::FATAL_ERROR;
     ++i;
@@ -36,10 +28,11 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
     type = cmake::WARNING;
     ++i;
   } else if (*i == "AUTHOR_WARNING") {
-    if (cm->GetDevWarningsAsErrors(this->Makefile)) {
+    if (this->Makefile->IsSet("CMAKE_SUPPRESS_DEVELOPER_ERRORS") &&
+        !this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_ERRORS")) {
       fatal = true;
       type = cmake::AUTHOR_ERROR;
-    } else if (!cm->GetSuppressDevWarnings(this->Makefile)) {
+    } else if (!this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
       type = cmake::AUTHOR_WARNING;
     } else {
       return true;
@@ -49,10 +42,11 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
     status = true;
     ++i;
   } else if (*i == "DEPRECATION") {
-    if (cm->GetDeprecatedWarningsAsErrors(this->Makefile)) {
+    if (this->Makefile->IsOn("CMAKE_ERROR_DEPRECATED")) {
       fatal = true;
       type = cmake::DEPRECATION_ERROR;
-    } else if (!cm->GetSuppressDeprecatedWarnings(this->Makefile)) {
+    } else if ((!this->Makefile->IsSet("CMAKE_WARN_DEPRECATED") ||
+                this->Makefile->IsOn("CMAKE_WARN_DEPRECATED"))) {
       type = cmake::DEPRECATION_WARNING;
     } else {
       return true;
@@ -63,8 +57,9 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
   std::string message = cmJoin(cmMakeRange(i, args.end()), std::string());
 
   if (type != cmake::MESSAGE) {
-    // we've overriden the message type, above, so force IssueMessage to use it
-    this->Makefile->IssueMessage(type, message, true);
+    // we've overriden the message type, above, so display it directly
+    cmMessenger* m = this->Makefile->GetMessenger();
+    m->DisplayMessage(type, message, this->Makefile->GetBacktrace());
   } else {
     if (status) {
       this->Makefile->DisplayStatus(message.c_str(), -1);
diff --git a/Source/cmMessageCommand.h b/Source/cmMessageCommand.h
index afc5509..a67d52b 100644
--- a/Source/cmMessageCommand.h
+++ b/Source/cmMessageCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmMessageCommand_h
 #define cmMessageCommand_h
 
@@ -24,24 +15,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmMessageCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmMessageCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "message"; }
+  std::string GetName() const CM_OVERRIDE { return "message"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmMessageCommand, cmCommand);
 };
diff --git a/Source/cmMessenger.cxx b/Source/cmMessenger.cxx
new file mode 100644
index 0000000..fe1c261
--- /dev/null
+++ b/Source/cmMessenger.cxx
@@ -0,0 +1,203 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmMessenger.h"
+
+#include "cmAlgorithms.h"
+#include "cmDocumentationFormatter.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/SystemInformation.hxx>
+#endif
+
+#include <sstream>
+
+cmake::MessageType cmMessenger::ConvertMessageType(cmake::MessageType t) const
+{
+  bool warningsAsErrors;
+
+  if (t == cmake::AUTHOR_WARNING || t == cmake::AUTHOR_ERROR) {
+    warningsAsErrors = this->GetDevWarningsAsErrors();
+    if (warningsAsErrors && t == cmake::AUTHOR_WARNING) {
+      t = cmake::AUTHOR_ERROR;
+    } else if (!warningsAsErrors && t == cmake::AUTHOR_ERROR) {
+      t = cmake::AUTHOR_WARNING;
+    }
+  } else if (t == cmake::DEPRECATION_WARNING ||
+             t == cmake::DEPRECATION_ERROR) {
+    warningsAsErrors = this->GetDeprecatedWarningsAsErrors();
+    if (warningsAsErrors && t == cmake::DEPRECATION_WARNING) {
+      t = cmake::DEPRECATION_ERROR;
+    } else if (!warningsAsErrors && t == cmake::DEPRECATION_ERROR) {
+      t = cmake::DEPRECATION_WARNING;
+    }
+  }
+
+  return t;
+}
+
+bool cmMessenger::IsMessageTypeVisible(cmake::MessageType t) const
+{
+  bool isVisible = true;
+
+  if (t == cmake::DEPRECATION_ERROR) {
+    if (!this->GetDeprecatedWarningsAsErrors()) {
+      isVisible = false;
+    }
+  } else if (t == cmake::DEPRECATION_WARNING) {
+    if (this->GetSuppressDeprecatedWarnings()) {
+      isVisible = false;
+    }
+  } else if (t == cmake::AUTHOR_ERROR) {
+    if (!this->GetDevWarningsAsErrors()) {
+      isVisible = false;
+    }
+  } else if (t == cmake::AUTHOR_WARNING) {
+    if (this->GetSuppressDevWarnings()) {
+      isVisible = false;
+    }
+  }
+
+  return isVisible;
+}
+
+static bool printMessagePreamble(cmake::MessageType t, std::ostream& msg)
+{
+  // Construct the message header.
+  if (t == cmake::FATAL_ERROR) {
+    msg << "CMake Error";
+  } else if (t == cmake::INTERNAL_ERROR) {
+    msg << "CMake Internal Error (please report a bug)";
+  } else if (t == cmake::LOG) {
+    msg << "CMake Debug Log";
+  } else if (t == cmake::DEPRECATION_ERROR) {
+    msg << "CMake Deprecation Error";
+  } else if (t == cmake::DEPRECATION_WARNING) {
+    msg << "CMake Deprecation Warning";
+  } else if (t == cmake::AUTHOR_WARNING) {
+    msg << "CMake Warning (dev)";
+  } else if (t == cmake::AUTHOR_ERROR) {
+    msg << "CMake Error (dev)";
+  } else {
+    msg << "CMake Warning";
+  }
+  return true;
+}
+
+void printMessageText(std::ostream& msg, std::string const& text)
+{
+  msg << ":\n";
+  cmDocumentationFormatter formatter;
+  formatter.SetIndent("  ");
+  formatter.PrintFormatted(msg, text.c_str());
+}
+
+void displayMessage(cmake::MessageType t, std::ostringstream& msg)
+{
+  // Add a note about warning suppression.
+  if (t == cmake::AUTHOR_WARNING) {
+    msg << "This warning is for project developers.  Use -Wno-dev to suppress "
+           "it.";
+  } else if (t == cmake::AUTHOR_ERROR) {
+    msg << "This error is for project developers. Use -Wno-error=dev to "
+           "suppress "
+           "it.";
+  }
+
+  // Add a terminating blank line.
+  msg << "\n";
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  // Add a C++ stack trace to internal errors.
+  if (t == cmake::INTERNAL_ERROR) {
+    std::string stack = cmsys::SystemInformation::GetProgramStack(0, 0);
+    if (!stack.empty()) {
+      if (cmHasLiteralPrefix(stack, "WARNING:")) {
+        stack = "Note:" + stack.substr(8);
+      }
+      msg << stack << "\n";
+    }
+  }
+#endif
+
+  // Output the message.
+  if (t == cmake::FATAL_ERROR || t == cmake::INTERNAL_ERROR ||
+      t == cmake::DEPRECATION_ERROR || t == cmake::AUTHOR_ERROR) {
+    cmSystemTools::SetErrorOccured();
+    cmSystemTools::Message(msg.str().c_str(), "Error");
+  } else {
+    cmSystemTools::Message(msg.str().c_str(), "Warning");
+  }
+}
+
+cmMessenger::cmMessenger(cmState* state)
+  : State(state)
+{
+}
+
+void cmMessenger::IssueMessage(cmake::MessageType t, const std::string& text,
+                               const cmListFileBacktrace& backtrace) const
+{
+  bool force = false;
+  if (!force) {
+    // override the message type, if needed, for warnings and errors
+    cmake::MessageType override = this->ConvertMessageType(t);
+    if (override != t) {
+      t = override;
+      force = true;
+    }
+  }
+
+  if (!force && !this->IsMessageTypeVisible(t)) {
+    return;
+  }
+  this->DisplayMessage(t, text, backtrace);
+}
+
+void cmMessenger::DisplayMessage(cmake::MessageType t, const std::string& text,
+                                 const cmListFileBacktrace& backtrace) const
+{
+  std::ostringstream msg;
+  if (!printMessagePreamble(t, msg)) {
+    return;
+  }
+
+  // Add the immediate context.
+  backtrace.PrintTitle(msg);
+
+  printMessageText(msg, text);
+
+  // Add the rest of the context.
+  backtrace.PrintCallStack(msg);
+
+  displayMessage(t, msg);
+}
+
+bool cmMessenger::GetSuppressDevWarnings() const
+{
+  const char* cacheEntryValue =
+    this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
+  return cmSystemTools::IsOn(cacheEntryValue);
+}
+
+bool cmMessenger::GetSuppressDeprecatedWarnings() const
+{
+  const char* cacheEntryValue =
+    this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
+  return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue);
+}
+
+bool cmMessenger::GetDevWarningsAsErrors() const
+{
+  const char* cacheEntryValue =
+    this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
+  return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue);
+}
+
+bool cmMessenger::GetDeprecatedWarningsAsErrors() const
+{
+  const char* cacheEntryValue =
+    this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
+  return cmSystemTools::IsOn(cacheEntryValue);
+}
diff --git a/Source/cmMessenger.h b/Source/cmMessenger.h
new file mode 100644
index 0000000..89f8efe
--- /dev/null
+++ b/Source/cmMessenger.h
@@ -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.  */
+#ifndef cmMessenger_h
+#define cmMessenger_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include "cmListFileCache.h"
+#include "cmake.h"
+
+#include <string>
+
+class cmState;
+
+class cmMessenger
+{
+public:
+  cmMessenger(cmState* state);
+
+  void IssueMessage(
+    cmake::MessageType t, std::string const& text,
+    cmListFileBacktrace const& backtrace = cmListFileBacktrace()) const;
+
+  void DisplayMessage(cmake::MessageType t, std::string const& text,
+                      cmListFileBacktrace const& backtrace) const;
+
+  bool GetSuppressDevWarnings() const;
+  bool GetSuppressDeprecatedWarnings() const;
+  bool GetDevWarningsAsErrors() const;
+  bool GetDeprecatedWarningsAsErrors() const;
+
+private:
+  bool IsMessageTypeVisible(cmake::MessageType t) const;
+  cmake::MessageType ConvertMessageType(cmake::MessageType t) const;
+
+  cmState* State;
+};
+
+#endif
diff --git a/Source/cmNewLineStyle.cxx b/Source/cmNewLineStyle.cxx
index c03f60d..55451ff 100644
--- a/Source/cmNewLineStyle.cxx
+++ b/Source/cmNewLineStyle.cxx
@@ -1,16 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNewLineStyle.h"
 
+#include <stddef.h>
+
 cmNewLineStyle::cmNewLineStyle()
   : NewLineStyle(Invalid)
 {
@@ -34,19 +27,18 @@ bool cmNewLineStyle::ReadFromArguments(const std::vector<std::string>& args,
         if (eol == "LF" || eol == "UNIX") {
           NewLineStyle = LF;
           return true;
-        } else if (eol == "CRLF" || eol == "WIN32" || eol == "DOS") {
+        }
+        if (eol == "CRLF" || eol == "WIN32" || eol == "DOS") {
           NewLineStyle = CRLF;
           return true;
-        } else {
-          errorString = "NEWLINE_STYLE sets an unknown style, only LF, "
-                        "CRLF, UNIX, DOS, and WIN32 are supported";
-          return false;
         }
-      } else {
-        errorString = "NEWLINE_STYLE must set a style: "
-                      "LF, CRLF, UNIX, DOS, or WIN32";
+        errorString = "NEWLINE_STYLE sets an unknown style, only LF, "
+                      "CRLF, UNIX, DOS, and WIN32 are supported";
         return false;
       }
+      errorString = "NEWLINE_STYLE must set a style: "
+                    "LF, CRLF, UNIX, DOS, or WIN32";
+      return false;
     }
   }
   return true;
diff --git a/Source/cmNewLineStyle.h b/Source/cmNewLineStyle.h
index 800f131..b46414c 100644
--- a/Source/cmNewLineStyle.h
+++ b/Source/cmNewLineStyle.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmNewLineStyle_h
 #define cmNewLineStyle_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 class cmNewLineStyle
 {
diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx
index 1386a04..cd6dd1a 100644
--- a/Source/cmNinjaNormalTargetGenerator.cxx
+++ b/Source/cmNinjaNormalTargetGenerator.cxx
@@ -1,30 +1,32 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNinjaNormalTargetGenerator.h"
 
 #include "cmAlgorithms.h"
+#include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalNinjaGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
+#include "cmNinjaTypes.h"
 #include "cmOSXBundleGenerator.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
 
 #include <algorithm>
 #include <assert.h>
+#include <iterator>
 #include <limits>
+#include <map>
+#include <set>
+#include <sstream>
+#include <stddef.h>
 
 #ifndef _WIN32
 #include <unistd.h>
@@ -41,15 +43,16 @@ cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
   , TargetLinkLanguage("")
 {
   this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
-  if (target->GetType() == cmState::EXECUTABLE)
+  if (target->GetType() == cmState::EXECUTABLE) {
     this->GetGeneratorTarget()->GetExecutableNames(
       this->TargetNameOut, this->TargetNameReal, this->TargetNameImport,
       this->TargetNamePDB, GetLocalGenerator()->GetConfigName());
-  else
+  } else {
     this->GetGeneratorTarget()->GetLibraryNames(
       this->TargetNameOut, this->TargetNameSO, this->TargetNameReal,
       this->TargetNameImport, this->TargetNamePDB,
       GetLocalGenerator()->GetConfigName());
+  }
 
   if (target->GetType() != cmState::OBJECT_LIBRARY) {
     // on Windows the output dir is already needed at compile time
@@ -125,14 +128,15 @@ const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
     case cmState::SHARED_LIBRARY:
       return "shared library";
     case cmState::MODULE_LIBRARY:
-      if (this->GetGeneratorTarget()->IsCFBundleOnApple())
+      if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
         return "CFBundle shared module";
-      else
+      } else {
         return "shared module";
+      }
     case cmState::EXECUTABLE:
       return "executable";
     default:
-      return 0;
+      return CM_NULLPTR;
   }
 }
 
@@ -144,6 +148,14 @@ std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
                     this->GetGeneratorTarget()->GetName());
 }
 
+struct cmNinjaRemoveNoOpCommands
+{
+  bool operator()(std::string const& cmd)
+  {
+    return cmd.empty() || cmd[0] == ':';
+  }
+};
+
 void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
 {
   cmState::TargetType targetType = this->GetGeneratorTarget()->GetType();
@@ -231,6 +243,13 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
          i != linkCmds.end(); ++i) {
       this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
     }
+    {
+      // If there is no ranlib the command will be ":".  Skip it.
+      std::vector<std::string>::iterator newEnd = std::remove_if(
+        linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
+      linkCmds.erase(newEnd, linkCmds.end());
+    }
+
     linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
     linkCmds.push_back("$POST_BUILD");
     std::string linkCmd =
@@ -256,7 +275,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
     std::string cmakeCommand =
       this->GetLocalGenerator()->ConvertToOutputFormat(
         cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
-    if (targetType == cmState::EXECUTABLE)
+    if (targetType == cmState::EXECUTABLE) {
       this->GetGlobalGenerator()->AddRule(
         "CMAKE_SYMLINK_EXECUTABLE",
         cmakeCommand + " -E cmake_symlink_executable"
@@ -269,7 +288,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
         /*rspcontent*/ "",
         /*restat*/ "",
         /*generator*/ false);
-    else
+    } else {
       this->GetGlobalGenerator()->AddRule(
         "CMAKE_SYMLINK_LIBRARY",
         cmakeCommand + " -E cmake_symlink_library"
@@ -282,6 +301,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
         /*rspcontent*/ "",
         /*restat*/ "",
         /*generator*/ false);
+    }
   }
 }
 
@@ -295,6 +315,22 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
     const char* linkCmd = mf->GetDefinition(linkCmdVar);
     if (linkCmd) {
       cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
+      if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
+        std::string cmakeCommand =
+          this->GetLocalGenerator()->ConvertToOutputFormat(
+            cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
+        cmakeCommand += " -E __run_iwyu --lwyu=";
+        cmGeneratorTarget& gt = *this->GetGeneratorTarget();
+        const std::string cfgName = this->GetConfigName();
+        std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
+        std::string targetOutputReal =
+          this->ConvertToNinjaPath(gt.GetFullPath(cfgName,
+                                                  /*implib=*/false,
+                                                  /*realname=*/true));
+        cmakeCommand += targetOutputReal;
+        cmakeCommand += " || true";
+        linkCmds.push_back(cmakeCommand);
+      }
       return linkCmds;
     }
   }
@@ -340,7 +376,7 @@ static int calculateCommandLineLengthLimit(int linkRuleLength)
 #ifdef _WIN32
     8000,
 #endif
-#if defined(__APPLE__) || defined(__HAIKU__) || defined(__linux)
+#if defined(_SC_ARG_MAX)
     // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
     ((int)sysconf(_SC_ARG_MAX)) - 1000,
 #endif
@@ -368,7 +404,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   std::string targetOutputReal =
     ConvertToNinjaPath(gt.GetFullPath(cfgName,
                                       /*implib=*/false,
-                                      /*realpath=*/true));
+                                      /*realname=*/true));
   std::string targetOutputImplib =
     ConvertToNinjaPath(gt.GetFullPath(cfgName,
                                       /*implib=*/true));
@@ -434,11 +470,12 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   vars["TARGET_FILE"] =
     localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
 
-  localGen.GetTargetFlags(vars["LINK_LIBRARIES"], vars["FLAGS"],
-                          vars["LINK_FLAGS"], frameworkPath, linkPath,
-                          &genTarget, useWatcomQuote);
+  localGen.GetTargetFlags(this->GetConfigName(), vars["LINK_LIBRARIES"],
+                          vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath,
+                          linkPath, &genTarget, useWatcomQuote);
   if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
-      gt.GetType() == cmState::SHARED_LIBRARY) {
+      (gt.GetType() == cmState::SHARED_LIBRARY ||
+       gt.IsExecutableWithExports())) {
     if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
       std::string name_of_def_file = gt.GetSupportDirectory();
       name_of_def_file += "/" + gt.GetName();
@@ -467,6 +504,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   vars["MANIFESTS"] = this->GetManifests();
 
   vars["LINK_PATH"] = frameworkPath + linkPath;
+  std::string lwyuFlags;
+  if (genTarget.GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
+    lwyuFlags = " -Wl,--no-as-needed";
+  }
 
   // Compute architecture specific link flags.  Yes, these go into a different
   // variable for executables, probably due to a mistake made when duplicating
@@ -474,16 +515,17 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   if (targetType == cmState::EXECUTABLE) {
     std::string t = vars["FLAGS"];
     localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
+    t += lwyuFlags;
     vars["FLAGS"] = t;
   } else {
     std::string t = vars["ARCH_FLAGS"];
     localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
     vars["ARCH_FLAGS"] = t;
     t = "";
+    t += lwyuFlags;
     localGen.AddLanguageFlags(t, TargetLinkLanguage, cfgName);
     vars["LANGUAGE_COMPILE_FLAGS"] = t;
   }
-
   if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
     vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
     vars["SONAME"] = this->TargetNameSO;
@@ -491,8 +533,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
       std::string install_dir =
         this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
       if (!install_dir.empty()) {
-        vars["INSTALLNAME_DIR"] = localGen.Convert(
-          install_dir, cmOutputConverter::NONE, cmOutputConverter::SHELL);
+        vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
+          install_dir, cmOutputConverter::SHELL);
       }
     }
   }
@@ -560,7 +602,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   }
 
   // maybe create .def file from list of objects
-  if (gt.GetType() == cmState::SHARED_LIBRARY &&
+  if ((gt.GetType() == cmState::SHARED_LIBRARY ||
+       gt.IsExecutableWithExports()) &&
       this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
       std::string cmakeCommand =
@@ -589,7 +632,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
       }
     }
   }
-  // If we have any PRE_LINK commands, we need to go back to HOME_OUTPUT for
+  // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
+  // for
   // the link commands.
   if (!preLinkCmdLines.empty()) {
     const std::string homeOutDir = localGen.ConvertToOutputFormat(
@@ -601,13 +645,14 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines);
 
   cmNinjaVars symlinkVars;
-  if (targetOutput == targetOutputReal) {
+  bool const symlinkNeeded =
+    (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple());
+  if (!symlinkNeeded) {
     vars["POST_BUILD"] = postBuildCmdLine;
   } else {
     vars["POST_BUILD"] = ":";
     symlinkVars["POST_BUILD"] = postBuildCmdLine;
   }
-
   cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
 
   int commandLineLengthLimit = -1;
@@ -638,18 +683,20 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   // Write the build statement for this target.
   bool usedResponseFile = false;
   globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
-                       this->LanguageLinkerRule(), outputs, explicitDeps,
+                       this->LanguageLinkerRule(), outputs,
+                       /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
                        implicitDeps, orderOnlyDeps, vars, rspfile,
                        commandLineLengthLimit, &usedResponseFile);
   this->WriteLinkRule(usedResponseFile);
 
-  if (targetOutput != targetOutputReal && !gt.IsFrameworkOnApple()) {
+  if (symlinkNeeded) {
     if (targetType == cmState::EXECUTABLE) {
       globalGen.WriteBuild(
         this->GetBuildFileStream(),
         "Create executable symlink " + targetOutput,
         "CMAKE_SYMLINK_EXECUTABLE", cmNinjaDeps(1, targetOutput),
-        cmNinjaDeps(1, targetOutputReal), emptyDeps, emptyDeps, symlinkVars);
+        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
+        emptyDeps, emptyDeps, symlinkVars);
     } else {
       cmNinjaDeps symlinks;
       std::string const soName =
@@ -664,7 +711,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
       symlinks.push_back(targetOutput);
       globalGen.WriteBuild(
         this->GetBuildFileStream(), "Create library symlink " + targetOutput,
-        "CMAKE_SYMLINK_LIBRARY", symlinks, cmNinjaDeps(1, targetOutputReal),
+        "CMAKE_SYMLINK_LIBRARY", symlinks,
+        /*implicitOuts=*/cmNinjaDeps(), cmNinjaDeps(1, targetOutputReal),
         emptyDeps, emptyDeps, symlinkVars);
     }
   }
diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h
index 300618c..5bd906f 100644
--- a/Source/cmNinjaNormalTargetGenerator.h
+++ b/Source/cmNinjaNormalTargetGenerator.h
@@ -1,35 +1,24 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmNinjaNormalTargetGenerator_h
 #define cmNinjaNormalTargetGenerator_h
 
-#include "cmNinjaTargetGenerator.h"
+#include <cmConfigure.h>
 
-#include "cmNinjaTypes.h"
+#include "cmNinjaTargetGenerator.h"
 
-#include <set>
+#include <string>
+#include <vector>
 
-class cmSourceFile;
-class cmOSXBundleGenerator;
 class cmGeneratorTarget;
 
 class cmNinjaNormalTargetGenerator : public cmNinjaTargetGenerator
 {
 public:
   cmNinjaNormalTargetGenerator(cmGeneratorTarget* target);
-  ~cmNinjaNormalTargetGenerator();
+  ~cmNinjaNormalTargetGenerator() CM_OVERRIDE;
 
-  void Generate();
+  void Generate() CM_OVERRIDE;
 
 private:
   std::string LanguageLinkerRule() const;
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index bad5e2f..46a6161 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNinjaTargetGenerator.h"
 
 #include "cmAlgorithms.h"
@@ -18,14 +8,24 @@
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalNinjaGenerator.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
 #include "cmNinjaNormalTargetGenerator.h"
 #include "cmNinjaUtilityTargetGenerator.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmake.h"
+
+#include "cm_jsoncpp_writer.h"
 
 #include <algorithm>
+#include <iterator>
+#include <map>
+#include <sstream>
+#include <string.h>
 
 cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
 {
@@ -38,28 +38,18 @@ cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
       return new cmNinjaNormalTargetGenerator(target);
 
     case cmState::UTILITY:
+    case cmState::GLOBAL_TARGET:
       return new cmNinjaUtilityTargetGenerator(target);
-      ;
-
-    case cmState::GLOBAL_TARGET: {
-      // We only want to process global targets that live in the home
-      // (i.e. top-level) directory.  CMake creates copies of these targets
-      // in every directory, which we don't need.
-      if (strcmp(target->GetLocalGenerator()->GetCurrentSourceDirectory(),
-                 target->GetLocalGenerator()->GetSourceDirectory()) == 0)
-        return new cmNinjaUtilityTargetGenerator(target);
-      // else fallthrough
-    }
 
     default:
-      return 0;
+      return CM_NULLPTR;
   }
 }
 
 cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
-  : cmCommonTargetGenerator(cmOutputConverter::HOME_OUTPUT, target)
-  , MacOSXContentGenerator(0)
-  , OSXBundleGenerator(0)
+  : cmCommonTargetGenerator(target)
+  , MacOSXContentGenerator(CM_NULLPTR)
+  , OSXBundleGenerator(CM_NULLPTR)
   , MacContentFolders()
   , LocalGenerator(
       static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
@@ -95,6 +85,31 @@ std::string cmNinjaTargetGenerator::LanguageCompilerRule(
     cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
 }
 
+std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
+  std::string const& lang) const
+{
+  return lang + "_PREPROCESS__" +
+    cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
+}
+
+bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
+  std::string const& lang) const
+{
+  return lang == "Fortran";
+}
+
+std::string cmNinjaTargetGenerator::LanguageDyndepRule(
+  const std::string& lang) const
+{
+  return lang + "_DYNDEP__" +
+    cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
+}
+
+bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
+{
+  return lang == "Fortran";
+}
+
 std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget()
 {
   return "cmake_order_depends_target_" + this->GetTargetName();
@@ -130,11 +145,11 @@ void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
   // Add include directory flags.
   std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
     includes, this->GeneratorTarget, language,
-    language == "RC" ? true : false, // full include paths for RC
-    // needed by cmcldeps
+    language == "RC", // full include paths for RC needed by cmcldeps
     false, this->GetConfigName());
-  if (this->GetGlobalGenerator()->IsGCCOnWindows())
+  if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
     std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
+  }
 
   this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
 }
@@ -171,13 +186,15 @@ cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const
 {
   // Static libraries never depend on other targets for linking.
   if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-      this->GeneratorTarget->GetType() == cmState::OBJECT_LIBRARY)
+      this->GeneratorTarget->GetType() == cmState::OBJECT_LIBRARY) {
     return cmNinjaDeps();
+  }
 
   cmComputeLinkInformation* cli =
     this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
-  if (!cli)
+  if (!cli) {
     return cmNinjaDeps();
+  }
 
   const std::vector<std::string>& deps = cli->GetDepends();
   cmNinjaDeps result(deps.size());
@@ -219,8 +236,9 @@ std::string cmNinjaTargetGenerator::GetObjectFilePath(
   cmSourceFile const* source) const
 {
   std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
-  if (!path.empty())
+  if (!path.empty()) {
     path += "/";
+  }
   std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
   path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
   path += "/";
@@ -228,6 +246,64 @@ std::string cmNinjaTargetGenerator::GetObjectFilePath(
   return path;
 }
 
+std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
+  cmSourceFile const* source) const
+{
+  // Choose an extension to compile already-preprocessed source.
+  std::string ppExt = source->GetExtension();
+  if (cmHasLiteralPrefix(ppExt, "F")) {
+    // Some Fortran compilers automatically enable preprocessing for
+    // upper-case extensions.  Since the source is already preprocessed,
+    // use a lower-case extension.
+    ppExt = cmSystemTools::LowerCase(ppExt);
+  }
+  if (ppExt == "fpp") {
+    // Some Fortran compilers automatically enable preprocessing for
+    // the ".fpp" extension.  Since the source is already preprocessed,
+    // use the ".f" extension.
+    ppExt = "f";
+  }
+
+  // Take the object file name and replace the extension.
+  std::string const& objName = this->GeneratorTarget->GetObjectName(source);
+  std::string const& objExt =
+    this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
+  assert(objName.size() >= objExt.size());
+  std::string const ppName =
+    objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt;
+
+  std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
+  if (!path.empty())
+    path += "/";
+  path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
+  path += "/";
+  path += ppName;
+  return path;
+}
+
+std::string cmNinjaTargetGenerator::GetDyndepFilePath(
+  std::string const& lang) const
+{
+  std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
+  if (!path.empty())
+    path += "/";
+  path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
+  path += "/";
+  path += lang;
+  path += ".dd";
+  return path;
+}
+
+std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
+  std::string const& lang) const
+{
+  std::string path = this->Makefile->GetCurrentBinaryDirectory();
+  path += "/";
+  path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
+  path += "/" + lang + "DependInfo.json";
+  return path;
+}
+
 std::string cmNinjaTargetGenerator::GetTargetOutputDir() const
 {
   std::string dir = this->GeneratorTarget->GetDirectory(this->GetConfigName());
@@ -238,8 +314,9 @@ std::string cmNinjaTargetGenerator::GetTargetFilePath(
   const std::string& name) const
 {
   std::string path = this->GetTargetOutputDir();
-  if (path.empty() || path == ".")
+  if (path.empty() || path == ".") {
     return name;
+  }
   path += "/";
   path += name;
   return path;
@@ -300,7 +377,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   vars.RuleLauncher = "RULE_LAUNCH_COMPILE";
   vars.CMTarget = this->GetGeneratorTarget();
   vars.Language = lang.c_str();
-  vars.Source = "$in";
+  vars.Source = "$IN_ABS";
   vars.Object = "$out";
   vars.Defines = "$DEFINES";
   vars.Includes = "$INCLUDES";
@@ -309,6 +386,10 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   vars.ObjectDir = "$OBJECT_DIR";
   vars.ObjectFileDir = "$OBJECT_FILE_DIR";
 
+  // For some cases we do an explicit preprocessor invocation.
+  bool const explicitPP = this->NeedExplicitPreprocessing(lang);
+  bool const needDyndep = this->NeedDyndep(lang);
+
   cmMakefile* mf = this->GetMakefile();
 
   std::string flags = "$FLAGS";
@@ -329,7 +410,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   std::string deptype;
   std::string depfile;
   std::string cldeps;
-  if (this->NeedDepTypeMSVC(lang)) {
+  if (explicitPP) {
+    // The explicit preprocessing step will handle dependency scanning.
+  } else if (this->NeedDepTypeMSVC(lang)) {
     deptype = "msvc";
     depfile = "";
     flags += " /showIncludes";
@@ -344,7 +427,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
         : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
       cldeps = "\"";
       cldeps += cmSystemTools::GetCMClDepsCommand();
-      cldeps += "\" " + lang + " $in \"$DEP_FILE\" $out \"";
+      cldeps += "\" " + lang + " " + vars.Source + " \"$DEP_FILE\" $out \"";
       cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
       cldeps += "\" \"" + cl + "\" ";
     }
@@ -369,6 +452,109 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   vars.Flags = flags.c_str();
   vars.DependencyFile = depfile.c_str();
 
+  std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
+    ConvertToNinjaPath(this->GetTargetDependInfoPath(lang)),
+    cmLocalGenerator::SHELL);
+
+  if (explicitPP) {
+    // Lookup the explicit preprocessing rule.
+    std::string const ppVar = "CMAKE_" + lang + "_PREPROCESS_SOURCE";
+    std::string const ppCmd =
+      this->GetMakefile()->GetRequiredDefinition(ppVar);
+
+    // Explicit preprocessing always uses a depfile.
+    std::string const ppDeptype = ""; // no deps= for multiple outputs
+    std::string const ppDepfile = "$DEP_FILE";
+
+    cmLocalGenerator::RuleVariables ppVars;
+    ppVars.RuleLauncher = vars.RuleLauncher;
+    ppVars.CMTarget = vars.CMTarget;
+    ppVars.Language = vars.Language;
+    ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
+    ppVars.PreprocessedSource = "$out";
+    ppVars.DependencyFile = ppDepfile.c_str();
+
+    // Preprocessing uses the original source,
+    // compilation uses preprocessed output.
+    ppVars.Source = vars.Source;
+    vars.Source = "$in";
+
+    // Preprocessing and compilation use the same flags.
+    ppVars.Flags = vars.Flags;
+
+    // Move preprocessor definitions to the preprocessor rule.
+    ppVars.Defines = vars.Defines;
+    vars.Defines = "";
+
+    // Copy include directories to the preprocessor rule.  The Fortran
+    // compilation rule still needs them for the INCLUDE directive.
+    ppVars.Includes = vars.Includes;
+
+    // Rule for preprocessing source file.
+    std::vector<std::string> ppCmds;
+    cmSystemTools::ExpandListArgument(ppCmd, ppCmds);
+
+    for (std::vector<std::string>::iterator i = ppCmds.begin();
+         i != ppCmds.end(); ++i) {
+      this->GetLocalGenerator()->ExpandRuleVariables(*i, ppVars);
+    }
+
+    // Run CMake dependency scanner on preprocessed output.
+    std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
+      cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
+    ppCmds.push_back(
+      cmake + " -E cmake_ninja_depends"
+              " --tdi=" +
+      tdi + " --pp=$out"
+            " --dep=$DEP_FILE" +
+      (needDyndep ? " --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE" : ""));
+
+    std::string const ppCmdLine =
+      this->GetLocalGenerator()->BuildCommandLine(ppCmds);
+
+    // Write the rule for preprocessing file of the given language.
+    std::ostringstream ppComment;
+    ppComment << "Rule for preprocessing " << lang << " files.";
+    std::ostringstream ppDesc;
+    ppDesc << "Building " << lang << " preprocessed $out";
+    this->GetGlobalGenerator()->AddRule(this->LanguagePreprocessRule(lang),
+                                        ppCmdLine, ppDesc.str(),
+                                        ppComment.str(), ppDepfile, ppDeptype,
+                                        /*rspfile*/ "",
+                                        /*rspcontent*/ "",
+                                        /*restat*/ "",
+                                        /*generator*/ false);
+  }
+
+  if (needDyndep) {
+    // Write the rule for ninja dyndep file generation.
+    std::vector<std::string> ddCmds;
+
+    // Run CMake dependency scanner on preprocessed output.
+    std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
+      cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
+    ddCmds.push_back(cmake + " -E cmake_ninja_dyndep"
+                             " --tdi=" +
+                     tdi + " --dd=$out"
+                           " $in");
+
+    std::string const ddCmdLine =
+      this->GetLocalGenerator()->BuildCommandLine(ddCmds);
+
+    std::ostringstream ddComment;
+    ddComment << "Rule to generate ninja dyndep files for " << lang << ".";
+    std::ostringstream ddDesc;
+    ddDesc << "Generating " << lang << " dyndep file $out";
+    this->GetGlobalGenerator()->AddRule(
+      this->LanguageDyndepRule(lang), ddCmdLine, ddDesc.str(), ddComment.str(),
+      /*depfile*/ "",
+      /*deps*/ "",
+      /*rspfile*/ "",
+      /*rspcontent*/ "",
+      /*restat*/ "",
+      /*generator*/ false);
+  }
+
   // Rule for compiling object file.
   const std::string cmdVar = std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
   std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
@@ -421,8 +607,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   }
 
   for (std::vector<std::string>::iterator i = compileCmds.begin();
-       i != compileCmds.end(); ++i)
+       i != compileCmds.end(); ++i) {
     this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
+  }
 
   std::string cmdLine =
     this->GetLocalGenerator()->BuildCommandLine(compileCmds);
@@ -481,6 +668,10 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
   this->GetLocalGenerator()->AppendTargetDepends(this->GeneratorTarget,
                                                  orderOnlyDeps);
 
+  // Add order-only dependencies on other files associated with the target.
+  orderOnlyDeps.insert(orderOnlyDeps.end(), this->ExtraFiles.begin(),
+                       this->ExtraFiles.end());
+
   // Add order-only dependencies on custom command outputs.
   for (std::vector<cmCustomCommand const*>::const_iterator cci =
          this->CustomCommands.begin();
@@ -512,6 +703,25 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
     this->WriteObjectBuildStatement(*si, !orderOnlyDeps.empty());
   }
 
+  if (!this->DDIFiles.empty()) {
+    std::string const ddComment;
+    std::string const ddRule = this->LanguageDyndepRule("Fortran");
+    cmNinjaDeps ddOutputs;
+    cmNinjaDeps ddImplicitOuts;
+    cmNinjaDeps const& ddExplicitDeps = this->DDIFiles;
+    cmNinjaDeps ddImplicitDeps;
+    cmNinjaDeps ddOrderOnlyDeps;
+    cmNinjaVars ddVars;
+
+    this->WriteTargetDependInfo("Fortran");
+
+    ddOutputs.push_back(this->GetDyndepFilePath("Fortran"));
+
+    this->GetGlobalGenerator()->WriteBuild(
+      this->GetBuildFileStream(), ddComment, ddRule, ddOutputs, ddImplicitOuts,
+      ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
+  }
+
   this->GetBuildFileStream() << "\n";
 }
 
@@ -519,8 +729,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
   cmSourceFile const* source, bool writeOrderDependsTargetForTarget)
 {
   std::string const language = source->GetLanguage();
-  std::string const sourceFileName =
-    language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
+  std::string const sourceFileName = this->GetSourceFilePath(source);
   std::string const objectDir =
     this->ConvertToNinjaPath(this->GeneratorTarget->GetSupportDirectory());
   std::string const objectFileName =
@@ -529,6 +738,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
     cmSystemTools::GetFilenamePath(objectFileName);
 
   cmNinjaVars vars;
+  vars["IN_ABS"] = this->GetLocalGenerator()->ConvertToOutputFormat(
+    source->GetFullPath(), cmOutputConverter::SHELL);
   vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
   vars["DEFINES"] = this->ComputeDefines(source, language);
   vars["INCLUDES"] = this->GetIncludes(language);
@@ -581,6 +792,89 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
                                                              orderOnlyDeps);
   }
 
+  // For some cases we need to generate a ninja dyndep file.
+  bool const needDyndep = this->NeedDyndep(language);
+
+  // For some cases we do an explicit preprocessor invocation.
+  bool const explicitPP = this->NeedExplicitPreprocessing(language);
+  if (explicitPP) {
+    std::string const ppComment;
+    std::string const ppRule = this->LanguagePreprocessRule(language);
+    cmNinjaDeps ppOutputs;
+    cmNinjaDeps ppImplicitOuts;
+    cmNinjaDeps ppExplicitDeps;
+    cmNinjaDeps ppImplicitDeps;
+    cmNinjaDeps ppOrderOnlyDeps;
+    cmNinjaVars ppVars;
+
+    std::string const ppFileName =
+      this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source));
+    ppOutputs.push_back(ppFileName);
+
+    // Move compilation dependencies to the preprocessing build statement.
+    std::swap(ppExplicitDeps, explicitDeps);
+    std::swap(ppImplicitDeps, implicitDeps);
+    std::swap(ppOrderOnlyDeps, orderOnlyDeps);
+    std::swap(ppVars["IN_ABS"], vars["IN_ABS"]);
+
+    // The actual compilation will now use the preprocessed source.
+    explicitDeps.push_back(ppFileName);
+
+    // Preprocessing and compilation use the same flags.
+    ppVars["FLAGS"] = vars["FLAGS"];
+
+    // Move preprocessor definitions to the preprocessor build statement.
+    std::swap(ppVars["DEFINES"], vars["DEFINES"]);
+
+    // Copy include directories to the preprocessor build statement.  The
+    // Fortran compilation build statement still needs them for the INCLUDE
+    // directive.
+    ppVars["INCLUDES"] = vars["INCLUDES"];
+
+    // Prepend source file's original directory as an include directory
+    // so e.g. Fortran INCLUDE statements can look for files in it.
+    std::vector<std::string> sourceDirectory;
+    sourceDirectory.push_back(
+      cmSystemTools::GetParentDirectory(source->GetFullPath()));
+
+    std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
+      sourceDirectory, this->GeneratorTarget, language, false, false,
+      this->GetConfigName());
+
+    vars["INCLUDES"] = sourceDirectoryFlag + " " + vars["INCLUDES"];
+
+    // Explicit preprocessing always uses a depfile.
+    ppVars["DEP_FILE"] =
+      cmGlobalNinjaGenerator::EncodeDepfileSpace(ppFileName + ".d");
+    // The actual compilation does not need a depfile because it
+    // depends on the already-preprocessed source.
+    vars.erase("DEP_FILE");
+
+    if (needDyndep) {
+      // Tell dependency scanner the object file that will result from
+      // compiling the preprocessed source.
+      ppVars["OBJ_FILE"] = objectFileName;
+
+      // Tell dependency scanner where to store dyndep intermediate results.
+      std::string const ddiFile = ppFileName + ".ddi";
+      ppVars["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
+      ppImplicitOuts.push_back(ddiFile);
+      this->DDIFiles.push_back(ddiFile);
+    }
+
+    this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
+                               ppVars);
+
+    this->GetGlobalGenerator()->WriteBuild(
+      this->GetBuildFileStream(), ppComment, ppRule, ppOutputs, ppImplicitOuts,
+      ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars);
+  }
+  if (needDyndep) {
+    std::string const dyndep = this->GetDyndepFilePath(language);
+    orderOnlyDeps.push_back(dyndep);
+    vars["dyndep"] = dyndep;
+  }
+
   EnsureParentDirectoryExists(objectFileName);
 
   vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
@@ -599,8 +893,9 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
   std::string const rspfile = objectFileName + ".rsp";
 
   this->GetGlobalGenerator()->WriteBuild(
-    this->GetBuildFileStream(), comment, rule, outputs, explicitDeps,
-    implicitDeps, orderOnlyDeps, vars, rspfile, commandLineLengthLimit);
+    this->GetBuildFileStream(), comment, rule, outputs,
+    /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, orderOnlyDeps,
+    vars, rspfile, commandLineLengthLimit);
 
   if (const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
     std::vector<std::string> outputList;
@@ -613,6 +908,49 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
   }
 }
 
+void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
+{
+  Json::Value tdi(Json::objectValue);
+  tdi["language"] = lang;
+  tdi["compiler-id"] =
+    this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID");
+
+  if (lang == "Fortran") {
+    std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
+      this->Makefile->GetHomeOutputDirectory());
+    if (mod_dir.empty()) {
+      mod_dir = this->Makefile->GetCurrentBinaryDirectory();
+    }
+    tdi["module-dir"] = mod_dir;
+  }
+
+  tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
+  tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
+  tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
+  tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
+
+  Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
+  std::vector<std::string> includes;
+  this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
+                                              lang, this->GetConfigName());
+  for (std::vector<std::string>::iterator i = includes.begin();
+       i != includes.end(); ++i) {
+    tdi_include_dirs.append(*i);
+  }
+
+  Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
+    Json::arrayValue;
+  std::vector<std::string> linked = this->GetLinkedTargetDirectories();
+  for (std::vector<std::string>::iterator i = linked.begin();
+       i != linked.end(); ++i) {
+    tdi_linked_target_dirs.append(*i);
+  }
+
+  std::string const tdin = this->GetTargetDependInfoPath(lang);
+  cmGeneratedFileStream tdif(tdin.c_str());
+  tdif << tdi;
+}
+
 void cmNinjaTargetGenerator::ExportObjectCompileCommand(
   std::string const& language, std::string const& sourceFileName,
   std::string const& objectDir, std::string const& objectFileName,
@@ -656,8 +994,9 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand(
   cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
 
   for (std::vector<std::string>::iterator i = compileCmds.begin();
-       i != compileCmds.end(); ++i)
+       i != compileCmds.end(); ++i) {
     this->GetLocalGenerator()->ExpandRuleVariables(*i, compileObjectVars);
+  }
 
   std::string cmdLine =
     this->GetLocalGenerator()->BuildCommandLine(compileCmds);
@@ -712,8 +1051,8 @@ void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
   this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(input,
                                                                  output);
 
-  // Add as a dependency of all target so that it gets called.
-  this->Generator->GetGlobalGenerator()->AddDependencyToAll(output);
+  // Add as a dependency to the target so that it gets called.
+  this->Generator->ExtraFiles.push_back(output);
 }
 
 void cmNinjaTargetGenerator::addPoolNinjaVariable(
@@ -730,5 +1069,5 @@ bool cmNinjaTargetGenerator::ForceResponseFile()
 {
   static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
   return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
-          cmSystemTools::GetEnv(forceRspFile) != 0);
+          cmSystemTools::HasEnv(forceRspFile));
 }
diff --git a/Source/cmNinjaTargetGenerator.h b/Source/cmNinjaTargetGenerator.h
index 414aa09..7aba66b 100644
--- a/Source/cmNinjaTargetGenerator.h
+++ b/Source/cmNinjaTargetGenerator.h
@@ -1,31 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmNinjaTargetGenerator_h
 #define cmNinjaTargetGenerator_h
 
-#include "cmCommonTargetGenerator.h"
+#include <cmConfigure.h>
 
+#include "cmCommonTargetGenerator.h"
 #include "cmGlobalNinjaGenerator.h"
-#include "cmLocalNinjaGenerator.h"
 #include "cmNinjaTypes.h"
 #include "cmOSXBundleGenerator.h"
 
-class cmTarget;
+#include <set>
+#include <string>
+#include <vector>
+
+class cmCustomCommand;
 class cmGeneratedFileStream;
 class cmGeneratorTarget;
+class cmLocalNinjaGenerator;
 class cmMakefile;
 class cmSourceFile;
-class cmCustomCommand;
 
 class cmNinjaTargetGenerator : public cmCommonTargetGenerator
 {
@@ -37,7 +31,7 @@ public:
   cmNinjaTargetGenerator(cmGeneratorTarget* target);
 
   /// Destructor.
-  virtual ~cmNinjaTargetGenerator();
+  ~cmNinjaTargetGenerator() CM_OVERRIDE;
 
   virtual void Generate() = 0;
 
@@ -66,6 +60,10 @@ protected:
   cmMakefile* GetMakefile() const { return this->Makefile; }
 
   std::string LanguageCompilerRule(const std::string& lang) const;
+  std::string LanguagePreprocessRule(std::string const& lang) const;
+  bool NeedExplicitPreprocessing(std::string const& lang) const;
+  std::string LanguageDyndepRule(std::string const& lang) const;
+  bool NeedDyndep(std::string const& lang) const;
 
   std::string OrderDependsTargetForTarget();
 
@@ -79,7 +77,8 @@ protected:
   std::string ComputeFlagsForObject(cmSourceFile const* source,
                                     const std::string& language);
 
-  void AddIncludeFlags(std::string& flags, std::string const& lang);
+  void AddIncludeFlags(std::string& flags,
+                       std::string const& lang) CM_OVERRIDE;
 
   std::string ComputeDefines(cmSourceFile const* source,
                              const std::string& language);
@@ -102,6 +101,15 @@ protected:
   /// @return the object file path for the given @a source.
   std::string GetObjectFilePath(cmSourceFile const* source) const;
 
+  /// @return the preprocessed source file path for the given @a source.
+  std::string GetPreprocessedFilePath(cmSourceFile const* source) const;
+
+  /// @return the dyndep file path for this target.
+  std::string GetDyndepFilePath(std::string const& lang) const;
+
+  /// @return the target dependency scanner info file path
+  std::string GetTargetDependInfoPath(std::string const& lang) const;
+
   /// @return the file path where the target named @a name is generated.
   std::string GetTargetFilePath(const std::string& name) const;
 
@@ -113,6 +121,7 @@ protected:
   void WriteObjectBuildStatements();
   void WriteObjectBuildStatement(cmSourceFile const* source,
                                  bool writeOrderDependsTargetForTarget);
+  void WriteTargetDependInfo(std::string const& lang);
 
   void ExportObjectCompileCommand(
     std::string const& language, std::string const& sourceFileName,
@@ -134,7 +143,8 @@ protected:
     {
     }
 
-    void operator()(cmSourceFile const& source, const char* pkgloc);
+    void operator()(cmSourceFile const& source,
+                    const char* pkgloc) CM_OVERRIDE;
 
   private:
     cmNinjaTargetGenerator* Generator;
@@ -155,7 +165,9 @@ private:
   cmLocalNinjaGenerator* LocalGenerator;
   /// List of object files for this target.
   cmNinjaDeps Objects;
+  cmNinjaDeps DDIFiles; // TODO: Make per-language.
   std::vector<cmCustomCommand const*> CustomCommands;
+  cmNinjaDeps ExtraFiles;
 };
 
 #endif // ! cmNinjaTargetGenerator_h
diff --git a/Source/cmNinjaTypes.h b/Source/cmNinjaTypes.h
index 82a5220..b4eaa59 100644
--- a/Source/cmNinjaTypes.h
+++ b/Source/cmNinjaTypes.h
@@ -1,18 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmNinjaTypes_h
 #define cmNinjaTypes_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 typedef std::vector<std::string> cmNinjaDeps;
diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx
index f7a7f38..17e35e5 100644
--- a/Source/cmNinjaUtilityTargetGenerator.cxx
+++ b/Source/cmNinjaUtilityTargetGenerator.cxx
@@ -1,23 +1,25 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNinjaUtilityTargetGenerator.h"
 
 #include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalNinjaGenerator.h"
+#include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
+#include "cmNinjaTypes.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include <algorithm>
+#include <iterator>
+#include <string>
+#include <vector>
 
 cmNinjaUtilityTargetGenerator::cmNinjaUtilityTargetGenerator(
   cmGeneratorTarget* target)
@@ -31,10 +33,12 @@ cmNinjaUtilityTargetGenerator::~cmNinjaUtilityTargetGenerator()
 
 void cmNinjaUtilityTargetGenerator::Generate()
 {
-  std::string utilCommandName = cmake::GetCMakeFilesDirectoryPostSlash();
+  std::string utilCommandName =
+    this->GetLocalGenerator()->GetCurrentBinaryDirectory();
+  utilCommandName += cmake::GetCMakeFilesDirectory();
+  utilCommandName += "/";
   utilCommandName += this->GetTargetName() + ".util";
-  utilCommandName =
-    this->GetGlobalGenerator()->NinjaOutputPath(utilCommandName);
+  utilCommandName = this->ConvertToNinjaPath(utilCommandName);
 
   std::vector<std::string> commands;
   cmNinjaDeps deps, outputs, util_outputs(1, utilCommandName);
@@ -57,8 +61,9 @@ void cmNinjaUtilityTargetGenerator::Generate()
       std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
       std::transform(ccByproducts.begin(), ccByproducts.end(),
                      std::back_inserter(util_outputs), MapToNinjaPath());
-      if (ci->GetUsesTerminal())
+      if (ci->GetUsesTerminal()) {
         uses_terminal = true;
+      }
     }
   }
 
@@ -99,10 +104,11 @@ void cmNinjaUtilityTargetGenerator::Generate()
     const char* echoStr =
       this->GetGeneratorTarget()->GetProperty("EchoString");
     std::string desc;
-    if (echoStr)
+    if (echoStr) {
       desc = echoStr;
-    else
+    } else {
       desc = "Running utility command for " + this->GetTargetName();
+    }
 
     // TODO: fix problematic global targets.  For now, search and replace the
     // makefile vars.
@@ -122,8 +128,9 @@ void cmNinjaUtilityTargetGenerator::Generate()
         .c_str());
     cmSystemTools::ReplaceString(command, "$(ARGS)", "");
 
-    if (command.find('$') != std::string::npos)
+    if (command.find('$') != std::string::npos) {
       return;
+    }
 
     for (cmNinjaDeps::const_iterator oi = util_outputs.begin(),
                                      oe = util_outputs.end();
@@ -133,7 +140,7 @@ void cmNinjaUtilityTargetGenerator::Generate()
 
     this->GetGlobalGenerator()->WriteCustomCommandBuild(
       command, desc, "Utility command for " + this->GetTargetName(),
-      uses_terminal,
+      /*depfile*/ "", uses_terminal,
       /*restat*/ true, util_outputs, deps);
 
     this->GetGlobalGenerator()->WritePhonyBuild(
@@ -141,6 +148,11 @@ void cmNinjaUtilityTargetGenerator::Generate()
       cmNinjaDeps(1, utilCommandName));
   }
 
-  this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
-                                             this->GetGeneratorTarget());
+  // Add an alias for the logical target name regardless of what directory
+  // contains it.  Skip this for GLOBAL_TARGET because they are meant to
+  // be per-directory and have one at the top-level anyway.
+  if (this->GetGeneratorTarget()->GetType() != cmState::GLOBAL_TARGET) {
+    this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
+                                               this->GetGeneratorTarget());
+  }
 }
diff --git a/Source/cmNinjaUtilityTargetGenerator.h b/Source/cmNinjaUtilityTargetGenerator.h
index fec2946..897f432 100644
--- a/Source/cmNinjaUtilityTargetGenerator.h
+++ b/Source/cmNinjaUtilityTargetGenerator.h
@@ -1,31 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2011 Peter Collingbourne <peter at pcc.me.uk>
-  Copyright 2011 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmNinjaUtilityTargetGenerator_h
 #define cmNinjaUtilityTargetGenerator_h
 
-#include "cmNinjaTargetGenerator.h"
+#include <cmConfigure.h>
 
-#include "cmNinjaTypes.h"
+#include "cmNinjaTargetGenerator.h"
 
-class cmSourceFile;
+class cmGeneratorTarget;
 
 class cmNinjaUtilityTargetGenerator : public cmNinjaTargetGenerator
 {
 public:
   cmNinjaUtilityTargetGenerator(cmGeneratorTarget* target);
-  ~cmNinjaUtilityTargetGenerator();
+  ~cmNinjaUtilityTargetGenerator() CM_OVERRIDE;
 
-  void Generate();
+  void Generate() CM_OVERRIDE;
 };
 
 #endif // ! cmNinjaUtilityTargetGenerator_h
diff --git a/Source/cmOSXBundleGenerator.cxx b/Source/cmOSXBundleGenerator.cxx
index f62ba40..8139be4 100644
--- a/Source/cmOSXBundleGenerator.cxx
+++ b/Source/cmOSXBundleGenerator.cxx
@@ -1,32 +1,30 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOSXBundleGenerator.h"
 
+#include <cmConfigure.h>
+
+#include "cmGeneratorTarget.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmTarget.h"
 
 #include <cassert>
 
+class cmSourceFile;
+
 cmOSXBundleGenerator::cmOSXBundleGenerator(cmGeneratorTarget* target,
                                            const std::string& configName)
   : GT(target)
   , Makefile(target->Target->GetMakefile())
   , LocalGenerator(target->GetLocalGenerator())
   , ConfigName(configName)
-  , MacContentFolders(0)
+  , MacContentFolders(CM_NULLPTR)
 {
-  if (this->MustSkip())
+  if (this->MustSkip()) {
     return;
+  }
 }
 
 bool cmOSXBundleGenerator::MustSkip()
@@ -37,8 +35,9 @@ bool cmOSXBundleGenerator::MustSkip()
 void cmOSXBundleGenerator::CreateAppBundle(const std::string& targetName,
                                            std::string& outpath)
 {
-  if (this->MustSkip())
+  if (this->MustSkip()) {
     return;
+  }
 
   // Compute bundle directory names.
   std::string out = outpath;
@@ -64,8 +63,9 @@ void cmOSXBundleGenerator::CreateAppBundle(const std::string& targetName,
 void cmOSXBundleGenerator::CreateFramework(const std::string& targetName,
                                            const std::string& outpath)
 {
-  if (this->MustSkip())
+  if (this->MustSkip()) {
     return;
+  }
 
   assert(this->MacContentFolders);
 
@@ -92,8 +92,9 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName,
                                                    plist.c_str());
 
   // Generate Versions directory only for MacOSX frameworks
-  if (this->Makefile->PlatformIsAppleIos())
+  if (this->Makefile->PlatformIsAppleIos()) {
     return;
+  }
 
   // TODO: Use the cmMakefileTargetGenerator::ExtraFiles vector to
   // drive rules to create these files at build time.
@@ -162,8 +163,9 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName,
 void cmOSXBundleGenerator::CreateCFBundle(const std::string& targetName,
                                           const std::string& root)
 {
-  if (this->MustSkip())
+  if (this->MustSkip()) {
     return;
+  }
 
   // Compute bundle directory names.
   std::string out = root;
@@ -186,8 +188,9 @@ void cmOSXBundleGenerator::GenerateMacOSXContentStatements(
   std::vector<cmSourceFile const*> const& sources,
   MacOSXContentGeneratorType* generator)
 {
-  if (this->MustSkip())
+  if (this->MustSkip()) {
     return;
+  }
 
   for (std::vector<cmSourceFile const*>::const_iterator si = sources.begin();
        si != sources.end(); ++si) {
diff --git a/Source/cmOSXBundleGenerator.h b/Source/cmOSXBundleGenerator.h
index 55a3c75..0a5a6c5 100644
--- a/Source/cmOSXBundleGenerator.h
+++ b/Source/cmOSXBundleGenerator.h
@@ -1,28 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Nicolas Despres <nicolas.despres at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmOSXBundleGenerator_h
 #define cmOSXBundleGenerator_h
 
-#include "cmStandardIncludes.h"
-
-#include "cmSourceFile.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <set>
 #include <string>
+#include <vector>
 
-class cmTarget;
-class cmMakefile;
-class cmLocalGenerator;
 class cmGeneratorTarget;
+class cmLocalGenerator;
+class cmMakefile;
+class cmSourceFile;
 
 class cmOSXBundleGenerator
 {
diff --git a/Source/cmObject.h b/Source/cmObject.h
index d883c52..621a06f 100644
--- a/Source/cmObject.h
+++ b/Source/cmObject.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmObject_h
 #define cmObject_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmObject
diff --git a/Source/cmOptionCommand.cxx b/Source/cmOptionCommand.cxx
index f6f0ec3..946a543 100644
--- a/Source/cmOptionCommand.cxx
+++ b/Source/cmOptionCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOptionCommand.h"
 
 // cmOptionCommand
diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h
index 491f45e..3ca62d7 100644
--- a/Source/cmOptionCommand.h
+++ b/Source/cmOptionCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmOptionCommand_h
 #define cmOptionCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmOptionCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmOptionCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "option"; }
+  std::string GetName() const CM_OVERRIDE { return "option"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmOptionCommand, cmCommand);
 };
diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx
index 00606c7..7744a5a 100644
--- a/Source/cmOrderDirectories.cxx
+++ b/Source/cmOrderDirectories.cxx
@@ -1,24 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOrderDirectories.h"
 
 #include "cmAlgorithms.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
-#include <assert.h>
-
 #include <algorithm>
+#include <assert.h>
+#include <functional>
+#include <sstream>
 
 /*
 Directory ordering computation.
@@ -157,7 +150,7 @@ public:
     }
   }
 
-  virtual void Report(std::ostream& e)
+  void Report(std::ostream& e) CM_OVERRIDE
   {
     e << "runtime library [";
     if (this->SOName.empty()) {
@@ -168,7 +161,7 @@ public:
     e << "]";
   }
 
-  virtual bool FindConflict(std::string const& dir);
+  bool FindConflict(std::string const& dir) CM_OVERRIDE;
 
 private:
   // The soname of the shared library if it is known.
@@ -212,12 +205,12 @@ public:
   {
   }
 
-  virtual void Report(std::ostream& e)
+  void Report(std::ostream& e) CM_OVERRIDE
   {
     e << "link library [" << this->FileName << "]";
   }
 
-  virtual bool FindConflict(std::string const& dir);
+  bool FindConflict(std::string const& dir) CM_OVERRIDE;
 };
 
 bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir)
diff --git a/Source/cmOrderDirectories.h b/Source/cmOrderDirectories.h
index fc1a388..90a67e7 100644
--- a/Source/cmOrderDirectories.h
+++ b/Source/cmOrderDirectories.h
@@ -1,25 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmOrderDirectories_h
 #define cmOrderDirectories_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
 
+class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmOrderDirectoriesConstraint;
-class cmOrderDirectoriesConstraintLibrary;
-class cmGeneratorTarget;
 
 /** \class cmOrderDirectories
  * \brief Compute a safe runtime path order for a set of shared libraries.
@@ -30,7 +25,8 @@ public:
   cmOrderDirectories(cmGlobalGenerator* gg, cmGeneratorTarget const* target,
                      const char* purpose);
   ~cmOrderDirectories();
-  void AddRuntimeLibrary(std::string const& fullPath, const char* soname = 0);
+  void AddRuntimeLibrary(std::string const& fullPath,
+                         const char* soname = CM_NULLPTR);
   void AddLinkLibrary(std::string const& fullPath);
   void AddUserDirectories(std::vector<std::string> const& extra);
   void AddLanguageDirectories(std::vector<std::string> const& dirs);
diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx
index 8e80bd0..2ef603b 100644
--- a/Source/cmOutputConverter.cxx
+++ b/Source/cmOutputConverter.cxx
@@ -1,23 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOutputConverter.h"
 
 #include "cmAlgorithms.h"
-#include "cmake.h"
+#include "cmSystemTools.h"
 
+#include <algorithm>
 #include <assert.h>
-
-#include <ctype.h>  /* isalpha */
-#include <string.h> /* strlen */
+#include <ctype.h>
+#include <set>
+#include <sstream>
 
 cmOutputConverter::cmOutputConverter(cmState::Snapshot snapshot)
   : StateSnapshot(snapshot)
@@ -26,14 +18,14 @@ cmOutputConverter::cmOutputConverter(cmState::Snapshot snapshot)
   assert(this->StateSnapshot.IsValid());
 }
 
-std::string cmOutputConverter::ConvertToOutputForExistingCommon(
-  const std::string& remote, std::string const& result,
-  OutputFormat format) const
+std::string cmOutputConverter::ConvertToOutputForExisting(
+  const std::string& remote, OutputFormat format) const
 {
   // If this is a windows shell, the result has a space, and the path
   // already exists, we can use a short-path to reference it without a
   // space.
-  if (this->GetState()->UseWindowsShell() && result.find(' ') != result.npos &&
+  if (this->GetState()->UseWindowsShell() &&
+      remote.find(' ') != std::string::npos &&
       cmSystemTools::FileExists(remote.c_str())) {
     std::string tmp;
     if (cmSystemTools::GetShortPath(remote, tmp)) {
@@ -41,83 +33,8 @@ std::string cmOutputConverter::ConvertToOutputForExistingCommon(
     }
   }
 
-  // Otherwise, leave it unchanged.
-  return result;
-}
-
-std::string cmOutputConverter::ConvertToOutputForExisting(
-  const std::string& remote, RelativeRoot local, OutputFormat format) const
-{
-  static_cast<void>(local);
-
-  // Perform standard conversion.
-  std::string result = this->ConvertToOutputFormat(remote, format);
-
-  // Consider short-path.
-  return this->ConvertToOutputForExistingCommon(remote, result, format);
-}
-
-std::string cmOutputConverter::ConvertToOutputForExisting(
-  RelativeRoot remote, const std::string& local, OutputFormat format) const
-{
-  // Perform standard conversion.
-  std::string result = this->Convert(remote, local, format, true);
-
-  // Consider short-path.
-  const char* remotePath = this->GetRelativeRootPath(remote);
-  return this->ConvertToOutputForExistingCommon(remotePath, result, format);
-}
-
-const char* cmOutputConverter::GetRelativeRootPath(RelativeRoot relroot) const
-{
-  switch (relroot) {
-    case HOME:
-      return this->GetState()->GetSourceDirectory();
-    case START:
-      return this->StateSnapshot.GetDirectory().GetCurrentSource();
-    case HOME_OUTPUT:
-      return this->GetState()->GetBinaryDirectory();
-    case START_OUTPUT:
-      return this->StateSnapshot.GetDirectory().GetCurrentBinary();
-    default:
-      break;
-  }
-  return 0;
-}
-
-std::string cmOutputConverter::Convert(const std::string& source,
-                                       RelativeRoot relative,
-                                       OutputFormat output) const
-{
-  // Convert the path to a relative path.
-  std::string result = source;
-
-  switch (relative) {
-    case HOME:
-      result = this->ConvertToRelativePath(
-        this->GetState()->GetSourceDirectoryComponents(), result);
-      break;
-    case START:
-      result = this->ConvertToRelativePath(
-        this->StateSnapshot.GetDirectory().GetCurrentSourceComponents(),
-        result);
-      break;
-    case HOME_OUTPUT:
-      result = this->ConvertToRelativePath(
-        this->GetState()->GetBinaryDirectoryComponents(), result);
-      break;
-    case START_OUTPUT:
-      result = this->ConvertToRelativePath(
-        this->StateSnapshot.GetDirectory().GetCurrentBinaryComponents(),
-        result);
-      break;
-    case FULL:
-      result = cmSystemTools::CollapseFullPath(result);
-      break;
-    case NONE:
-      break;
-  }
-  return this->ConvertToOutputFormat(result, output);
+  // Otherwise, perform standard conversion.
+  return this->ConvertToOutputFormat(remote, format);
 }
 
 std::string cmOutputConverter::ConvertToOutputFormat(const std::string& source,
@@ -125,9 +42,7 @@ std::string cmOutputConverter::ConvertToOutputFormat(const std::string& source,
 {
   std::string result = source;
   // Convert it to an output path.
-  if (output == MAKERULE) {
-    result = cmSystemTools::ConvertToOutputPath(result.c_str());
-  } else if (output == SHELL || output == WATCOMQUOTE) {
+  if (output == SHELL || output == WATCOMQUOTE) {
     result = this->ConvertDirectorySeparatorsForShell(source);
     result = this->EscapeForShell(result, true, false, output == WATCOMQUOTE);
   } else if (output == RESPONSE) {
@@ -155,26 +70,6 @@ std::string cmOutputConverter::ConvertDirectorySeparatorsForShell(
   return result;
 }
 
-std::string cmOutputConverter::Convert(RelativeRoot remote,
-                                       const std::string& local,
-                                       OutputFormat output,
-                                       bool optional) const
-{
-  const char* remotePath = this->GetRelativeRootPath(remote);
-
-  // The relative root must have a path (i.e. not FULL or NONE)
-  assert(remotePath != 0);
-
-  if (!local.empty() && !optional) {
-    std::vector<std::string> components;
-    cmSystemTools::SplitPath(local, components);
-    std::string result = this->ConvertToRelativePath(components, remotePath);
-    return this->ConvertToOutputFormat(result, output);
-  }
-
-  return this->ConvertToOutputFormat(remotePath, output);
-}
-
 static bool cmOutputConverterNotAbove(const char* a, const char* b)
 {
   return (cmSystemTools::ComparePath(a, b) ||
@@ -185,41 +80,67 @@ std::string cmOutputConverter::ConvertToRelativePath(
   const std::vector<std::string>& local, const std::string& in_remote,
   bool force) const
 {
-  // The path should never be quoted.
-  assert(in_remote[0] != '\"');
+  std::string local_path = cmSystemTools::JoinPath(local);
+  return force ? this->ForceToRelativePath(local_path, in_remote)
+               : this->ConvertToRelativePath(local_path, in_remote);
+}
+
+std::string cmOutputConverter::ConvertToRelativePath(
+  std::string const& local_path, std::string const& remote_path) const
+{
+  // The paths should never be quoted.
+  assert(local_path[0] != '\"');
+  assert(remote_path[0] != '\"');
 
   // The local path should never have a trailing slash.
-  assert(!local.empty() && !(local[local.size() - 1] == ""));
+  assert(local_path.empty() || local_path[local_path.size() - 1] != '/');
 
   // If the path is already relative then just return the path.
-  if (!cmSystemTools::FileIsFullPath(in_remote.c_str())) {
-    return in_remote;
-  }
-
-  if (!force) {
-    // Skip conversion if the path and local are not both in the source
-    // or both in the binary tree.
-    std::string local_path = cmSystemTools::JoinPath(local);
-    if (!((cmOutputConverterNotAbove(
-             local_path.c_str(),
-             this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()) &&
-           cmOutputConverterNotAbove(
-             in_remote.c_str(),
-             this->StateSnapshot.GetDirectory().GetRelativePathTopBinary())) ||
-          (cmOutputConverterNotAbove(
-             local_path.c_str(),
-             this->StateSnapshot.GetDirectory().GetRelativePathTopSource()) &&
-           cmOutputConverterNotAbove(in_remote.c_str(),
-                                     this->StateSnapshot.GetDirectory()
-                                       .GetRelativePathTopSource())))) {
-      return in_remote;
-    }
+  if (!cmSystemTools::FileIsFullPath(remote_path.c_str())) {
+    return remote_path;
+  }
+
+  // Skip conversion if the path and local are not both in the source
+  // or both in the binary tree.
+  if (!((cmOutputConverterNotAbove(
+           local_path.c_str(),
+           this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()) &&
+         cmOutputConverterNotAbove(
+           remote_path.c_str(),
+           this->StateSnapshot.GetDirectory().GetRelativePathTopBinary())) ||
+        (cmOutputConverterNotAbove(
+           local_path.c_str(),
+           this->StateSnapshot.GetDirectory().GetRelativePathTopSource()) &&
+         cmOutputConverterNotAbove(
+           remote_path.c_str(),
+           this->StateSnapshot.GetDirectory().GetRelativePathTopSource())))) {
+    return remote_path;
+  }
+
+  return this->ForceToRelativePath(local_path, remote_path);
+}
+
+std::string cmOutputConverter::ForceToRelativePath(
+  std::string const& local_path, std::string const& remote_path)
+{
+  // The paths should never be quoted.
+  assert(local_path[0] != '\"');
+  assert(remote_path[0] != '\"');
+
+  // The local path should never have a trailing slash.
+  assert(local_path.empty() || local_path[local_path.size() - 1] != '/');
+
+  // If the path is already relative then just return the path.
+  if (!cmSystemTools::FileIsFullPath(remote_path.c_str())) {
+    return remote_path;
   }
 
   // Identify the longest shared path component between the remote
   // path and the local path.
+  std::vector<std::string> local;
+  cmSystemTools::SplitPath(local_path, local);
   std::vector<std::string> remote;
-  cmSystemTools::SplitPath(in_remote, remote);
+  cmSystemTools::SplitPath(remote_path, remote);
   unsigned int common = 0;
   while (common < remote.size() && common < local.size() &&
          cmSystemTools::ComparePath(remote[common], local[common])) {
@@ -228,7 +149,7 @@ std::string cmOutputConverter::ConvertToRelativePath(
 
   // If no part of the path is in common then return the full path.
   if (common == 0) {
-    return in_remote;
+    return remote_path;
   }
 
   // If the entire path is in common then just return a ".".
@@ -328,19 +249,9 @@ std::string cmOutputConverter::EscapeForShell(const std::string& str,
     flags |= Shell_Flag_NMake;
   }
 
-  // Compute the buffer size needed.
-  int size = (this->GetState()->UseWindowsShell()
-                ? Shell_GetArgumentSizeForWindows(str.c_str(), flags)
-                : Shell_GetArgumentSizeForUnix(str.c_str(), flags));
-
-  // Compute the shell argument itself.
-  std::vector<char> arg(size);
-  if (this->GetState()->UseWindowsShell()) {
-    Shell_GetArgumentForWindows(str.c_str(), &arg[0], flags);
-  } else {
-    Shell_GetArgumentForUnix(str.c_str(), &arg[0], flags);
-  }
-  return std::string(&arg[0]);
+  return this->GetState()->UseWindowsShell()
+    ? Shell_GetArgumentForWindows(str.c_str(), flags)
+    : Shell_GetArgumentForUnix(str.c_str(), flags);
 }
 
 std::string cmOutputConverter::EscapeForCMake(const std::string& str)
@@ -369,18 +280,7 @@ std::string cmOutputConverter::EscapeForCMake(const std::string& str)
 std::string cmOutputConverter::EscapeWindowsShellArgument(const char* arg,
                                                           int shell_flags)
 {
-  char local_buffer[1024];
-  char* buffer = local_buffer;
-  int size = Shell_GetArgumentSizeForWindows(arg, shell_flags);
-  if (size > 1024) {
-    buffer = new char[size];
-  }
-  Shell_GetArgumentForWindows(arg, buffer, shell_flags);
-  std::string result(buffer);
-  if (buffer != local_buffer) {
-    delete[] buffer;
-  }
-  return result;
+  return Shell_GetArgumentForWindows(arg, shell_flags);
 }
 
 cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat(
@@ -586,112 +486,11 @@ int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
   return 0;
 }
 
-int cmOutputConverter::Shell__GetArgumentSize(const char* in, int isUnix,
-                                              int flags)
+std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
+                                                  int flags)
 {
-  /* Start with the length of the original argument, plus one for
-     either a terminating null or a separating space.  */
-  int size = (int)strlen(in) + 1;
-
-  /* String iterator.  */
-  const char* c;
-
-  /* Keep track of how many backslashes have been encountered in a row.  */
-  int windows_backslashes = 0;
+  std::ostringstream out;
 
-  /* Scan the string for characters that require escaping or quoting.  */
-  for (c = in; *c; ++c) {
-    /* Look for $(MAKEVAR) syntax if requested.  */
-    if (flags & Shell_Flag_AllowMakeVariables) {
-      /* Skip over the make variable references if any are present.  */
-      c = Shell__SkipMakeVariables(c);
-
-      /* Stop if we have reached the end of the string.  */
-      if (!*c) {
-        break;
-      }
-    }
-
-    /* Check whether this character needs escaping for the shell.  */
-    if (isUnix) {
-      /* On Unix a few special characters need escaping even inside a
-         quoted argument.  */
-      if (*c == '\\' || *c == '"' || *c == '`' || *c == '$') {
-        /* This character needs a backslash to escape it.  */
-        ++size;
-      }
-    } else if (flags & Shell_Flag_EchoWindows) {
-      /* On Windows the built-in command shell echo never needs escaping.  */
-    } else {
-      /* On Windows only backslashes and double-quotes need escaping.  */
-      if (*c == '\\') {
-        /* Found a backslash.  It may need to be escaped later.  */
-        ++windows_backslashes;
-      } else if (*c == '"') {
-        /* Found a double-quote.  We need to escape it and all
-           immediately preceding backslashes.  */
-        size += windows_backslashes + 1;
-        windows_backslashes = 0;
-      } else {
-        /* Found another character.  This eliminates the possibility
-           that any immediately preceding backslashes will be
-           escaped.  */
-        windows_backslashes = 0;
-      }
-    }
-
-    /* Check whether this character needs escaping for a make tool.  */
-    if (*c == '$') {
-      if (flags & Shell_Flag_Make) {
-        /* In Makefiles a dollar is written $$ so we need one extra
-           character.  */
-        ++size;
-      } else if (flags & Shell_Flag_VSIDE) {
-        /* In a VS IDE a dollar is written "$" so we need two extra
-           characters.  */
-        size += 2;
-      }
-    } else if (*c == '#') {
-      if ((flags & Shell_Flag_Make) && (flags & Shell_Flag_WatcomWMake)) {
-        /* In Watcom WMake makefiles a pound is written $# so we need
-           one extra character.  */
-        ++size;
-      }
-    } else if (*c == '%') {
-      if ((flags & Shell_Flag_VSIDE) ||
-          ((flags & Shell_Flag_Make) &&
-           ((flags & Shell_Flag_MinGWMake) || (flags & Shell_Flag_NMake)))) {
-        /* In the VS IDE, NMake, or MinGW make a percent is written %%
-           so we need one extra characters.  */
-        size += 1;
-      }
-    } else if (*c == ';') {
-      if (flags & Shell_Flag_VSIDE) {
-        /* In a VS IDE a semicolon is written ";" so we need two extra
-           characters.  */
-        size += 2;
-      }
-    }
-  }
-
-  /* Check whether the argument needs surrounding quotes.  */
-  if (Shell__ArgumentNeedsQuotes(in, isUnix, flags)) {
-    /* Surrounding quotes are needed.  Allocate space for them.  */
-    if ((flags & Shell_Flag_WatcomQuote) && (isUnix)) {
-      size += 2;
-    }
-    size += 2;
-
-    /* We must escape all ending backslashes when quoting on windows.  */
-    size += windows_backslashes;
-  }
-
-  return size;
-}
-
-char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
-                                            int isUnix, int flags)
-{
   /* String iterator.  */
   const char* c;
 
@@ -704,11 +503,11 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
     /* Add the opening quote for this argument.  */
     if (flags & Shell_Flag_WatcomQuote) {
       if (isUnix) {
-        *out++ = '"';
+        out << '"';
       }
-      *out++ = '\'';
+      out << '\'';
     } else {
-      *out++ = '"';
+      out << '"';
     }
   }
 
@@ -720,7 +519,7 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
       if (skip != c) {
         /* Copy to the end of the make variable references.  */
         while (c != skip) {
-          *out++ = *c++;
+          out << *c++;
         }
 
         /* The make variable reference eliminates any escaping needed
@@ -740,7 +539,7 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
          quoted argument.  */
       if (*c == '\\' || *c == '"' || *c == '`' || *c == '$') {
         /* This character needs a backslash to escape it.  */
-        *out++ = '\\';
+        out << '\\';
       }
     } else if (flags & Shell_Flag_EchoWindows) {
       /* On Windows the built-in command shell echo never needs escaping.  */
@@ -754,11 +553,11 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
            backslashes.  */
         while (windows_backslashes > 0) {
           --windows_backslashes;
-          *out++ = '\\';
+          out << '\\';
         }
 
         /* Add the backslash to escape the double-quote.  */
-        *out++ = '\\';
+        out << '\\';
       } else {
         /* We encountered a normal character.  This eliminates any
            escaping needed for preceding backslashes.  */
@@ -771,8 +570,7 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
       if (flags & Shell_Flag_Make) {
         /* In Makefiles a dollar is written $$.  The make tool will
            replace it with just $ before passing it to the shell.  */
-        *out++ = '$';
-        *out++ = '$';
+        out << "$$";
       } else if (flags & Shell_Flag_VSIDE) {
         /* In a VS IDE a dollar is written "$".  If this is written in
            an un-quoted argument it starts a quoted segment, inserts
@@ -780,34 +578,30 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
            argument it ends quoting, inserts the $ and restarts
            quoting.  Either way the $ is isolated from surrounding
            text to avoid looking like a variable reference.  */
-        *out++ = '"';
-        *out++ = '$';
-        *out++ = '"';
+        out << "\"$\"";
       } else {
         /* Otherwise a dollar is written just $. */
-        *out++ = '$';
+        out << '$';
       }
     } else if (*c == '#') {
       if ((flags & Shell_Flag_Make) && (flags & Shell_Flag_WatcomWMake)) {
         /* In Watcom WMake makefiles a pound is written $#.  The make
            tool will replace it with just # before passing it to the
            shell.  */
-        *out++ = '$';
-        *out++ = '#';
+        out << "$#";
       } else {
         /* Otherwise a pound is written just #. */
-        *out++ = '#';
+        out << '#';
       }
     } else if (*c == '%') {
       if ((flags & Shell_Flag_VSIDE) ||
           ((flags & Shell_Flag_Make) &&
            ((flags & Shell_Flag_MinGWMake) || (flags & Shell_Flag_NMake)))) {
         /* In the VS IDE, NMake, or MinGW make a percent is written %%.  */
-        *out++ = '%';
-        *out++ = '%';
+        out << "%%";
       } else {
         /* Otherwise a percent is written just %. */
-        *out++ = '%';
+        out << '%';
       }
     } else if (*c == ';') {
       if (flags & Shell_Flag_VSIDE) {
@@ -816,16 +610,14 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
            inserts the ; and ends the segment.  If it is written in a
            quoted argument it ends quoting, inserts the ; and restarts
            quoting.  Either way the ; is isolated.  */
-        *out++ = '"';
-        *out++ = ';';
-        *out++ = '"';
+        out << "\";\"";
       } else {
         /* Otherwise a semicolon is written just ;. */
-        *out++ = ';';
+        out << ';';
       }
     } else {
       /* Store this character.  */
-      *out++ = *c;
+      out << *c;
     }
   }
 
@@ -833,45 +625,31 @@ char* cmOutputConverter::Shell__GetArgument(const char* in, char* out,
     /* Add enough backslashes to escape any trailing ones.  */
     while (windows_backslashes > 0) {
       --windows_backslashes;
-      *out++ = '\\';
+      out << '\\';
     }
 
     /* Add the closing quote for this argument.  */
     if (flags & Shell_Flag_WatcomQuote) {
-      *out++ = '\'';
+      out << '\'';
       if (isUnix) {
-        *out++ = '"';
+        out << '"';
       }
     } else {
-      *out++ = '"';
+      out << '"';
     }
   }
 
-  /* Store a terminating null without incrementing.  */
-  *out = 0;
-
-  return out;
-}
-
-char* cmOutputConverter::Shell_GetArgumentForWindows(const char* in, char* out,
-                                                     int flags)
-{
-  return Shell__GetArgument(in, out, 0, flags);
-}
-
-char* cmOutputConverter::Shell_GetArgumentForUnix(const char* in, char* out,
-                                                  int flags)
-{
-  return Shell__GetArgument(in, out, 1, flags);
+  return out.str();
 }
 
-int cmOutputConverter::Shell_GetArgumentSizeForWindows(const char* in,
-                                                       int flags)
+std::string cmOutputConverter::Shell_GetArgumentForWindows(const char* in,
+                                                           int flags)
 {
-  return Shell__GetArgumentSize(in, 0, flags);
+  return Shell__GetArgument(in, 0, flags);
 }
 
-int cmOutputConverter::Shell_GetArgumentSizeForUnix(const char* in, int flags)
+std::string cmOutputConverter::Shell_GetArgumentForUnix(const char* in,
+                                                        int flags)
 {
-  return Shell__GetArgumentSize(in, 1, flags);
+  return Shell__GetArgument(in, 1, flags);
 }
diff --git a/Source/cmOutputConverter.h b/Source/cmOutputConverter.h
index 75d6326..5979eaa 100644
--- a/Source/cmOutputConverter.h
+++ b/Source/cmOutputConverter.h
@@ -1,82 +1,33 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmOutputConverter_h
 #define cmOutputConverter_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmGlobalGenerator.h"
 #include "cmState.h"
 
+#include <string>
+#include <vector>
+
 class cmOutputConverter
 {
 public:
   cmOutputConverter(cmState::Snapshot snapshot);
 
-  /**
-   * Convert something to something else. This is a centralized conversion
-   * routine used by the generators to handle relative paths and the like.
-   * The flags determine what is actually done.
-   *
-   * relative: treat the argument as a directory and convert it to make it
-   * relative or full or unchanged. If relative (HOME, START etc) then that
-   * specifies what it should be relative to.
-   *
-   * output: make the result suitable for output to a...
-   *
-   * optional: should any relative path operation be controlled by the rel
-   * path setting
-   */
-  enum RelativeRoot
-  {
-    NONE,
-    FULL,
-    HOME,
-    START,
-    HOME_OUTPUT,
-    START_OUTPUT
-  };
   enum OutputFormat
   {
-    UNCHANGED,
-    MAKERULE,
     SHELL,
     WATCOMQUOTE,
     RESPONSE
   };
   std::string ConvertToOutputFormat(const std::string& source,
                                     OutputFormat output) const;
-  std::string Convert(const std::string& remote, RelativeRoot local,
-                      OutputFormat output = UNCHANGED) const;
-  std::string Convert(RelativeRoot remote, const std::string& local,
-                      OutputFormat output = UNCHANGED,
-                      bool optional = false) const;
   std::string ConvertDirectorySeparatorsForShell(
     const std::string& source) const;
 
-  /**
-    * Get path for the specified relative root.
-    */
-  const char* GetRelativeRootPath(RelativeRoot relroot) const;
-
   ///! for existing files convert to output path and short path if spaces
   std::string ConvertToOutputForExisting(const std::string& remote,
-                                         RelativeRoot local = START_OUTPUT,
-                                         OutputFormat format = SHELL) const;
-
-  /** For existing path identified by RelativeRoot convert to output
-      path and short path if spaces.  */
-  std::string ConvertToOutputForExisting(RelativeRoot remote,
-                                         const std::string& local = "",
                                          OutputFormat format = SHELL) const;
 
   void SetLinkScriptShell(bool linkScriptShell);
@@ -126,17 +77,8 @@ public:
    * modify the generated quoting and escape sequences to work under
    * alternative environments.
    */
-  static char* Shell_GetArgumentForWindows(const char* in, char* out,
-                                           int flags);
-  static char* Shell_GetArgumentForUnix(const char* in, char* out, int flags);
-
-  /**
-   * Compute the size of the buffer required to store the output from
-   * Shell_GetArgumentForWindows or Shell_GetArgumentForUnix.  The flags
-   * passed must be identical between the two calls.
-   */
-  static int Shell_GetArgumentSizeForWindows(const char* in, int flags);
-  static int Shell_GetArgumentSizeForUnix(const char* in, int flags);
+  static std::string Shell_GetArgumentForWindows(const char* in, int flags);
+  static std::string Shell_GetArgumentForUnix(const char* in, int flags);
 
   std::string EscapeForShell(const std::string& str, bool makeVars = false,
                              bool forEcho = false,
@@ -168,13 +110,27 @@ public:
                                     const std::string& in_remote,
                                     bool force = false) const;
 
+  /**
+   * Convert the given remote path to a relative path with respect to
+   * the given local path.  Both paths must use forward slashes and not
+   * already be escaped or quoted.
+   * The conversion is skipped if the paths are not both in the source
+   * or both in the binary tree.
+   */
+  std::string ConvertToRelativePath(std::string const& local_path,
+                                    std::string const& remote_path) const;
+
+  /**
+   * Convert the given remote path to a relative path with respect to
+   * the given local path.  Both paths must use forward slashes and not
+   * already be escaped or quoted.
+   */
+  static std::string ForceToRelativePath(std::string const& local_path,
+                                         std::string const& remote_path);
+
 private:
   cmState* GetState() const;
 
-  std::string ConvertToOutputForExistingCommon(const std::string& remote,
-                                               std::string const& result,
-                                               OutputFormat format) const;
-
   static int Shell__CharIsWhitespace(char c);
   static int Shell__CharNeedsQuotesOnUnix(char c);
   static int Shell__CharNeedsQuotesOnWindows(char c);
@@ -182,9 +138,7 @@ private:
   static int Shell__CharIsMakeVariableName(char c);
   static const char* Shell__SkipMakeVariables(const char* c);
   static int Shell__ArgumentNeedsQuotes(const char* in, int isUnix, int flags);
-  static int Shell__GetArgumentSize(const char* in, int isUnix, int flags);
-  static char* Shell__GetArgument(const char* in, char* out, int isUnix,
-                                  int flags);
+  static std::string Shell__GetArgument(const char* in, int isUnix, int flags);
 
 private:
   cmState::Snapshot StateSnapshot;
diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx
index 29f1acc..8b629fe 100644
--- a/Source/cmOutputRequiredFilesCommand.cxx
+++ b/Source/cmOutputRequiredFilesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOutputRequiredFilesCommand.h"
 
 #include "cmAlgorithms.h"
@@ -28,7 +19,7 @@ public:
    */
   cmDependInformation()
     : DependDone(false)
-    , SourceFile(0)
+    , SourceFile(CM_NULLPTR)
   {
   }
 
@@ -154,7 +145,7 @@ public:
    */
   const cmDependInformation* FindDependencies(const char* file)
   {
-    cmDependInformation* info = this->GetDependInformation(file, 0);
+    cmDependInformation* info = this->GetDependInformation(file, CM_NULLPTR);
     this->GenerateDependInformation(info);
     return info;
   }
@@ -203,7 +194,7 @@ protected:
             message += includeFile;
             message += " for file ";
             message += info->FullPath.c_str();
-            cmSystemTools::Error(message.c_str(), 0);
+            cmSystemTools::Error(message.c_str(), CM_NULLPTR);
           }
           continue;
         }
@@ -307,10 +298,10 @@ protected:
     // If dependencies are already done, stop now.
     if (info->DependDone) {
       return;
-    } else {
-      // Make sure we don't visit the same file more than once.
-      info->DependDone = true;
     }
+    // Make sure we don't visit the same file more than once.
+    info->DependDone = true;
+
     const char* path = info->FullPath.c_str();
     if (!path) {
       cmSystemTools::Error(
@@ -329,7 +320,7 @@ protected:
 
     // See if the cmSourceFile for it has any files specified as
     // dependency hints.
-    if (info->SourceFile != 0) {
+    if (info->SourceFile != CM_NULLPTR) {
 
       // Get the cmSourceFile corresponding to this.
       const cmSourceFile& cFile = *(info->SourceFile);
@@ -405,15 +396,14 @@ protected:
     if (result != this->DependInformationMap.end()) {
       // Found an instance, return it.
       return result->second;
-    } else {
-      // Didn't find an instance.  Create a new one and save it.
-      cmDependInformation* info = new cmDependInformation;
-      info->FullPath = fullPath;
-      info->PathOnly = cmSystemTools::GetFilenamePath(fullPath);
-      info->IncludeName = file;
-      this->DependInformationMap[fullPath] = info;
-      return info;
     }
+    // Didn't find an instance.  Create a new one and save it.
+    cmDependInformation* info = new cmDependInformation;
+    info->FullPath = fullPath;
+    info->PathOnly = cmSystemTools::GetFilenamePath(fullPath);
+    info->IncludeName = file;
+    this->DependInformationMap[fullPath] = info;
+    return info;
   }
 
   /**
diff --git a/Source/cmOutputRequiredFilesCommand.h b/Source/cmOutputRequiredFilesCommand.h
index 7a6f5a6..7a81a76 100644
--- a/Source/cmOutputRequiredFilesCommand.h
+++ b/Source/cmOutputRequiredFilesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmOutputRequiredFilesCommand_h
 #define cmOutputRequiredFilesCommand_h
 
@@ -20,10 +11,10 @@ class cmOutputRequiredFilesCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmOutputRequiredFilesCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmOutputRequiredFilesCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "output_required_files"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmOutputRequiredFilesCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "output_required_files"; }
 
   void ListDependencies(cmDependInformation const* info, FILE* fout,
                         std::set<cmDependInformation const*>* visited);
diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx
index 8f524ec..55d71ea 100644
--- a/Source/cmParseArgumentsCommand.cxx
+++ b/Source/cmParseArgumentsCommand.cxx
@@ -1,25 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Matthias Maennich <matthias at maennich.net>
-  Copyright 2010 Alexander Neundorf <neundorf at kde.org>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmParseArgumentsCommand.h"
 
 #include "cmAlgorithms.h"
 
+static std::string escape_arg(const std::string& arg)
+{
+  // replace ";" with "\;" so output argument lists will split correctly
+  std::string escapedArg;
+  for (size_t i = 0; i < arg.size(); ++i) {
+    if (arg[i] == ';') {
+      escapedArg += '\\';
+    }
+    escapedArg += arg[i];
+  }
+  return escapedArg;
+}
+
 bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
   // cmake_parse_arguments(prefix options single multi <ARGN>)
   //                         1       2      3      4
+  // or
+  // cmake_parse_arguments(PARSE_ARGV N prefix options single multi)
   if (args.size() < 4) {
     this->SetError("must be called with at least 4 arguments.");
     return false;
@@ -27,6 +31,27 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
 
   std::vector<std::string>::const_iterator argIter = args.begin(),
                                            argEnd = args.end();
+  bool parseFromArgV = false;
+  unsigned long argvStart = 0;
+  if (*argIter == "PARSE_ARGV") {
+    if (args.size() != 6) {
+      this->Makefile->IssueMessage(
+        cmake::FATAL_ERROR,
+        "PARSE_ARGV must be called with exactly 6 arguments.");
+      cmSystemTools::SetFatalErrorOccured();
+      return true;
+    }
+    parseFromArgV = true;
+    argIter++; // move past PARSE_ARGV
+    if (!cmSystemTools::StringToULong(argIter->c_str(), &argvStart)) {
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR, "PARSE_ARGV index '" +
+                                     *argIter +
+                                     "' is not an unsigned integer");
+      cmSystemTools::SetFatalErrorOccured();
+      return true;
+    }
+    argIter++; // move past N
+  }
   // the first argument is the prefix
   const std::string prefix = (*argIter++) + "_";
 
@@ -90,11 +115,37 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
   } insideValues = NONE;
   std::string currentArgName;
 
-  // Flatten ;-lists in the arguments into a single list as was done
-  // by the original function(CMAKE_PARSE_ARGUMENTS).
   list.clear();
-  for (; argIter != argEnd; ++argIter) {
-    cmSystemTools::ExpandListArgument(*argIter, list);
+  if (!parseFromArgV) {
+    // Flatten ;-lists in the arguments into a single list as was done
+    // by the original function(CMAKE_PARSE_ARGUMENTS).
+    for (; argIter != argEnd; ++argIter) {
+      cmSystemTools::ExpandListArgument(*argIter, list);
+    }
+  } else {
+    // in the PARSE_ARGV move read the arguments from ARGC and ARGV#
+    std::string argc = this->Makefile->GetSafeDefinition("ARGC");
+    unsigned long count;
+    if (!cmSystemTools::StringToULong(argc.c_str(), &count)) {
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR,
+                                   "PARSE_ARGV called with ARGC='" + argc +
+                                     "' that is not an unsigned integer");
+      cmSystemTools::SetFatalErrorOccured();
+      return true;
+    }
+    for (unsigned long i = argvStart; i < count; ++i) {
+      std::ostringstream argName;
+      argName << "ARGV" << i;
+      const char* arg = this->Makefile->GetDefinition(argName.str());
+      if (!arg) {
+        this->Makefile->IssueMessage(cmake::FATAL_ERROR,
+                                     "PARSE_ARGV called with " +
+                                       argName.str() + " not set");
+        cmSystemTools::SetFatalErrorOccured();
+        return true;
+      }
+      list.push_back(arg);
+    }
   }
 
   // iterate over the arguments list and fill in the values where applicable
@@ -127,10 +178,18 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
         insideValues = NONE;
         break;
       case MULTI:
-        multi[currentArgName].push_back(*argIter);
+        if (parseFromArgV) {
+          multi[currentArgName].push_back(escape_arg(*argIter));
+        } else {
+          multi[currentArgName].push_back(*argIter);
+        }
         break;
       default:
-        unparsed.push_back(*argIter);
+        if (parseFromArgV) {
+          unparsed.push_back(escape_arg(*argIter));
+        } else {
+          unparsed.push_back(*argIter);
+        }
         break;
     }
   }
diff --git a/Source/cmParseArgumentsCommand.h b/Source/cmParseArgumentsCommand.h
index 46d9daa..fbeb3df 100644
--- a/Source/cmParseArgumentsCommand.h
+++ b/Source/cmParseArgumentsCommand.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Matthias Maennich <matthias at maennich.net>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmParseArgumentsCommand_h
 #define cmParseArgumentsCommand_h
 
@@ -24,24 +14,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmParseArgumentsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmParseArgumentsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "cmake_parse_arguments"; }
+  std::string GetName() const CM_OVERRIDE { return "cmake_parse_arguments"; }
 
   cmTypeMacro(cmParseArgumentsCommand, cmCommand);
 };
diff --git a/Source/cmPathLabel.cxx b/Source/cmPathLabel.cxx
index 491d2f0..19e6820 100644
--- a/Source/cmPathLabel.cxx
+++ b/Source/cmPathLabel.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmPathLabel.h"
 
 cmPathLabel::cmPathLabel(const std::string& label)
diff --git a/Source/cmPathLabel.h b/Source/cmPathLabel.h
index 39fbec3..5e9e423 100644
--- a/Source/cmPathLabel.h
+++ b/Source/cmPathLabel.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmPathLabel_h
 #define cmPathLabel_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 /** \class cmPathLabel
diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx
index 85f0fa3..3402191 100644
--- a/Source/cmPolicies.cxx
+++ b/Source/cmPolicies.cxx
@@ -2,14 +2,18 @@
 
 #include "cmAlgorithms.h"
 #include "cmMakefile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmVersion.h"
-#include "cmVersionMacros.h"
 #include "cmake.h"
+
 #include <assert.h>
+#include <cmConfigure.h>
 #include <ctype.h>
-#include <map>
-#include <queue>
-#include <set>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+#include <vector>
 
 static bool stringToId(const char* input, cmPolicies::PolicyID& pid)
 {
@@ -57,9 +61,9 @@ static const char* idToString(cmPolicies::PolicyID id)
     CM_FOR_EACH_POLICY_ID(POLICY_CASE)
 #undef POLICY_CASE
     case cmPolicies::CMPCOUNT:
-      return 0;
+      return CM_NULLPTR;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 static const char* idToVersion(cmPolicies::PolicyID id)
@@ -71,9 +75,9 @@ static const char* idToVersion(cmPolicies::PolicyID id)
     CM_FOR_EACH_POLICY_ID_VERSION(POLICY_CASE)
 #undef POLICY_CASE
     case cmPolicies::CMPCOUNT:
-      return 0;
+      return CM_NULLPTR;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 static bool isPolicyNewerThan(cmPolicies::PolicyID id, unsigned int majorV,
@@ -82,9 +86,10 @@ static bool isPolicyNewerThan(cmPolicies::PolicyID id, unsigned int majorV,
   switch (id) {
 #define POLICY_CASE(ID, V_MAJOR, V_MINOR, V_PATCH)                            \
   case cmPolicies::ID:                                                        \
-    return (                                                                  \
-      majorV < V_MAJOR || (majorV == V_MAJOR && minorV + 1 < V_MINOR + 1) ||  \
-      (majorV == V_MAJOR && minorV == V_MINOR && patchV + 1 < V_PATCH + 1));
+    return (majorV < (V_MAJOR) ||                                             \
+            (majorV == (V_MAJOR) && minorV + 1 < (V_MINOR) + 1) ||            \
+            (majorV == (V_MAJOR) && minorV == (V_MINOR) &&                    \
+             patchV + 1 < (V_PATCH) + 1));
     CM_FOR_EACH_POLICY_ID_VERSION(POLICY_CASE)
 #undef POLICY_CASE
     case cmPolicies::CMPCOUNT:
@@ -102,9 +107,9 @@ const char* idToShortDescription(cmPolicies::PolicyID id)
     CM_FOR_EACH_POLICY_ID_DOC(POLICY_CASE)
 #undef POLICY_CASE
     case cmPolicies::CMPCOUNT:
-      return 0;
+      return CM_NULLPTR;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 static void DiagnoseAncientPolicies(
@@ -293,7 +298,8 @@ std::string cmPolicies::GetRequiredPolicyError(cmPolicies::PolicyID id)
 }
 
 ///! Get the default status for a policy
-cmPolicies::PolicyStatus cmPolicies::GetPolicyStatus(cmPolicies::PolicyID)
+cmPolicies::PolicyStatus cmPolicies::GetPolicyStatus(
+  cmPolicies::PolicyID /*unused*/)
 {
   return cmPolicies::WARN;
 }
diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h
index ff49e31..9b86435 100644
--- a/Source/cmPolicies.h
+++ b/Source/cmPolicies.h
@@ -1,23 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmPolicies_h
 #define cmPolicies_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <bitset>
+#include <string>
 
 class cmMakefile;
-class cmPolicy;
 
 #define CM_FOR_EACH_POLICY_TABLE(POLICY, SELECT)                              \
   SELECT(POLICY, CMP0000,                                                     \
@@ -203,7 +194,10 @@ class cmPolicy;
   SELECT(POLICY, CMP0065,                                                     \
          "Do not add flags to export symbols from executables without "       \
          "the ENABLE_EXPORTS target property.",                               \
-         3, 4, 0, cmPolicies::WARN)
+         3, 4, 0, cmPolicies::WARN)                                           \
+  SELECT(POLICY, CMP0066,                                                     \
+         "Honor per-config flags in try_compile() source-file signature.", 3, \
+         7, 0, cmPolicies::WARN)
 
 #define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1)
 #define CM_FOR_EACH_POLICY_ID(POLICY)                                         \
diff --git a/Source/cmProcessTools.cxx b/Source/cmProcessTools.cxx
index 446752e..e7b6051 100644
--- a/Source/cmProcessTools.cxx
+++ b/Source/cmProcessTools.cxx
@@ -1,43 +1,35 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmProcessTools.h"
 
 #include <cmsys/Process.h>
+#include <ostream>
 
 void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
                                 OutputParser* err)
 {
   cmsysProcess_Execute(cp);
-  char* data = 0;
+  char* data = CM_NULLPTR;
   int length = 0;
   int p;
   while ((out || err) &&
-         (p = cmsysProcess_WaitForData(cp, &data, &length, 0), p)) {
+         (p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     if (out && p == cmsysProcess_Pipe_STDOUT) {
       if (!out->Process(data, length)) {
-        out = 0;
+        out = CM_NULLPTR;
       }
     } else if (err && p == cmsysProcess_Pipe_STDERR) {
       if (!err->Process(data, length)) {
-        err = 0;
+        err = CM_NULLPTR;
       }
     }
   }
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 }
 
 cmProcessTools::LineParser::LineParser(char sep, bool ignoreCR)
-  : Log(0)
-  , Prefix(0)
+  : Log(CM_NULLPTR)
+  , Prefix(CM_NULLPTR)
   , Separator(sep)
   , LineEnd('\0')
   , IgnoreCR(ignoreCR)
diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h
index a48e52b..e5a3fe9 100644
--- a/Source/cmProcessTools.h
+++ b/Source/cmProcessTools.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmProcessTools_h
 #define cmProcessTools_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string.h>
+#include <string>
 
 /** \class cmProcessTools
  * \brief Helper classes for process output parsing
@@ -62,7 +57,7 @@ public:
     char Separator;
     char LineEnd;
     bool IgnoreCR;
-    virtual bool ProcessChunk(const char* data, int length);
+    bool ProcessChunk(const char* data, int length) CM_OVERRIDE;
 
     /** Implement in a subclass to process one line of input.  It
         should return true only if it is interested in more data.  */
@@ -73,18 +68,18 @@ public:
   class OutputLogger : public LineParser
   {
   public:
-    OutputLogger(std::ostream& log, const char* prefix = 0)
+    OutputLogger(std::ostream& log, const char* prefix = CM_NULLPTR)
     {
       this->SetLog(&log, prefix);
     }
 
   private:
-    virtual bool ProcessLine() { return true; }
+    bool ProcessLine() CM_OVERRIDE { return true; }
   };
 
   /** Run a process and send output to given parsers.  */
   static void RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
-                         OutputParser* err = 0);
+                         OutputParser* err = CM_NULLPTR);
 };
 
 #endif
diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx
index 139303b..c34a94b 100644
--- a/Source/cmProjectCommand.cxx
+++ b/Source/cmProjectCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmProjectCommand.h"
 
 // cmProjectCommand
 bool cmProjectCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("PROJECT called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmProjectCommand.h b/Source/cmProjectCommand.h
index a4e6367..c9c2549 100644
--- a/Source/cmProjectCommand.h
+++ b/Source/cmProjectCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmProjectCommand_h
 #define cmProjectCommand_h
 
@@ -28,19 +19,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmProjectCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmProjectCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "project"; }
+  std::string GetName() const CM_OVERRIDE { return "project"; }
 
   cmTypeMacro(cmProjectCommand, cmCommand);
 };
diff --git a/Source/cmProperty.cxx b/Source/cmProperty.cxx
index 4910616..90122a4 100644
--- a/Source/cmProperty.cxx
+++ b/Source/cmProperty.cxx
@@ -1,17 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmProperty.h"
 
-#include "cmSystemTools.h"
+#include <cmConfigure.h>
 
 void cmProperty::Set(const char* value)
 {
@@ -33,5 +24,5 @@ const char* cmProperty::GetValue() const
   if (this->ValueHasBeenSet) {
     return this->Value.c_str();
   }
-  return 0;
+  return CM_NULLPTR;
 }
diff --git a/Source/cmProperty.h b/Source/cmProperty.h
index 1736136..3f2dcfe 100644
--- a/Source/cmProperty.h
+++ b/Source/cmProperty.h
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmProperty_h
 #define cmProperty_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
 
 class cmProperty
 {
diff --git a/Source/cmPropertyDefinition.cxx b/Source/cmPropertyDefinition.cxx
index 546146b..6a3174c 100644
--- a/Source/cmPropertyDefinition.cxx
+++ b/Source/cmPropertyDefinition.cxx
@@ -1,18 +1,7 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmPropertyDefinition.h"
 
-#include "cmSystemTools.h"
-
 void cmPropertyDefinition::DefineProperty(const std::string& name,
                                           cmProperty::ScopeType scope,
                                           const char* shortDescription,
diff --git a/Source/cmPropertyDefinition.h b/Source/cmPropertyDefinition.h
index 5733917..eb8d064 100644
--- a/Source/cmPropertyDefinition.h
+++ b/Source/cmPropertyDefinition.h
@@ -1,19 +1,14 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmPropertyDefinition_h
 #define cmPropertyDefinition_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmProperty.h"
 
+#include <string>
+
 /** \class cmPropertyDefinition
  * \brief Property meta-information
  *
diff --git a/Source/cmPropertyDefinitionMap.cxx b/Source/cmPropertyDefinitionMap.cxx
index ebc2caa..5daaf9b 100644
--- a/Source/cmPropertyDefinitionMap.cxx
+++ b/Source/cmPropertyDefinitionMap.cxx
@@ -1,18 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmPropertyDefinitionMap.h"
 
-#include "cmDocumentationSection.h"
-#include "cmSystemTools.h"
+#include <utility>
 
 void cmPropertyDefinitionMap::DefineProperty(const std::string& name,
                                              cmProperty::ScopeType scope,
@@ -31,12 +21,7 @@ void cmPropertyDefinitionMap::DefineProperty(const std::string& name,
 
 bool cmPropertyDefinitionMap::IsPropertyDefined(const std::string& name) const
 {
-  cmPropertyDefinitionMap::const_iterator it = this->find(name);
-  if (it == this->end()) {
-    return false;
-  }
-
-  return true;
+  return this->find(name) != this->end();
 }
 
 bool cmPropertyDefinitionMap::IsPropertyChained(const std::string& name) const
diff --git a/Source/cmPropertyDefinitionMap.h b/Source/cmPropertyDefinitionMap.h
index fbc9a18..e747503 100644
--- a/Source/cmPropertyDefinitionMap.h
+++ b/Source/cmPropertyDefinitionMap.h
@@ -1,20 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmPropertyDefinitionMap_h
 #define cmPropertyDefinitionMap_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include "cmProperty.h"
 #include "cmPropertyDefinition.h"
 
-class cmDocumentationSection;
+#include <map>
+#include <string>
 
 class cmPropertyDefinitionMap
   : public std::map<std::string, cmPropertyDefinition>
diff --git a/Source/cmPropertyMap.cxx b/Source/cmPropertyMap.cxx
index 74e04da..fa92ae2 100644
--- a/Source/cmPropertyMap.cxx
+++ b/Source/cmPropertyMap.cxx
@@ -1,21 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmPropertyMap.h"
 
-#include "cmState.h"
-#include "cmSystemTools.h"
-#include "cmake.h"
-
+#include <algorithm>
 #include <assert.h>
+#include <cmConfigure.h>
+#include <utility>
 
 cmProperty* cmPropertyMap::GetOrCreateProperty(const std::string& name)
 {
@@ -29,6 +19,17 @@ cmProperty* cmPropertyMap::GetOrCreateProperty(const std::string& name)
   return prop;
 }
 
+std::vector<std::string> cmPropertyMap::GetPropertyList() const
+{
+  std::vector<std::string> keyList;
+  for (cmPropertyMap::const_iterator i = this->begin(), e = this->end();
+       i != e; ++i) {
+    keyList.push_back(i->first);
+  }
+  std::sort(keyList.begin(), keyList.end());
+  return keyList;
+}
+
 void cmPropertyMap::SetProperty(const std::string& name, const char* value)
 {
   if (!value) {
@@ -58,7 +59,7 @@ const char* cmPropertyMap::GetPropertyValue(const std::string& name) const
 
   cmPropertyMap::const_iterator it = this->find(name);
   if (it == this->end()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return it->second.GetValue();
 }
diff --git a/Source/cmPropertyMap.h b/Source/cmPropertyMap.h
index 4e98750..e1db7df 100644
--- a/Source/cmPropertyMap.h
+++ b/Source/cmPropertyMap.h
@@ -1,24 +1,23 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmPropertyMap_h
 #define cmPropertyMap_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmProperty.h"
 
+#include <map>
+#include <string>
+#include <vector>
+
 class cmPropertyMap : public std::map<std::string, cmProperty>
 {
 public:
   cmProperty* GetOrCreateProperty(const std::string& name);
 
+  std::vector<std::string> GetPropertyList() const;
+
   void SetProperty(const std::string& name, const char* value);
 
   void AppendProperty(const std::string& name, const char* value,
diff --git a/Source/cmQTWrapCPPCommand.cxx b/Source/cmQTWrapCPPCommand.cxx
index f63672b..3a721da 100644
--- a/Source/cmQTWrapCPPCommand.cxx
+++ b/Source/cmQTWrapCPPCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQTWrapCPPCommand.h"
 
 // cmQTWrapCPPCommand
@@ -80,7 +71,7 @@ bool cmQTWrapCPPCommand::InitialPass(std::vector<std::string> const& args,
       depends.push_back(hname);
 
       std::string no_main_dependency = "";
-      const char* no_working_dir = 0;
+      const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
         newName, depends, no_main_dependency, commandLines, "Qt Wrapped File",
         no_working_dir);
diff --git a/Source/cmQTWrapCPPCommand.h b/Source/cmQTWrapCPPCommand.h
index 2014828..3567fb6 100644
--- a/Source/cmQTWrapCPPCommand.h
+++ b/Source/cmQTWrapCPPCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmQTWrapCPPCommand_h
 #define cmQTWrapCPPCommand_h
 
@@ -30,19 +21,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmQTWrapCPPCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapCPPCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "qt_wrap_cpp"; }
+  std::string GetName() const CM_OVERRIDE { return "qt_wrap_cpp"; }
 };
 
 #endif
diff --git a/Source/cmQTWrapUICommand.cxx b/Source/cmQTWrapUICommand.cxx
index 4c1da36..3b0f083 100644
--- a/Source/cmQTWrapUICommand.cxx
+++ b/Source/cmQTWrapUICommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQTWrapUICommand.h"
 
 // cmQTWrapUICommand
@@ -111,8 +102,8 @@ bool cmQTWrapUICommand::InitialPass(std::vector<std::string> const& args,
       std::vector<std::string> depends;
       depends.push_back(uiName);
       std::string no_main_dependency = "";
-      const char* no_comment = 0;
-      const char* no_working_dir = 0;
+      const char* no_comment = CM_NULLPTR;
+      const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
         hName, depends, no_main_dependency, hCommandLines, no_comment,
         no_working_dir);
diff --git a/Source/cmQTWrapUICommand.h b/Source/cmQTWrapUICommand.h
index 48cfc77..84b88a8 100644
--- a/Source/cmQTWrapUICommand.h
+++ b/Source/cmQTWrapUICommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmQTWrapUICommand_h
 #define cmQTWrapUICommand_h
 
@@ -28,19 +19,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmQTWrapUICommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapUICommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "qt_wrap_ui"; }
+  std::string GetName() const CM_OVERRIDE { return "qt_wrap_ui"; }
 };
 
 #endif
diff --git a/Source/cmQtAutoGeneratorInitializer.cxx b/Source/cmQtAutoGeneratorInitializer.cxx
index 70c8a65..5246a67 100644
--- a/Source/cmQtAutoGeneratorInitializer.cxx
+++ b/Source/cmQtAutoGeneratorInitializer.cxx
@@ -1,30 +1,69 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQtAutoGeneratorInitializer.h"
 
+#include "cmAlgorithms.h"
+#include "cmCustomCommandLines.h"
+#include "cmFilePathUuid.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
-
-#include <sys/stat.h>
-
-#include <cmsys/FStream.hxx>
+#include "cmSourceFileLocation.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #include "cmGlobalVisualStudioGenerator.h"
 #endif
 
+#include <algorithm>
+#include <assert.h>
+#include <cmConfigure.h>
+#include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <iostream>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string.h>
+#include <string>
+#include <sys/stat.h>
+#include <utility>
+#include <vector>
+
+static std::string GetAutogenTargetName(cmGeneratorTarget const* target)
+{
+  std::string autogenTargetName = target->GetName();
+  autogenTargetName += "_automoc";
+  return autogenTargetName;
+}
+
+static std::string GetAutogenTargetDir(cmGeneratorTarget const* target)
+{
+  cmMakefile* makefile = target->Target->GetMakefile();
+  std::string targetDir = makefile->GetCurrentBinaryDirectory();
+  targetDir += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
+  targetDir += "/";
+  targetDir += GetAutogenTargetName(target);
+  targetDir += ".dir/";
+  return targetDir;
+}
+
+static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target)
+{
+  cmMakefile* makefile = target->Target->GetMakefile();
+  std::string targetDir = makefile->GetCurrentBinaryDirectory();
+  targetDir += "/";
+  targetDir += GetAutogenTargetName(target);
+  targetDir += ".dir/";
+  return targetDir;
+}
+
 static void SetupSourceFiles(cmGeneratorTarget const* target,
                              std::vector<std::string>& skipMoc,
                              std::vector<std::string>& mocSources,
@@ -38,6 +77,7 @@ static void SetupSourceFiles(cmGeneratorTarget const* target,
 
   std::vector<std::string> newRccFiles;
 
+  cmFilePathUuid fpathUuid(makefile);
   for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
        fileIt != srcFiles.end(); ++fileIt) {
     cmSourceFile* sf = *fileIt;
@@ -55,13 +95,12 @@ static void SetupSourceFiles(cmGeneratorTarget const* target,
     if (target->GetPropertyAsBool("AUTORCC")) {
       if (ext == "qrc" &&
           !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"))) {
-        std::string basename =
-          cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile);
 
-        std::string rcc_output_dir = target->GetSupportDirectory();
-        cmSystemTools::MakeDirectory(rcc_output_dir.c_str());
-        std::string rcc_output_file = rcc_output_dir;
-        rcc_output_file += "/qrc_" + basename + ".cpp";
+        std::string rcc_output_file = GetAutogenTargetBuildDir(target);
+        // Create output directory
+        cmSystemTools::MakeDirectory(rcc_output_file.c_str());
+        rcc_output_file += fpathUuid.get(absFile, "qrc_", ".cpp");
+
         makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
                                  rcc_output_file.c_str(), false);
         makefile->GetOrCreateSource(rcc_output_file, true);
@@ -97,7 +136,7 @@ static void GetCompileDefinitionsAndDirectories(
   std::vector<std::string> includeDirs;
   cmLocalGenerator* localGen = target->GetLocalGenerator();
   // Get the include dirs for this target, without stripping the implicit
-  // include dirs off, see http://public.kitware.com/Bug/view.php?id=13667
+  // include dirs off, see https://gitlab.kitware.com/cmake/cmake/issues/13667
   localGen->GetIncludeDirectories(includeDirs, target, "CXX", config, false);
 
   incs = cmJoin(includeDirs, ";");
@@ -119,7 +158,7 @@ static void SetupAutoMocTarget(
   cmMakefile* makefile = target->Target->GetMakefile();
 
   const char* tmp = target->GetProperty("AUTOMOC_MOC_OPTIONS");
-  std::string _moc_options = (tmp != 0 ? tmp : "");
+  std::string _moc_options = (tmp != CM_NULLPTR ? tmp : "");
   makefile->AddDefinition(
     "_moc_options", cmOutputConverter::EscapeForCMake(_moc_options).c_str());
   makefile->AddDefinition(
@@ -318,7 +357,8 @@ static std::string GetRccExecutable(cmGeneratorTarget const* target)
       return std::string();
     }
     return qt5Rcc->ImportedGetLocation("");
-  } else if (strcmp(qtVersion, "4") == 0) {
+  }
+  if (strcmp(qtVersion, "4") == 0) {
     cmGeneratorTarget* qt4Rcc = lg->FindGeneratorTargetToUse("Qt4::rcc");
     if (!qt4Rcc) {
       cmSystemTools::Error("Qt4::rcc target not found ", targetName.c_str());
@@ -365,24 +405,6 @@ static void MergeRccOptions(std::vector<std::string>& opts,
   opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
 }
 
-std::string GetAutogenTargetName(cmGeneratorTarget const* target)
-{
-  std::string autogenTargetName = target->GetName();
-  autogenTargetName += "_automoc";
-  return autogenTargetName;
-}
-
-std::string GetAutogenTargetDir(cmGeneratorTarget const* target)
-{
-  cmMakefile* makefile = target->Target->GetMakefile();
-  std::string targetDir = makefile->GetCurrentBinaryDirectory();
-  targetDir += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
-  targetDir += "/";
-  targetDir += GetAutogenTargetName(target);
-  targetDir += ".dir/";
-  return targetDir;
-}
-
 static void copyTargetProperty(cmTarget* destinationTarget,
                                cmTarget* sourceTarget,
                                const std::string& propertyName)
@@ -406,19 +428,21 @@ static std::string cmQtAutoGeneratorsStripCR(std::string const& line)
 static std::string ReadAll(const std::string& filename)
 {
   cmsys::ifstream file(filename.c_str());
-  std::stringstream stream;
+  std::ostringstream stream;
   stream << file.rdbuf();
   file.close();
   return stream.str();
 }
 
-static std::string ListQt5RccInputs(cmSourceFile* sf,
-                                    cmGeneratorTarget const* target,
-                                    std::vector<std::string>& depends)
+/// @brief Reads the resource files list from from a .qrc file - Qt5 version
+/// @return True if the .qrc file was successfully parsed
+static bool ListQt5RccInputs(cmSourceFile* sf, cmGeneratorTarget const* target,
+                             std::vector<std::string>& depends)
 {
   std::string rccCommand = GetRccExecutable(target);
 
   bool hasDashDashList = false;
+  // Read rcc features
   {
     std::vector<std::string> command;
     command.push_back(rccCommand);
@@ -426,46 +450,46 @@ static std::string ListQt5RccInputs(cmSourceFile* sf,
     std::string rccStdOut;
     std::string rccStdErr;
     int retVal = 0;
-    bool result = cmSystemTools::RunSingleCommand(
-      command, &rccStdOut, &rccStdErr, &retVal, 0, cmSystemTools::OUTPUT_NONE);
+    bool result =
+      cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal,
+                                      CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
     if (result && retVal == 0 &&
         rccStdOut.find("--list") != std::string::npos) {
       hasDashDashList = true;
     }
   }
-
-  std::vector<std::string> qrcEntries;
-
+  // Run rcc list command
   std::vector<std::string> command;
   command.push_back(rccCommand);
   command.push_back(hasDashDashList ? "--list" : "-list");
 
   std::string absFile = cmsys::SystemTools::GetRealPath(sf->GetFullPath());
-
   command.push_back(absFile);
 
   std::string rccStdOut;
   std::string rccStdErr;
   int retVal = 0;
-  bool result = cmSystemTools::RunSingleCommand(
-    command, &rccStdOut, &rccStdErr, &retVal, 0, cmSystemTools::OUTPUT_NONE);
+  bool result =
+    cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal,
+                                    CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
   if (!result || retVal) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "AUTOGEN: error: Rcc list process for " << sf->GetFullPath()
         << " failed:\n"
         << rccStdOut << "\n"
         << rccStdErr << std::endl;
-    std::cerr << err.str();
-    return std::string();
+    cmSystemTools::Error(err.str().c_str());
+    return false;
   }
 
+  // Parse rcc list output
   {
     std::istringstream ostr(rccStdOut);
     std::string oline;
     while (std::getline(ostr, oline)) {
       oline = cmQtAutoGeneratorsStripCR(oline);
       if (!oline.empty()) {
-        qrcEntries.push_back(oline);
+        depends.push_back(oline);
       }
     }
   }
@@ -480,33 +504,31 @@ static std::string ListQt5RccInputs(cmSourceFile* sf,
 
         std::string::size_type pos = eline.find(searchString);
         if (pos == std::string::npos) {
-          std::stringstream err;
+          std::ostringstream err;
           err << "AUTOGEN: error: Rcc lists unparsable output " << eline
               << std::endl;
-          std::cerr << err.str();
-          return std::string();
+          cmSystemTools::Error(err.str().c_str());
+          return false;
         }
         pos += searchString.length();
         std::string::size_type sz = eline.size() - pos - 1;
-        qrcEntries.push_back(eline.substr(pos, sz));
+        depends.push_back(eline.substr(pos, sz));
       }
     }
   }
 
-  depends.insert(depends.end(), qrcEntries.begin(), qrcEntries.end());
-  return cmJoin(qrcEntries, "@list_sep@");
+  return true;
 }
 
-static std::string ListQt4RccInputs(cmSourceFile* sf,
-                                    std::vector<std::string>& depends)
+/// @brief Reads the resource files list from from a .qrc file - Qt4 version
+/// @return True if the .qrc file was successfully parsed
+static bool ListQt4RccInputs(cmSourceFile* sf,
+                             std::vector<std::string>& depends)
 {
   const std::string qrcContents = ReadAll(sf->GetFullPath());
 
   cmsys::RegularExpression fileMatchRegex("(<file[^<]+)");
 
-  std::string entriesList;
-  const char* sep = "";
-
   size_t offset = 0;
   while (fileMatchRegex.find(qrcContents.c_str() + offset)) {
     std::string qrcEntry = fileMatchRegex.match(1);
@@ -523,12 +545,21 @@ static std::string ListQt4RccInputs(cmSourceFile* sf,
       qrcEntry = sf->GetLocation().GetDirectory() + "/" + qrcEntry;
     }
 
-    entriesList += sep;
-    entriesList += qrcEntry;
-    sep = "@list_sep@";
     depends.push_back(qrcEntry);
   }
-  return entriesList;
+  return true;
+}
+
+/// @brief Reads the resource files list from from a .qrc file
+/// @return True if the rcc file was successfully parsed
+static bool ListQtRccInputs(const std::string& qtMajorVersion,
+                            cmSourceFile* sf, cmGeneratorTarget const* target,
+                            std::vector<std::string>& depends)
+{
+  if (qtMajorVersion == "5") {
+    return ListQt5RccInputs(sf, target, depends);
+  }
+  return ListQt4RccInputs(sf, depends);
 }
 
 static void SetupAutoRccTarget(cmGeneratorTarget const* target)
@@ -591,16 +622,12 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
         }
         optionSep = ";";
 
-        std::vector<std::string> depends;
-
         std::string entriesList;
         if (!cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"))) {
-          if (qtMajorVersion == "5") {
-            entriesList = ListQt5RccInputs(sf, target, depends);
+          std::vector<std::string> depends;
+          if (ListQtRccInputs(qtMajorVersion, sf, target, depends)) {
+            entriesList = cmJoin(depends, "@list_sep@");
           } else {
-            entriesList = ListQt4RccInputs(sf, depends);
-          }
-          if (entriesList.empty()) {
             return;
           }
         }
@@ -735,6 +762,7 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
       ) {
     std::vector<cmSourceFile*> srcFiles;
     target->GetConfigCommonSourceFiles(srcFiles);
+    cmFilePathUuid fpathUuid(makefile);
     for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
          fileIt != srcFiles.end(); ++fileIt) {
       cmSourceFile* sf = *fileIt;
@@ -745,21 +773,15 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
       if (target->GetPropertyAsBool("AUTORCC")) {
         if (ext == "qrc" &&
             !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"))) {
-          std::string basename =
-            cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile);
-
-          std::string rcc_output_dir = target->GetSupportDirectory();
-          cmSystemTools::MakeDirectory(rcc_output_dir.c_str());
-          std::string rcc_output_file = rcc_output_dir;
-          rcc_output_file += "/qrc_" + basename + ".cpp";
-          rcc_output.push_back(rcc_output_file);
-
+          {
+            std::string rcc_output_file = GetAutogenTargetBuildDir(target);
+            // Create output directory
+            cmSystemTools::MakeDirectory(rcc_output_file.c_str());
+            rcc_output_file += fpathUuid.get(absFile, "qrc_", ".cpp");
+            rcc_output.push_back(rcc_output_file);
+          }
           if (!cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"))) {
-            if (qtMajorVersion == "5") {
-              ListQt5RccInputs(sf, target, depends);
-            } else {
-              ListQt4RccInputs(sf, depends);
-            }
+            ListQtRccInputs(qtMajorVersion, sf, target, depends);
 #if defined(_WIN32) && !defined(__CYGWIN__)
             // Cannot use PRE_BUILD because the resource files themselves
             // may not be sources within the target so VS may not know the
diff --git a/Source/cmQtAutoGeneratorInitializer.h b/Source/cmQtAutoGeneratorInitializer.h
index b411597..26f2c8e 100644
--- a/Source/cmQtAutoGeneratorInitializer.h
+++ b/Source/cmQtAutoGeneratorInitializer.h
@@ -1,26 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmQtAutoGeneratorInitializer_h
 #define cmQtAutoGeneratorInitializer_h
 
-#include "cmStandardIncludes.h"
-
-#include <map>
-#include <string>
-#include <vector>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-class cmSourceFile;
 class cmGeneratorTarget;
 class cmLocalGenerator;
 
diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx
index 3677a28..b66257c 100644
--- a/Source/cmQtAutoGenerators.cxx
+++ b/Source/cmQtAutoGenerators.cxx
@@ -1,32 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQtAutoGenerators.h"
 
 #include "cmAlgorithms.h"
+#include "cmFilePathUuid.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
-#include <sys/stat.h>
-
+#include <algorithm>
 #include <assert.h>
+#include <cmConfigure.h>
 #include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
 #include <cmsys/Terminal.h>
-
+#include <iostream>
+#include <sstream>
+#include <stdlib.h>
 #include <string.h>
+#include <utility>
+
 #if defined(__APPLE__)
 #include <unistd.h>
 #endif
@@ -34,8 +31,8 @@
 static bool requiresMocing(const std::string& text, std::string& macroName)
 {
   // this simple check is much much faster than the regexp
-  if (strstr(text.c_str(), "Q_OBJECT") == NULL &&
-      strstr(text.c_str(), "Q_GADGET") == NULL) {
+  if (strstr(text.c_str(), "Q_OBJECT") == CM_NULLPTR &&
+      strstr(text.c_str(), "Q_GADGET") == CM_NULLPTR) {
     return false;
   }
 
@@ -87,8 +84,25 @@ static std::string extractSubDir(const std::string& absPath,
   return subDir;
 }
 
+static bool FileNameIsUnique(const std::string& filePath,
+                             const std::map<std::string, std::string>& fileMap)
+{
+  size_t count(0);
+  const std::string fileName = cmsys::SystemTools::GetFilenameName(filePath);
+  for (std::map<std::string, std::string>::const_iterator si = fileMap.begin();
+       si != fileMap.end(); ++si) {
+    if (cmsys::SystemTools::GetFilenameName(si->first) == fileName) {
+      ++count;
+      if (count > 1) {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
 cmQtAutoGenerators::cmQtAutoGenerators()
-  : Verbose(cmsys::SystemTools::GetEnv("VERBOSE") != 0)
+  : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
   , ColorOutput(true)
   , RunMocFailed(false)
   , RunUicFailed(false)
@@ -155,7 +169,7 @@ bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
   snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
   snapshot.GetDirectory().SetCurrentSource(targetDirectory);
 
-  cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(&gg, snapshot));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
   gg.SetCurrentMakefile(mf.get());
 
   this->ReadAutogenInfoFile(mf.get(), targetDirectory, config);
@@ -358,11 +372,13 @@ void cmQtAutoGenerators::WriteOldMocDefinitionsFile(
 
 void cmQtAutoGenerators::Init()
 {
+  this->TargetBuildSubDir = this->TargetName;
+  this->TargetBuildSubDir += ".dir/";
+
   this->OutMocCppFilenameRel = this->TargetName;
   this->OutMocCppFilenameRel += ".cpp";
 
-  this->OutMocCppFilename = this->Builddir;
-  this->OutMocCppFilename += this->OutMocCppFilenameRel;
+  this->OutMocCppFilenameAbs = this->Builddir + this->OutMocCppFilenameRel;
 
   std::vector<std::string> cdefList;
   cmSystemTools::ExpandListArgument(this->MocCompileDefinitionsStr, cdefList);
@@ -431,7 +447,7 @@ void cmQtAutoGenerators::Init()
 static std::string ReadAll(const std::string& filename)
 {
   cmsys::ifstream file(filename.c_str());
-  std::stringstream stream;
+  std::ostringstream stream;
   stream << file.rdbuf();
   file.close();
   return stream.str();
@@ -439,7 +455,7 @@ static std::string ReadAll(const std::string& filename)
 
 bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
 {
-  if (!cmsys::SystemTools::FileExists(this->OutMocCppFilename.c_str()) ||
+  if (!cmsys::SystemTools::FileExists(this->OutMocCppFilenameAbs.c_str()) ||
       (this->OldCompileSettingsStr != this->CurrentCompileSettingsStr)) {
     this->GenerateAll = true;
   }
@@ -476,7 +492,7 @@ bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
       skipUic ? skippedUis : includedUis;
     const std::string& absFilename = *it;
     if (this->Verbose) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: Checking " << absFilename << std::endl;
       this->LogInfo(err.str());
     }
@@ -498,7 +514,7 @@ bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
           uicSkipped.end()) {
         const std::string& absFilename = *it;
         if (this->Verbose) {
-          std::stringstream err;
+          std::ostringstream err;
           err << "AUTOGEN: Checking " << absFilename << std::endl;
           this->LogInfo(err.str());
         }
@@ -526,19 +542,19 @@ bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
   }
 
   if (this->RunMocFailed) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "moc failed..." << std::endl;
     this->LogError(err.str());
     return false;
   }
   if (this->RunUicFailed) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "uic failed..." << std::endl;
     this->LogError(err.str());
     return false;
   }
   if (this->RunRccFailed) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "rcc failed..." << std::endl;
     this->LogError(err.str());
     return false;
@@ -559,7 +575,7 @@ void cmQtAutoGenerators::ParseCppFile(
 
   const std::string contentsString = ReadAll(absFilename);
   if (contentsString.empty()) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
         << std::endl;
     this->LogError(err.str());
@@ -587,7 +603,7 @@ void cmQtAutoGenerators::ParseCppFile(
   // first a simple string check for "moc" is *much* faster than the regexp,
   // and if the string search already fails, we don't have to try the
   // expensive regexp
-  if ((strstr(contentsString.c_str(), "moc") != NULL) &&
+  if ((strstr(contentsString.c_str(), "moc") != CM_NULLPTR) &&
       (mocIncludeRegExp.find(contentsString))) {
     // for every moc include in the file
     do {
@@ -619,7 +635,7 @@ void cmQtAutoGenerators::ParseCppFile(
             ownMocHeaderFile = headerToMoc;
           }
         } else {
-          std::stringstream err;
+          std::ostringstream err;
           err << "AUTOGEN: error: " << absFilename << ": The file "
               << "includes the moc file \"" << currentMoc << "\", "
               << "but could not find header \"" << basename << '{'
@@ -635,15 +651,15 @@ void cmQtAutoGenerators::ParseCppFile(
         }
       } else {
         std::string fileToMoc = absFilename;
-        if ((basename != scannedFileBasename) || (requiresMoc == false)) {
+        if (!requiresMoc || basename != scannedFileBasename) {
           std::string mocSubDir = extractSubDir(absPath, currentMoc);
           std::string headerToMoc =
             findMatchingHeader(absPath, mocSubDir, basename, headerExtensions);
           if (!headerToMoc.empty()) {
             // this is for KDE4 compatibility:
             fileToMoc = headerToMoc;
-            if ((requiresMoc == false) && (basename == scannedFileBasename)) {
-              std::stringstream err;
+            if (!requiresMoc && basename == scannedFileBasename) {
+              std::ostringstream err;
               err << "AUTOGEN: warning: " << absFilename
                   << ": The file "
                      "includes the moc file \""
@@ -655,7 +671,7 @@ void cmQtAutoGenerators::ParseCppFile(
                   << std::endl;
               this->LogError(err.str());
             } else {
-              std::stringstream err;
+              std::ostringstream err;
               err << "AUTOGEN: warning: " << absFilename
                   << ": The file "
                      "includes the moc file \""
@@ -669,7 +685,7 @@ void cmQtAutoGenerators::ParseCppFile(
               this->LogError(err.str());
             }
           } else {
-            std::stringstream err;
+            std::ostringstream err;
             err << "AUTOGEN: error: " << absFilename
                 << ": The file "
                    "includes the moc file \""
@@ -695,10 +711,10 @@ void cmQtAutoGenerators::ParseCppFile(
   // If this is the case, the moc_foo.cpp should probably be generated from
   // foo.cpp instead of foo.h, because otherwise it won't build.
   // But warn, since this is not how it is supposed to be used.
-  if ((dotMocIncluded == false) && (requiresMoc == true)) {
-    if (mocUnderscoreIncluded == true) {
+  if (!dotMocIncluded && requiresMoc) {
+    if (mocUnderscoreIncluded) {
       // this is for KDE4 compatibility:
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: warning: " << absFilename << ": The file "
           << "contains a " << macroName << " macro, but does not "
                                            "include "
@@ -716,7 +732,7 @@ void cmQtAutoGenerators::ParseCppFile(
       includedMocs.erase(ownMocHeaderFile);
     } else {
       // otherwise always error out since it will not compile:
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: error: " << absFilename << ": The file "
           << "contains a " << macroName << " macro, but does not "
                                            "include "
@@ -741,7 +757,7 @@ void cmQtAutoGenerators::StrictParseCppFile(
 
   const std::string contentsString = ReadAll(absFilename);
   if (contentsString.empty()) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
         << std::endl;
     this->LogError(err.str());
@@ -764,7 +780,7 @@ void cmQtAutoGenerators::StrictParseCppFile(
   // first a simple string check for "moc" is *much* faster than the regexp,
   // and if the string search already fails, we don't have to try the
   // expensive regexp
-  if ((strstr(contentsString.c_str(), "moc") != NULL) &&
+  if ((strstr(contentsString.c_str(), "moc") != CM_NULLPTR) &&
       (mocIncludeRegExp.find(contentsString))) {
     // for every moc include in the file
     do {
@@ -790,7 +806,7 @@ void cmQtAutoGenerators::StrictParseCppFile(
         if (!headerToMoc.empty()) {
           includedMocs[headerToMoc] = currentMoc;
         } else {
-          std::stringstream err;
+          std::ostringstream err;
           err << "AUTOGEN: error: " << absFilename << " The file "
               << "includes the moc file \"" << currentMoc << "\", "
               << "but could not find header \"" << basename << '{'
@@ -806,7 +822,7 @@ void cmQtAutoGenerators::StrictParseCppFile(
         }
       } else {
         if (basename != scannedFileBasename) {
-          std::stringstream err;
+          std::ostringstream err;
           err << "AUTOGEN: error: " << absFilename
               << ": The file "
                  "includes the moc file \""
@@ -832,10 +848,9 @@ void cmQtAutoGenerators::StrictParseCppFile(
   // foo.cpp instead of foo.h, because otherwise it won't build.
   // But warn, since this is not how it is supposed to be used.
   std::string macroName;
-  if ((dotMocIncluded == false) &&
-      (requiresMocing(contentsString, macroName))) {
+  if (!dotMocIncluded && requiresMocing(contentsString, macroName)) {
     // otherwise always error out since it will not compile:
-    std::stringstream err;
+    std::ostringstream err;
     err << "AUTOGEN: error: " << absFilename << ": The file "
         << "contains a " << macroName << " macro, but does not include "
         << "\"" << scannedFileBasename << ".moc\" !\n"
@@ -854,7 +869,7 @@ void cmQtAutoGenerators::ParseForUic(
   }
   const std::string contentsString = ReadAll(absFilename);
   if (contentsString.empty()) {
-    std::stringstream err;
+    std::ostringstream err;
     err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
         << std::endl;
     this->LogError(err.str());
@@ -879,7 +894,7 @@ void cmQtAutoGenerators::ParseForUic(
   const std::string realName = cmsys::SystemTools::GetRealPath(absFilename);
 
   matchOffset = 0;
-  if ((strstr(contentsString.c_str(), "ui_") != NULL) &&
+  if ((strstr(contentsString.c_str(), "ui_") != CM_NULLPTR) &&
       (uiIncludeRegExp.find(contentsString))) {
     do {
       const std::string currentUi = uiIncludeRegExp.match(1);
@@ -934,6 +949,8 @@ void cmQtAutoGenerators::ParseHeaders(
   std::map<std::string, std::string>& notIncludedMocs,
   std::map<std::string, std::vector<std::string> >& includedUis)
 {
+  cmFilePathUuid fpathUuid(this->Srcdir, this->Builddir,
+                           this->ProjectSourceDir, this->ProjectBinaryDir);
   for (std::set<std::string>::const_iterator hIt = absHeaders.begin();
        hIt != absHeaders.end(); ++hIt) {
     const std::string& headerName = *hIt;
@@ -942,18 +959,15 @@ void cmQtAutoGenerators::ParseHeaders(
     if (!this->MocExecutable.empty() &&
         includedMocs.find(headerName) == includedMocs.end()) {
       if (this->Verbose) {
-        std::stringstream err;
+        std::ostringstream err;
         err << "AUTOGEN: Checking " << headerName << std::endl;
         this->LogInfo(err.str());
       }
 
-      const std::string basename =
-        cmsys::SystemTools::GetFilenameWithoutLastExtension(headerName);
-
-      const std::string currentMoc = "moc_" + basename + ".cpp";
       std::string macroName;
       if (requiresMocing(contents, macroName)) {
-        notIncludedMocs[headerName] = currentMoc;
+        notIncludedMocs[headerName] =
+          this->TargetBuildSubDir + fpathUuid.get(headerName, "moc_", ".cpp");
       }
     }
     this->ParseForUic(headerName, contents, includedUis);
@@ -971,7 +985,7 @@ bool cmQtAutoGenerators::GenerateMocFiles(
     std::map<std::string, std::string> mergedMocs(includedMocs);
     mergedMocs.insert(notIncludedMocs.begin(), notIncludedMocs.end());
     if (this->NameCollisionTest(mergedMocs, collisions)) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: error: "
              "The same moc file will be generated "
              "from different sources."
@@ -1012,7 +1026,7 @@ bool cmQtAutoGenerators::GenerateMocFiles(
   // compose _automoc.cpp content
   std::string automocSource;
   {
-    std::stringstream outStream;
+    std::ostringstream outStream;
     outStream << "/* This file is autogenerated, do not edit*/\n";
     if (notIncludedMocs.empty()) {
       outStream << "enum some_compilers { need_more_than_nothing };\n";
@@ -1030,11 +1044,11 @@ bool cmQtAutoGenerators::GenerateMocFiles(
   // check if we even need to update _automoc.cpp
   if (!automocCppChanged) {
     // compare contents of the _automoc.cpp file
-    const std::string oldContents = ReadAll(this->OutMocCppFilename);
+    const std::string oldContents = ReadAll(this->OutMocCppFilenameAbs);
     if (oldContents == automocSource) {
       // nothing changed: don't touch the _automoc.cpp file
       if (this->Verbose) {
-        std::stringstream err;
+        std::ostringstream err;
         err << "AUTOGEN: " << this->OutMocCppFilenameRel << " still up to date"
             << std::endl;
         this->LogInfo(err.str());
@@ -1053,7 +1067,7 @@ bool cmQtAutoGenerators::GenerateMocFiles(
   }
   {
     cmsys::ofstream outfile;
-    outfile.open(this->OutMocCppFilename.c_str(), std::ios::trunc);
+    outfile.open(this->OutMocCppFilenameAbs.c_str(), std::ios::trunc);
     outfile << automocSource;
     outfile.close();
   }
@@ -1105,7 +1119,7 @@ bool cmQtAutoGenerators::GenerateMoc(const std::string& sourceFile,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: error: process for " << mocFilePath << " failed:\n"
           << output << std::endl;
       this->LogError(err.str());
@@ -1146,7 +1160,7 @@ bool cmQtAutoGenerators::GenerateUiFiles(
   {
     std::multimap<std::string, std::string> collisions;
     if (this->NameCollisionTest(testMap, collisions)) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: error: The same ui_NAME.h file will be generated "
              "from different sources."
           << std::endl
@@ -1184,7 +1198,7 @@ bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
     cmsys::SystemTools::MakeDirectory(this->Builddir.c_str());
   }
 
-  const ::std::string uiBuildFile = this->Builddir + uiOutputFile;
+  const std::string uiBuildFile = this->Builddir + uiOutputFile;
 
   int sourceNewerThanUi = 0;
   bool success = cmsys::SystemTools::FileTimeCompare(uiInputFile, uiBuildFile,
@@ -1222,7 +1236,7 @@ bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOUIC: error: process for " << uiOutputFile
           << " needed by\n \"" << realName << "\"\nfailed:\n"
           << output << std::endl;
@@ -1256,15 +1270,18 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
 {
   // generate single map with input / output names
   std::map<std::string, std::string> qrcGenMap;
-  for (std::vector<std::string>::const_iterator si = this->RccSources.begin();
-       si != this->RccSources.end(); ++si) {
-    const std::string ext = cmsys::SystemTools::GetFilenameLastExtension(*si);
-    if (ext == ".qrc") {
-      std::string basename =
-        cmsys::SystemTools::GetFilenameWithoutLastExtension(*si);
-      std::string qrcOutputFile = "CMakeFiles/" + this->OriginTargetName +
-        ".dir/qrc_" + basename + ".cpp";
-      qrcGenMap[*si] = qrcOutputFile;
+  {
+    cmFilePathUuid fpathUuid(this->Srcdir, this->Builddir,
+                             this->ProjectSourceDir, this->ProjectBinaryDir);
+    for (std::vector<std::string>::const_iterator si =
+           this->RccSources.begin();
+         si != this->RccSources.end(); ++si) {
+      const std::string ext =
+        cmsys::SystemTools::GetFilenameLastExtension(*si);
+      if (ext == ".qrc") {
+        qrcGenMap[*si] =
+          (this->TargetBuildSubDir + fpathUuid.get(*si, "qrc_", ".cpp"));
+      }
     }
   }
 
@@ -1272,7 +1289,7 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
   {
     std::multimap<std::string, std::string> collisions;
     if (this->NameCollisionTest(qrcGenMap, collisions)) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTOGEN: error: The same qrc_NAME.cpp file"
              " will be generated from different sources."
           << std::endl
@@ -1286,7 +1303,8 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
   for (std::map<std::string, std::string>::const_iterator si =
          qrcGenMap.begin();
        si != qrcGenMap.end(); ++si) {
-    if (!this->GenerateQrc(si->first, si->second)) {
+    bool unique = FileNameIsUnique(si->first, qrcGenMap);
+    if (!this->GenerateQrc(si->first, si->second, unique)) {
       if (this->RunRccFailed) {
         return false;
       }
@@ -1296,11 +1314,24 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
 }
 
 bool cmQtAutoGenerators::GenerateQrc(const std::string& qrcInputFile,
-                                     const std::string& qrcOutputFile)
+                                     const std::string& qrcOutputFile,
+                                     bool unique_n)
 {
-  const std::string basename =
-    cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcInputFile);
-  const ::std::string qrcBuildFile = this->Builddir + qrcOutputFile;
+  std::string symbolName;
+  if (unique_n) {
+    symbolName =
+      cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcInputFile);
+  } else {
+    symbolName =
+      cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcOutputFile);
+    // Remove "qrc_" at string begin
+    symbolName.erase(0, 4);
+  }
+  // Replace '-' with '_'. The former is valid for
+  // file names but not for symbol names.
+  std::replace(symbolName.begin(), symbolName.end(), '-', '_');
+
+  const std::string qrcBuildFile = this->Builddir + qrcOutputFile;
 
   int sourceNewerThanQrc = 0;
   bool generateQrc = !cmsys::SystemTools::FileTimeCompare(
@@ -1326,7 +1357,7 @@ bool cmQtAutoGenerators::GenerateQrc(const std::string& qrcInputFile,
     }
 
     command.push_back("-name");
-    command.push_back(basename);
+    command.push_back(symbolName);
     command.push_back("-o");
     command.push_back(qrcBuildFile);
     command.push_back(qrcInputFile);
@@ -1339,7 +1370,7 @@ bool cmQtAutoGenerators::GenerateQrc(const std::string& qrcInputFile,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::stringstream err;
+      std::ostringstream err;
       err << "AUTORCC: error: process for " << qrcOutputFile << " failed:\n"
           << output << std::endl;
       this->LogError(err.str());
@@ -1387,7 +1418,7 @@ void cmQtAutoGenerators::NameCollisionLog(
 {
   typedef std::multimap<std::string, std::string>::const_iterator Iter;
 
-  std::stringstream err;
+  std::ostringstream err;
   // Add message
   err << message;
   // Append collision list
@@ -1409,7 +1440,7 @@ void cmQtAutoGenerators::LogError(const std::string& message)
 
 void cmQtAutoGenerators::LogCommand(const std::vector<std::string>& command)
 {
-  std::stringstream sbuf;
+  std::ostringstream sbuf;
   for (std::vector<std::string>::const_iterator cmdIt = command.begin();
        cmdIt != command.end(); ++cmdIt) {
     if (cmdIt != command.begin()) {
diff --git a/Source/cmQtAutoGenerators.h b/Source/cmQtAutoGenerators.h
index 86913f0..08d7e03 100644
--- a/Source/cmQtAutoGenerators.h
+++ b/Source/cmQtAutoGenerators.h
@@ -1,23 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmQtAutoGenerators_h
 #define cmQtAutoGenerators_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <list>
 #include <map>
+#include <set>
 #include <string>
 #include <vector>
 
@@ -51,7 +41,8 @@ private:
                   const std::string& uiOutputFile);
   bool GenerateQrcFiles();
   bool GenerateQrc(const std::string& qrcInputFile,
-                   const std::string& qrcOutputFile);
+                   const std::string& qrcOutputFile, bool unique_n);
+
   void ParseCppFile(
     const std::string& absFilename,
     const std::vector<std::string>& headerExtensions,
@@ -123,8 +114,9 @@ private:
   std::string CurrentCompileSettingsStr;
   std::string OldCompileSettingsStr;
 
+  std::string TargetBuildSubDir;
   std::string OutMocCppFilenameRel;
-  std::string OutMocCppFilename;
+  std::string OutMocCppFilenameAbs;
   std::list<std::string> MocIncludes;
   std::list<std::string> MocDefinitions;
   std::vector<std::string> MocOptions;
diff --git a/Source/cmRST.cxx b/Source/cmRST.cxx
index 10d1cda..355b8c4 100644
--- a/Source/cmRST.cxx
+++ b/Source/cmRST.cxx
@@ -1,21 +1,17 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRST.h"
 
 #include "cmAlgorithms.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
+
+#include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <ctype.h>
+#include <iterator>
+#include <stddef.h>
+#include <utility>
 
 cmRST::cmRST(std::ostream& os, std::string const& docroot)
   : OS(os)
diff --git a/Source/cmRST.h b/Source/cmRST.h
index 0e379b6..2fedf4b 100644
--- a/Source/cmRST.h
+++ b/Source/cmRST.h
@@ -1,20 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef _cmRST_h
 #define _cmRST_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/RegularExpression.hxx>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
 /** \class cmRST
  * \brief Perform basic .rst processing for command-line help
diff --git a/Source/cmRemoveCommand.cxx b/Source/cmRemoveCommand.cxx
index 955f712..540f37f 100644
--- a/Source/cmRemoveCommand.cxx
+++ b/Source/cmRemoveCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRemoveCommand.h"
 
 // cmRemoveCommand
 bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmRemoveCommand.h b/Source/cmRemoveCommand.h
index c226a54..bf33de0 100644
--- a/Source/cmRemoveCommand.h
+++ b/Source/cmRemoveCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmRemoveCommand_h
 #define cmRemoveCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmRemoveCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmRemoveCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "remove"; }
+  std::string GetName() const CM_OVERRIDE { return "remove"; }
 
   cmTypeMacro(cmRemoveCommand, cmCommand);
 };
diff --git a/Source/cmRemoveDefinitionsCommand.cxx b/Source/cmRemoveDefinitionsCommand.cxx
index 638eda6..cae5072 100644
--- a/Source/cmRemoveDefinitionsCommand.cxx
+++ b/Source/cmRemoveDefinitionsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRemoveDefinitionsCommand.h"
 
 // cmRemoveDefinitionsCommand
@@ -16,7 +7,7 @@ bool cmRemoveDefinitionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
   // it is OK to have no arguments
-  if (args.size() < 1) {
+  if (args.empty()) {
     return true;
   }
 
diff --git a/Source/cmRemoveDefinitionsCommand.h b/Source/cmRemoveDefinitionsCommand.h
index b440307..016f5fd 100644
--- a/Source/cmRemoveDefinitionsCommand.h
+++ b/Source/cmRemoveDefinitionsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmRemoveDefinitionsCommand_h
 #define cmRemoveDefinitionsCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmRemoveDefinitionsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmRemoveDefinitionsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "remove_definitions"; }
+  std::string GetName() const CM_OVERRIDE { return "remove_definitions"; }
 
   cmTypeMacro(cmRemoveDefinitionsCommand, cmCommand);
 };
diff --git a/Source/cmReturnCommand.cxx b/Source/cmReturnCommand.cxx
index 1de649f..aa056c3 100644
--- a/Source/cmReturnCommand.cxx
+++ b/Source/cmReturnCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmReturnCommand.h"
 
 // cmReturnCommand
diff --git a/Source/cmReturnCommand.h b/Source/cmReturnCommand.h
index 44cd4c8..1159e78 100644
--- a/Source/cmReturnCommand.h
+++ b/Source/cmReturnCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmReturnCommand_h
 #define cmReturnCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmReturnCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmReturnCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "return"; }
+  std::string GetName() const CM_OVERRIDE { return "return"; }
 
   cmTypeMacro(cmReturnCommand, cmCommand);
 };
diff --git a/Source/cmScriptGenerator.cxx b/Source/cmScriptGenerator.cxx
index 5fed107..4c5ab64 100644
--- a/Source/cmScriptGenerator.cxx
+++ b/Source/cmScriptGenerator.cxx
@@ -1,25 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmScriptGenerator.h"
 
 #include "cmSystemTools.h"
 
+#include <cmConfigure.h>
+
 cmScriptGenerator::cmScriptGenerator(
   const std::string& config_var,
   std::vector<std::string> const& configurations)
   : RuntimeConfigVariable(config_var)
   , Configurations(configurations)
   , ConfigurationName("")
-  , ConfigurationTypes(0)
+  , ConfigurationTypes(CM_NULLPTR)
   , ActionsPerConfig(false)
 {
 }
@@ -36,7 +29,7 @@ void cmScriptGenerator::Generate(
   this->ConfigurationTypes = &configurationTypes;
   this->GenerateScript(os);
   this->ConfigurationName = "";
-  this->ConfigurationTypes = 0;
+  this->ConfigurationTypes = CM_NULLPTR;
 }
 
 static void cmScriptGeneratorEncodeConfig(const std::string& config,
@@ -117,9 +110,9 @@ void cmScriptGenerator::GenerateScriptActions(std::ostream& os,
   }
 }
 
-void cmScriptGenerator::GenerateScriptForConfig(std::ostream&,
-                                                const std::string&,
-                                                Indent const&)
+void cmScriptGenerator::GenerateScriptForConfig(std::ostream& /*unused*/,
+                                                const std::string& /*unused*/,
+                                                Indent const& /*unused*/)
 {
   // No actions for this generator.
 }
diff --git a/Source/cmScriptGenerator.h b/Source/cmScriptGenerator.h
index ef0766f..a8f6fae 100644
--- a/Source/cmScriptGenerator.h
+++ b/Source/cmScriptGenerator.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmScriptGenerator_h
 #define cmScriptGenerator_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <ostream>
+#include <string>
+#include <vector>
 
 class cmScriptGeneratorIndent
 {
diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx
index a0cce12..c34028e 100644
--- a/Source/cmSearchPath.cxx
+++ b/Source/cmSearchPath.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSearchPath.h"
 
 #include "cmAlgorithms.h"
@@ -45,7 +36,7 @@ void cmSearchPath::AddPath(const std::string& path)
 
 void cmSearchPath::AddUserPath(const std::string& path)
 {
-  assert(this->FC != NULL);
+  assert(this->FC != CM_NULLPTR);
 
   std::vector<std::string> outPaths;
 
@@ -80,7 +71,7 @@ void cmSearchPath::AddUserPath(const std::string& path)
 
 void cmSearchPath::AddCMakePath(const std::string& variable)
 {
-  assert(this->FC != NULL);
+  assert(this->FC != CM_NULLPTR);
 
   // Get a path from a CMake variable.
   if (const char* value = this->FC->Makefile->GetDefinition(variable)) {
@@ -107,7 +98,7 @@ void cmSearchPath::AddEnvPath(const std::string& variable)
 
 void cmSearchPath::AddCMakePrefixPath(const std::string& variable)
 {
-  assert(this->FC != NULL);
+  assert(this->FC != CM_NULLPTR);
 
   // Get a path from a CMake variable.
   if (const char* value = this->FC->Makefile->GetDefinition(variable)) {
@@ -124,9 +115,8 @@ static std::string cmSearchPathStripBin(std::string const& s)
   // If the path is a PREFIX/bin case then add its parent instead.
   if ((cmHasLiteralSuffix(s, "/bin")) || (cmHasLiteralSuffix(s, "/sbin"))) {
     return cmSystemTools::GetFilenamePath(s);
-  } else {
-    return s;
   }
+  return s;
 }
 
 void cmSearchPath::AddEnvPrefixPath(const std::string& variable, bool stripBin)
@@ -172,7 +162,7 @@ void cmSearchPath::AddSuffixes(const std::vector<std::string>& suffixes)
 void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths,
                                   const char* base)
 {
-  assert(this->FC != NULL);
+  assert(this->FC != CM_NULLPTR);
 
   // default for programs
   std::string subdir = "bin";
@@ -213,7 +203,7 @@ void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths,
 
 void cmSearchPath::AddPathInternal(const std::string& path, const char* base)
 {
-  assert(this->FC != NULL);
+  assert(this->FC != CM_NULLPTR);
 
   std::string collapsed = cmSystemTools::CollapseFullPath(path, base);
 
diff --git a/Source/cmSearchPath.h b/Source/cmSearchPath.h
index 835196f..80815ed 100644
--- a/Source/cmSearchPath.h
+++ b/Source/cmSearchPath.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSearchPath_h
 #define cmSearchPath_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmFindCommon;
@@ -28,7 +21,7 @@ public:
   // cmSearchPath must be initialized from a valid pointer.  The only reason
   // for the default is to allow it to be easily used in stl containers.
   // Attempting to initialize with a NULL value will fail an assertion
-  cmSearchPath(cmFindCommon* findCmd = 0);
+  cmSearchPath(cmFindCommon* findCmd = CM_NULLPTR);
   ~cmSearchPath();
 
   const std::vector<std::string>& GetPaths() const { return this->Paths; }
@@ -47,8 +40,8 @@ public:
 
 protected:
   void AddPrefixPaths(const std::vector<std::string>& paths,
-                      const char* base = 0);
-  void AddPathInternal(const std::string& path, const char* base = 0);
+                      const char* base = CM_NULLPTR);
+  void AddPathInternal(const std::string& path, const char* base = CM_NULLPTR);
 
   cmFindCommon* FC;
   std::vector<std::string> Paths;
diff --git a/Source/cmSeparateArgumentsCommand.cxx b/Source/cmSeparateArgumentsCommand.cxx
index 440b635..b5c3186 100644
--- a/Source/cmSeparateArgumentsCommand.cxx
+++ b/Source/cmSeparateArgumentsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSeparateArgumentsCommand.h"
 
 // cmSeparateArgumentsCommand
diff --git a/Source/cmSeparateArgumentsCommand.h b/Source/cmSeparateArgumentsCommand.h
index 47246c9..66fbef7 100644
--- a/Source/cmSeparateArgumentsCommand.h
+++ b/Source/cmSeparateArgumentsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSeparateArgumentsCommand_h
 #define cmSeparateArgumentsCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmSeparateArgumentsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSeparateArgumentsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "separate_arguments"; }
+  std::string GetName() const CM_OVERRIDE { return "separate_arguments"; }
 
   cmTypeMacro(cmSeparateArgumentsCommand, cmCommand);
 };
diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx
new file mode 100644
index 0000000..51a363f
--- /dev/null
+++ b/Source/cmServer.cxx
@@ -0,0 +1,379 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmServer.h"
+
+#include "cmServerConnection.h"
+#include "cmServerDictionary.h"
+#include "cmServerProtocol.h"
+#include "cmSystemTools.h"
+#include "cmVersionMacros.h"
+#include "cmake.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_jsoncpp_reader.h"
+#include "cm_jsoncpp_value.h"
+#endif
+
+#include <fstream>
+#include <iostream>
+#include <memory>
+
+class cmServer::DebugInfo
+{
+public:
+  DebugInfo()
+    : StartTime(uv_hrtime())
+  {
+  }
+
+  bool PrintStatistics = false;
+
+  std::string OutputFile;
+  uint64_t StartTime;
+};
+
+cmServer::cmServer(cmServerConnection* conn, bool supportExperimental)
+  : Connection(conn)
+  , SupportExperimental(supportExperimental)
+{
+  this->Connection->SetServer(this);
+  // Register supported protocols:
+  this->RegisterProtocol(new cmServerProtocol1_0);
+}
+
+cmServer::~cmServer()
+{
+  if (!this->Protocol) { // Server was never fully started!
+    return;
+  }
+
+  for (cmServerProtocol* p : this->SupportedProtocols) {
+    delete p;
+  }
+
+  delete this->Connection;
+}
+
+void cmServer::PopOne()
+{
+  if (this->Queue.empty()) {
+    return;
+  }
+
+  Json::Reader reader;
+  Json::Value value;
+  const std::string input = this->Queue.front();
+  this->Queue.erase(this->Queue.begin());
+
+  if (!reader.parse(input, value)) {
+    this->WriteParseError("Failed to parse JSON input.");
+    return;
+  }
+
+  std::unique_ptr<DebugInfo> debug;
+  Json::Value debugValue = value["debug"];
+  if (!debugValue.isNull()) {
+    debug = std::make_unique<DebugInfo>();
+    debug->OutputFile = debugValue["dumpToFile"].asString();
+    debug->PrintStatistics = debugValue["showStats"].asBool();
+  }
+
+  const cmServerRequest request(this, value[kTYPE_KEY].asString(),
+                                value[kCOOKIE_KEY].asString(), value);
+
+  if (request.Type == "") {
+    cmServerResponse response(request);
+    response.SetError("No type given in request.");
+    this->WriteResponse(response, nullptr);
+    return;
+  }
+
+  cmSystemTools::SetMessageCallback(reportMessage,
+                                    const_cast<cmServerRequest*>(&request));
+  if (this->Protocol) {
+    this->Protocol->CMakeInstance()->SetProgressCallback(
+      reportProgress, const_cast<cmServerRequest*>(&request));
+    this->WriteResponse(this->Protocol->Process(request), debug.get());
+  } else {
+    this->WriteResponse(this->SetProtocolVersion(request), debug.get());
+  }
+}
+
+void cmServer::RegisterProtocol(cmServerProtocol* protocol)
+{
+  if (protocol->IsExperimental() && !this->SupportExperimental) {
+    return;
+  }
+  auto version = protocol->ProtocolVersion();
+  assert(version.first >= 0);
+  assert(version.second >= 0);
+  auto it = std::find_if(this->SupportedProtocols.begin(),
+                         this->SupportedProtocols.end(),
+                         [version](cmServerProtocol* p) {
+                           return p->ProtocolVersion() == version;
+                         });
+  if (it == this->SupportedProtocols.end()) {
+    this->SupportedProtocols.push_back(protocol);
+  }
+}
+
+void cmServer::PrintHello() const
+{
+  Json::Value hello = Json::objectValue;
+  hello[kTYPE_KEY] = "hello";
+
+  Json::Value& protocolVersions = hello[kSUPPORTED_PROTOCOL_VERSIONS] =
+    Json::arrayValue;
+
+  for (auto const& proto : this->SupportedProtocols) {
+    auto version = proto->ProtocolVersion();
+    Json::Value tmp = Json::objectValue;
+    tmp[kMAJOR_KEY] = version.first;
+    tmp[kMINOR_KEY] = version.second;
+    if (proto->IsExperimental()) {
+      tmp[kIS_EXPERIMENTAL_KEY] = true;
+    }
+    protocolVersions.append(tmp);
+  }
+
+  this->WriteJsonObject(hello, nullptr);
+}
+
+void cmServer::QueueRequest(const std::string& request)
+{
+  this->Queue.push_back(request);
+  this->PopOne();
+}
+
+void cmServer::reportProgress(const char* msg, float progress, void* data)
+{
+  const cmServerRequest* request = static_cast<const cmServerRequest*>(data);
+  assert(request);
+  if (progress < 0.0 || progress > 1.0) {
+    request->ReportMessage(msg, "");
+  } else {
+    request->ReportProgress(0, static_cast<int>(progress * 1000), 1000, msg);
+  }
+}
+
+void cmServer::reportMessage(const char* msg, const char* title,
+                             bool& /* cancel */, void* data)
+{
+  const cmServerRequest* request = static_cast<const cmServerRequest*>(data);
+  assert(request);
+  assert(msg);
+  std::string titleString;
+  if (title) {
+    titleString = title;
+  }
+  request->ReportMessage(std::string(msg), titleString);
+}
+
+cmServerResponse cmServer::SetProtocolVersion(const cmServerRequest& request)
+{
+  if (request.Type != kHANDSHAKE_TYPE) {
+    return request.ReportError("Waiting for type \"" + kHANDSHAKE_TYPE +
+                               "\".");
+  }
+
+  Json::Value requestedProtocolVersion = request.Data[kPROTOCOL_VERSION_KEY];
+  if (requestedProtocolVersion.isNull()) {
+    return request.ReportError("\"" + kPROTOCOL_VERSION_KEY +
+                               "\" is required for \"" + kHANDSHAKE_TYPE +
+                               "\".");
+  }
+
+  if (!requestedProtocolVersion.isObject()) {
+    return request.ReportError("\"" + kPROTOCOL_VERSION_KEY +
+                               "\" must be a JSON object.");
+  }
+
+  Json::Value majorValue = requestedProtocolVersion[kMAJOR_KEY];
+  if (!majorValue.isInt()) {
+    return request.ReportError("\"" + kMAJOR_KEY +
+                               "\" must be set and an integer.");
+  }
+
+  Json::Value minorValue = requestedProtocolVersion[kMINOR_KEY];
+  if (!minorValue.isNull() && !minorValue.isInt()) {
+    return request.ReportError("\"" + kMINOR_KEY +
+                               "\" must be unset or an integer.");
+  }
+
+  const int major = majorValue.asInt();
+  const int minor = minorValue.isNull() ? -1 : minorValue.asInt();
+  if (major < 0) {
+    return request.ReportError("\"" + kMAJOR_KEY + "\" must be >= 0.");
+  }
+  if (!minorValue.isNull() && minor < 0) {
+    return request.ReportError("\"" + kMINOR_KEY +
+                               "\" must be >= 0 when set.");
+  }
+
+  this->Protocol =
+    this->FindMatchingProtocol(this->SupportedProtocols, major, minor);
+  if (!this->Protocol) {
+    return request.ReportError("Protocol version not supported.");
+  }
+
+  std::string errorMessage;
+  if (!this->Protocol->Activate(this, request, &errorMessage)) {
+    this->Protocol = CM_NULLPTR;
+    return request.ReportError("Failed to activate protocol version: " +
+                               errorMessage);
+  }
+  return request.Reply(Json::objectValue);
+}
+
+bool cmServer::Serve(std::string* errorMessage)
+{
+  if (this->SupportedProtocols.empty()) {
+    *errorMessage =
+      "No protocol versions defined. Maybe you need --experimental?";
+    return false;
+  }
+  assert(!this->Protocol);
+
+  return Connection->ProcessEvents(errorMessage);
+}
+
+cmFileMonitor* cmServer::FileMonitor() const
+{
+  return Connection->FileMonitor();
+}
+
+void cmServer::WriteJsonObject(const Json::Value& jsonValue,
+                               const DebugInfo* debug) const
+{
+  Json::FastWriter writer;
+
+  auto beforeJson = uv_hrtime();
+  std::string result = writer.write(jsonValue);
+
+  if (debug) {
+    Json::Value copy = jsonValue;
+    if (debug->PrintStatistics) {
+      Json::Value stats = Json::objectValue;
+      auto endTime = uv_hrtime();
+
+      stats["jsonSerialization"] = double(endTime - beforeJson) / 1000000.0;
+      stats["totalTime"] = double(endTime - debug->StartTime) / 1000000.0;
+      stats["size"] = static_cast<int>(result.size());
+      if (!debug->OutputFile.empty()) {
+        stats["dumpFile"] = debug->OutputFile;
+      }
+
+      copy["zzzDebug"] = stats;
+
+      result = writer.write(copy); // Update result to include debug info
+    }
+
+    if (!debug->OutputFile.empty()) {
+      std::ofstream myfile;
+      myfile.open(debug->OutputFile);
+      myfile << result;
+      myfile.close();
+    }
+  }
+
+  Connection->WriteData(std::string("\n") + kSTART_MAGIC + std::string("\n") +
+                        result + kEND_MAGIC + std::string("\n"));
+}
+
+cmServerProtocol* cmServer::FindMatchingProtocol(
+  const std::vector<cmServerProtocol*>& protocols, int major, int minor)
+{
+  cmServerProtocol* bestMatch = nullptr;
+  for (auto protocol : protocols) {
+    auto version = protocol->ProtocolVersion();
+    if (major != version.first) {
+      continue;
+    }
+    if (minor == version.second) {
+      return protocol;
+    }
+    if (!bestMatch || bestMatch->ProtocolVersion().second < version.second) {
+      bestMatch = protocol;
+    }
+  }
+  return minor < 0 ? bestMatch : nullptr;
+}
+
+void cmServer::WriteProgress(const cmServerRequest& request, int min,
+                             int current, int max,
+                             const std::string& message) const
+{
+  assert(min <= current && current <= max);
+  assert(message.length() != 0);
+
+  Json::Value obj = Json::objectValue;
+  obj[kTYPE_KEY] = kPROGRESS_TYPE;
+  obj[kREPLY_TO_KEY] = request.Type;
+  obj[kCOOKIE_KEY] = request.Cookie;
+  obj[kPROGRESS_MESSAGE_KEY] = message;
+  obj[kPROGRESS_MINIMUM_KEY] = min;
+  obj[kPROGRESS_MAXIMUM_KEY] = max;
+  obj[kPROGRESS_CURRENT_KEY] = current;
+
+  this->WriteJsonObject(obj, nullptr);
+}
+
+void cmServer::WriteMessage(const cmServerRequest& request,
+                            const std::string& message,
+                            const std::string& title) const
+{
+  if (message.empty()) {
+    return;
+  }
+
+  Json::Value obj = Json::objectValue;
+  obj[kTYPE_KEY] = kMESSAGE_TYPE;
+  obj[kREPLY_TO_KEY] = request.Type;
+  obj[kCOOKIE_KEY] = request.Cookie;
+  obj[kMESSAGE_KEY] = message;
+  if (!title.empty()) {
+    obj[kTITLE_KEY] = title;
+  }
+
+  WriteJsonObject(obj, nullptr);
+}
+
+void cmServer::WriteParseError(const std::string& message) const
+{
+  Json::Value obj = Json::objectValue;
+  obj[kTYPE_KEY] = kERROR_TYPE;
+  obj[kERROR_MESSAGE_KEY] = message;
+  obj[kREPLY_TO_KEY] = "";
+  obj[kCOOKIE_KEY] = "";
+
+  this->WriteJsonObject(obj, nullptr);
+}
+
+void cmServer::WriteSignal(const std::string& name,
+                           const Json::Value& data) const
+{
+  assert(data.isObject());
+  Json::Value obj = data;
+  obj[kTYPE_KEY] = kSIGNAL_TYPE;
+  obj[kREPLY_TO_KEY] = "";
+  obj[kCOOKIE_KEY] = "";
+  obj[kNAME_KEY] = name;
+
+  WriteJsonObject(obj, nullptr);
+}
+
+void cmServer::WriteResponse(const cmServerResponse& response,
+                             const DebugInfo* debug) const
+{
+  assert(response.IsComplete());
+
+  Json::Value obj = response.Data();
+  obj[kCOOKIE_KEY] = response.Cookie;
+  obj[kTYPE_KEY] = response.IsError() ? kERROR_TYPE : kREPLY_TYPE;
+  obj[kREPLY_TO_KEY] = response.Type;
+  if (response.IsError()) {
+    obj[kERROR_MESSAGE_KEY] = response.ErrorMessage();
+  }
+
+  this->WriteJsonObject(obj, debug);
+}
diff --git a/Source/cmServer.h b/Source/cmServer.h
new file mode 100644
index 0000000..7f29e32
--- /dev/null
+++ b/Source/cmServer.h
@@ -0,0 +1,94 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#pragma once
+
+#include "cmListFileCache.h"
+#include "cmState.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_jsoncpp_value.h"
+#include "cm_uv.h"
+#endif
+
+#include <string>
+#include <vector>
+
+class cmFileMonitor;
+class cmServerConnection;
+class cmServerProtocol;
+class cmServerRequest;
+class cmServerResponse;
+
+class cmServer
+{
+public:
+  class DebugInfo;
+
+  cmServer(cmServerConnection* conn, bool supportExperimental);
+  ~cmServer();
+
+  bool Serve(std::string* errorMessage);
+
+  cmFileMonitor* FileMonitor() const;
+
+private:
+  void RegisterProtocol(cmServerProtocol* protocol);
+
+  // Callbacks from cmServerConnection:
+  void PopOne();
+  void QueueRequest(const std::string& request);
+
+  static void reportProgress(const char* msg, float progress, void* data);
+  static void reportMessage(const char* msg, const char* title, bool& cancel,
+                            void* data);
+
+  // Handle requests:
+  cmServerResponse SetProtocolVersion(const cmServerRequest& request);
+
+  void PrintHello() const;
+
+  // Write responses:
+  void WriteProgress(const cmServerRequest& request, int min, int current,
+                     int max, const std::string& message) const;
+  void WriteMessage(const cmServerRequest& request, const std::string& message,
+                    const std::string& title) const;
+  void WriteResponse(const cmServerResponse& response,
+                     const DebugInfo* debug) const;
+  void WriteParseError(const std::string& message) const;
+  void WriteSignal(const std::string& name, const Json::Value& obj) const;
+
+  void WriteJsonObject(Json::Value const& jsonValue,
+                       const DebugInfo* debug) const;
+
+  static cmServerProtocol* FindMatchingProtocol(
+    const std::vector<cmServerProtocol*>& protocols, int major, int minor);
+
+  cmServerConnection* Connection = nullptr;
+  const bool SupportExperimental;
+
+  cmServerProtocol* Protocol = nullptr;
+  std::vector<cmServerProtocol*> SupportedProtocols;
+  std::vector<std::string> Queue;
+
+  std::string DataBuffer;
+  std::string JsonData;
+
+  uv_loop_t* Loop = nullptr;
+
+  typedef union
+  {
+    uv_tty_t tty;
+    uv_pipe_t pipe;
+  } InOutUnion;
+
+  InOutUnion Input;
+  InOutUnion Output;
+  uv_stream_t* InputStream = nullptr;
+  uv_stream_t* OutputStream = nullptr;
+
+  mutable bool Writing = false;
+
+  friend class cmServerConnection;
+  friend class cmServerProtocol;
+  friend class cmServerRequest;
+};
diff --git a/Source/cmServerConnection.cxx b/Source/cmServerConnection.cxx
new file mode 100644
index 0000000..b4af52b
--- /dev/null
+++ b/Source/cmServerConnection.cxx
@@ -0,0 +1,377 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmServerConnection.h"
+
+#include "cmServerDictionary.h"
+
+#include "cmFileMonitor.h"
+#include "cmServer.h"
+
+#include <assert.h>
+
+namespace {
+
+struct write_req_t
+{
+  uv_write_t req;
+  uv_buf_t buf;
+};
+
+void on_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
+{
+  (void)(handle);
+  char* rawBuffer = new char[suggested_size];
+  *buf = uv_buf_init(rawBuffer, static_cast<unsigned int>(suggested_size));
+}
+
+void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
+{
+  auto conn = reinterpret_cast<cmServerConnection*>(stream->data);
+  if (nread >= 0) {
+    conn->ReadData(std::string(buf->base, buf->base + nread));
+  } else {
+    conn->TriggerShutdown();
+  }
+
+  delete[](buf->base);
+}
+
+void on_write(uv_write_t* req, int status)
+{
+  (void)(status);
+  auto conn = reinterpret_cast<cmServerConnection*>(req->data);
+
+  // Free req and buffer
+  write_req_t* wr = reinterpret_cast<write_req_t*>(req);
+  delete[](wr->buf.base);
+  delete wr;
+
+  conn->ProcessNextRequest();
+}
+
+void on_new_connection(uv_stream_t* stream, int status)
+{
+  (void)(status);
+  auto conn = reinterpret_cast<cmServerConnection*>(stream->data);
+  conn->Connect(stream);
+}
+
+void on_signal(uv_signal_t* signal, int signum)
+{
+  auto conn = reinterpret_cast<cmServerConnection*>(signal->data);
+  (void)(signum);
+  conn->TriggerShutdown();
+}
+
+void on_signal_close(uv_handle_t* handle)
+{
+  delete reinterpret_cast<uv_signal_t*>(handle);
+}
+
+void on_pipe_close(uv_handle_t* handle)
+{
+  delete reinterpret_cast<uv_pipe_t*>(handle);
+}
+
+void on_tty_close(uv_handle_t* handle)
+{
+  delete reinterpret_cast<uv_tty_t*>(handle);
+}
+
+} // namespace
+
+class LoopGuard
+{
+public:
+  LoopGuard(cmServerConnection* connection)
+    : Connection(connection)
+  {
+    this->Connection->mLoop = uv_default_loop();
+    if (!this->Connection->mLoop) {
+      return;
+    }
+    this->Connection->mFileMonitor =
+      new cmFileMonitor(this->Connection->mLoop);
+  }
+
+  ~LoopGuard()
+  {
+    if (!this->Connection->mLoop) {
+      return;
+    }
+
+    if (this->Connection->mFileMonitor) {
+      delete this->Connection->mFileMonitor;
+    }
+    uv_loop_close(this->Connection->mLoop);
+    this->Connection->mLoop = nullptr;
+  }
+
+private:
+  cmServerConnection* Connection;
+};
+
+cmServerConnection::cmServerConnection()
+{
+}
+
+cmServerConnection::~cmServerConnection()
+{
+}
+
+void cmServerConnection::SetServer(cmServer* s)
+{
+  this->Server = s;
+}
+
+bool cmServerConnection::ProcessEvents(std::string* errorMessage)
+{
+  assert(this->Server);
+  errorMessage->clear();
+
+  this->RawReadBuffer.clear();
+  this->RequestBuffer.clear();
+
+  LoopGuard guard(this);
+  (void)(guard);
+  if (!this->mLoop) {
+    *errorMessage = "Internal Error: Failed to create event loop.";
+    return false;
+  }
+
+  this->SIGINTHandler = new uv_signal_t;
+  uv_signal_init(this->mLoop, this->SIGINTHandler);
+  this->SIGINTHandler->data = static_cast<void*>(this);
+  uv_signal_start(this->SIGINTHandler, &on_signal, SIGINT);
+
+  this->SIGHUPHandler = new uv_signal_t;
+  uv_signal_init(this->mLoop, this->SIGHUPHandler);
+  this->SIGHUPHandler->data = static_cast<void*>(this);
+  uv_signal_start(this->SIGHUPHandler, &on_signal, SIGHUP);
+
+  if (!DoSetup(errorMessage)) {
+    return false;
+  }
+
+  if (uv_run(this->mLoop, UV_RUN_DEFAULT) != 0) {
+    *errorMessage = "Internal Error: Event loop stopped in unclean state.";
+    return false;
+  }
+
+  // These need to be cleaned up by now:
+  assert(!this->ReadStream);
+  assert(!this->WriteStream);
+
+  this->RawReadBuffer.clear();
+  this->RequestBuffer.clear();
+
+  return true;
+}
+
+void cmServerConnection::ReadData(const std::string& data)
+{
+  this->RawReadBuffer += data;
+
+  for (;;) {
+    auto needle = this->RawReadBuffer.find('\n');
+
+    if (needle == std::string::npos) {
+      return;
+    }
+    std::string line = this->RawReadBuffer.substr(0, needle);
+    const auto ls = line.size();
+    if (ls > 1 && line.at(ls - 1) == '\r') {
+      line.erase(ls - 1, 1);
+    }
+    this->RawReadBuffer.erase(this->RawReadBuffer.begin(),
+                              this->RawReadBuffer.begin() +
+                                static_cast<long>(needle) + 1);
+    if (line == kSTART_MAGIC) {
+      this->RequestBuffer.clear();
+      continue;
+    }
+    if (line == kEND_MAGIC) {
+      this->Server->QueueRequest(this->RequestBuffer);
+      this->RequestBuffer.clear();
+    } else {
+      this->RequestBuffer += line;
+      this->RequestBuffer += "\n";
+    }
+  }
+}
+
+void cmServerConnection::TriggerShutdown()
+{
+  this->FileMonitor()->StopMonitoring();
+
+  uv_signal_stop(this->SIGINTHandler);
+  uv_signal_stop(this->SIGHUPHandler);
+
+  uv_close(reinterpret_cast<uv_handle_t*>(this->SIGINTHandler),
+           &on_signal_close); // delete handle
+  uv_close(reinterpret_cast<uv_handle_t*>(this->SIGHUPHandler),
+           &on_signal_close); // delete handle
+
+  this->SIGINTHandler = nullptr;
+  this->SIGHUPHandler = nullptr;
+
+  this->TearDown();
+}
+
+void cmServerConnection::WriteData(const std::string& data)
+{
+  assert(this->WriteStream);
+
+  auto ds = data.size();
+
+  write_req_t* req = new write_req_t;
+  req->req.data = this;
+  req->buf = uv_buf_init(new char[ds], static_cast<unsigned int>(ds));
+  memcpy(req->buf.base, data.c_str(), ds);
+
+  uv_write(reinterpret_cast<uv_write_t*>(req),
+           static_cast<uv_stream_t*>(this->WriteStream), &req->buf, 1,
+           on_write);
+}
+
+void cmServerConnection::ProcessNextRequest()
+{
+  Server->PopOne();
+}
+
+void cmServerConnection::SendGreetings()
+{
+  Server->PrintHello();
+}
+
+cmServerStdIoConnection::cmServerStdIoConnection()
+{
+  this->Input.tty = nullptr;
+  this->Output.tty = nullptr;
+}
+
+bool cmServerStdIoConnection::DoSetup(std::string* errorMessage)
+{
+  (void)(errorMessage);
+
+  if (uv_guess_handle(1) == UV_TTY) {
+    usesTty = true;
+    this->Input.tty = new uv_tty_t;
+    uv_tty_init(this->Loop(), this->Input.tty, 0, 1);
+    uv_tty_set_mode(this->Input.tty, UV_TTY_MODE_NORMAL);
+    Input.tty->data = this;
+    this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.tty);
+
+    this->Output.tty = new uv_tty_t;
+    uv_tty_init(this->Loop(), this->Output.tty, 1, 0);
+    uv_tty_set_mode(this->Output.tty, UV_TTY_MODE_NORMAL);
+    Output.tty->data = this;
+    this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.tty);
+  } else {
+    usesTty = false;
+    this->Input.pipe = new uv_pipe_t;
+    uv_pipe_init(this->Loop(), this->Input.pipe, 0);
+    uv_pipe_open(this->Input.pipe, 0);
+    Input.pipe->data = this;
+    this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.pipe);
+
+    this->Output.pipe = new uv_pipe_t;
+    uv_pipe_init(this->Loop(), this->Output.pipe, 0);
+    uv_pipe_open(this->Output.pipe, 1);
+    Output.pipe->data = this;
+    this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.pipe);
+  }
+
+  SendGreetings();
+  uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
+
+  return true;
+}
+
+void cmServerStdIoConnection::TearDown()
+{
+  if (usesTty) {
+    uv_close(reinterpret_cast<uv_handle_t*>(this->Input.tty), &on_tty_close);
+    uv_close(reinterpret_cast<uv_handle_t*>(this->Output.tty), &on_tty_close);
+    this->Input.tty = nullptr;
+    this->Output.tty = nullptr;
+  } else {
+    uv_close(reinterpret_cast<uv_handle_t*>(this->Input.pipe), &on_pipe_close);
+    uv_close(reinterpret_cast<uv_handle_t*>(this->Output.pipe),
+             &on_pipe_close);
+    this->Input.pipe = nullptr;
+    this->Input.pipe = nullptr;
+  }
+  this->ReadStream = nullptr;
+  this->WriteStream = nullptr;
+}
+
+cmServerPipeConnection::cmServerPipeConnection(const std::string& name)
+  : PipeName(name)
+{
+}
+
+bool cmServerPipeConnection::DoSetup(std::string* errorMessage)
+{
+  this->ServerPipe = new uv_pipe_t;
+  uv_pipe_init(this->Loop(), this->ServerPipe, 0);
+  this->ServerPipe->data = this;
+
+  int r;
+  if ((r = uv_pipe_bind(this->ServerPipe, this->PipeName.c_str())) != 0) {
+    *errorMessage = std::string("Internal Error with ") + this->PipeName +
+      ": " + uv_err_name(r);
+    return false;
+  }
+  auto serverStream = reinterpret_cast<uv_stream_t*>(this->ServerPipe);
+  if ((r = uv_listen(serverStream, 1, on_new_connection)) != 0) {
+    *errorMessage = std::string("Internal Error listening on ") +
+      this->PipeName + ": " + uv_err_name(r);
+    return false;
+  }
+
+  return true;
+}
+
+void cmServerPipeConnection::TearDown()
+{
+  if (this->ClientPipe) {
+    uv_close(reinterpret_cast<uv_handle_t*>(this->ClientPipe), &on_pipe_close);
+    this->WriteStream->data = nullptr;
+  }
+  uv_close(reinterpret_cast<uv_handle_t*>(this->ServerPipe), &on_pipe_close);
+
+  this->ClientPipe = nullptr;
+  this->ServerPipe = nullptr;
+  this->WriteStream = nullptr;
+  this->ReadStream = nullptr;
+}
+
+void cmServerPipeConnection::Connect(uv_stream_t* server)
+{
+  if (this->ClientPipe) {
+    // Accept and close all pipes but the first:
+    uv_pipe_t* rejectPipe = new uv_pipe_t;
+
+    uv_pipe_init(this->Loop(), rejectPipe, 0);
+    auto rejecter = reinterpret_cast<uv_stream_t*>(rejectPipe);
+    uv_accept(server, rejecter);
+    uv_close(reinterpret_cast<uv_handle_t*>(rejecter), &on_pipe_close);
+    return;
+  }
+
+  this->ClientPipe = new uv_pipe_t;
+  uv_pipe_init(this->Loop(), this->ClientPipe, 0);
+  this->ClientPipe->data = this;
+  auto client = reinterpret_cast<uv_stream_t*>(this->ClientPipe);
+  if (uv_accept(server, client) != 0) {
+    uv_close(reinterpret_cast<uv_handle_t*>(client), nullptr);
+    return;
+  }
+  this->ReadStream = client;
+  this->WriteStream = client;
+
+  uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
+
+  this->SendGreetings();
+}
diff --git a/Source/cmServerConnection.h b/Source/cmServerConnection.h
new file mode 100644
index 0000000..3efe28d
--- /dev/null
+++ b/Source/cmServerConnection.h
@@ -0,0 +1,95 @@
+/* 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>
+#include <vector>
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_uv.h"
+#endif
+
+class cmServer;
+class cmFileMonitor;
+class LoopGuard;
+
+class cmServerConnection
+{
+public:
+  cmServerConnection();
+  virtual ~cmServerConnection();
+
+  void SetServer(cmServer* s);
+
+  bool ProcessEvents(std::string* errorMessage);
+
+  void ReadData(const std::string& data);
+  void TriggerShutdown();
+  void WriteData(const std::string& data);
+  void ProcessNextRequest();
+
+  virtual void Connect(uv_stream_t* server) { (void)(server); }
+
+  cmFileMonitor* FileMonitor() const { return this->mFileMonitor; }
+
+protected:
+  virtual bool DoSetup(std::string* errorMessage) = 0;
+  virtual void TearDown() = 0;
+
+  void SendGreetings();
+
+  uv_loop_t* Loop() const { return mLoop; }
+
+protected:
+  std::string RawReadBuffer;
+  std::string RequestBuffer;
+
+  uv_stream_t* ReadStream = nullptr;
+  uv_stream_t* WriteStream = nullptr;
+
+private:
+  uv_loop_t* mLoop = nullptr;
+  cmFileMonitor* mFileMonitor = nullptr;
+  cmServer* Server = nullptr;
+  uv_signal_t* SIGINTHandler = nullptr;
+  uv_signal_t* SIGHUPHandler = nullptr;
+
+  friend class LoopGuard;
+};
+
+class cmServerStdIoConnection : public cmServerConnection
+{
+public:
+  cmServerStdIoConnection();
+  bool DoSetup(std::string* errorMessage) override;
+
+  void TearDown() override;
+
+private:
+  typedef union
+  {
+    uv_tty_t* tty;
+    uv_pipe_t* pipe;
+  } InOutUnion;
+
+  bool usesTty = false;
+
+  InOutUnion Input;
+  InOutUnion Output;
+};
+
+class cmServerPipeConnection : public cmServerConnection
+{
+public:
+  cmServerPipeConnection(const std::string& name);
+  bool DoSetup(std::string* errorMessage) override;
+
+  void TearDown() override;
+
+  void Connect(uv_stream_t* server) override;
+
+private:
+  const std::string PipeName;
+  uv_pipe_t* ServerPipe = nullptr;
+  uv_pipe_t* ClientPipe = nullptr;
+};
diff --git a/Source/cmServerDictionary.h b/Source/cmServerDictionary.h
new file mode 100644
index 0000000..c82274a
--- /dev/null
+++ b/Source/cmServerDictionary.h
@@ -0,0 +1,94 @@
+/* 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 kDIRTY_SIGNAL = "dirty";
+static const std::string kFILE_CHANGE_SIGNAL = "fileChange";
+
+static const std::string kCACHE_TYPE = "cache";
+static const std::string kCMAKE_INPUTS_TYPE = "cmakeInputs";
+static const std::string kCODE_MODEL_TYPE = "codemodel";
+static const std::string kCOMPUTE_TYPE = "compute";
+static const std::string kCONFIGURE_TYPE = "configure";
+static const std::string kERROR_TYPE = "error";
+static const std::string kFILESYSTEM_WATCHERS_TYPE = "fileSystemWatchers";
+static const std::string kGLOBAL_SETTINGS_TYPE = "globalSettings";
+static const std::string kHANDSHAKE_TYPE = "handshake";
+static const std::string kMESSAGE_TYPE = "message";
+static const std::string kPROGRESS_TYPE = "progress";
+static const std::string kREPLY_TYPE = "reply";
+static const std::string kSET_GLOBAL_SETTINGS_TYPE = "setGlobalSettings";
+static const std::string kSIGNAL_TYPE = "signal";
+
+static const std::string kARTIFACTS_KEY = "artifacts";
+static const std::string kBUILD_DIRECTORY_KEY = "buildDirectory";
+static const std::string kBUILD_FILES_KEY = "buildFiles";
+static const std::string kCACHE_ARGUMENTS_KEY = "cacheArguments";
+static const std::string kCACHE_KEY = "cache";
+static const std::string kCAPABILITIES_KEY = "capabilities";
+static const std::string kCHECK_SYSTEM_VARS_KEY = "checkSystemVars";
+static const std::string kCMAKE_ROOT_DIRECTORY_KEY = "cmakeRootDirectory";
+static const std::string kCOMPILE_FLAGS_KEY = "compileFlags";
+static const std::string kCONFIGURATIONS_KEY = "configurations";
+static const std::string kCOOKIE_KEY = "cookie";
+static const std::string kDEBUG_OUTPUT_KEY = "debugOutput";
+static const std::string kDEFINES_KEY = "defines";
+static const std::string kERROR_MESSAGE_KEY = "errorMessage";
+static const std::string kEXTRA_GENERATOR_KEY = "extraGenerator";
+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 kGENERATOR_KEY = "generator";
+static const std::string kINCLUDE_PATH_KEY = "includePath";
+static const std::string kIS_CMAKE_KEY = "isCMake";
+static const std::string kIS_EXPERIMENTAL_KEY = "isExperimental";
+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 kKEYS_KEY = "keys";
+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 kMAJOR_KEY = "major";
+static const std::string kMESSAGE_KEY = "message";
+static const std::string kMINOR_KEY = "minor";
+static const std::string kNAME_KEY = "name";
+static const std::string kPATH_KEY = "path";
+static const std::string kPROGRESS_CURRENT_KEY = "progressCurrent";
+static const std::string kPROGRESS_MAXIMUM_KEY = "progressMaximum";
+static const std::string kPROGRESS_MESSAGE_KEY = "progressMessage";
+static const std::string kPROGRESS_MINIMUM_KEY = "progressMinimum";
+static const std::string kPROJECTS_KEY = "projects";
+static const std::string kPROPERTIES_KEY = "properties";
+static const std::string kPROTOCOL_VERSION_KEY = "protocolVersion";
+static const std::string kREPLY_TO_KEY = "inReplyTo";
+static const std::string kSOURCE_DIRECTORY_KEY = "sourceDirectory";
+static const std::string kSOURCES_KEY = "sources";
+static const std::string kSUPPORTED_PROTOCOL_VERSIONS =
+  "supportedProtocolVersions";
+static const std::string kSYSROOT_KEY = "sysroot";
+static const std::string kTARGETS_KEY = "targets";
+static const std::string kTITLE_KEY = "title";
+static const std::string kTRACE_EXPAND_KEY = "traceExpand";
+static const std::string kTRACE_KEY = "trace";
+static const std::string kTYPE_KEY = "type";
+static const std::string kVALUE_KEY = "value";
+static const std::string kWARN_UNINITIALIZED_KEY = "warnUninitialized";
+static const std::string kWARN_UNUSED_CLI_KEY = "warnUnusedCli";
+static const std::string kWARN_UNUSED_KEY = "warnUnused";
+static const std::string kWATCHED_DIRECTORIES_KEY = "watchedDirectories";
+static const std::string kWATCHED_FILES_KEY = "watchedFiles";
+
+static const std::string kSTART_MAGIC = "[== CMake Server ==[";
+static const std::string kEND_MAGIC = "]== CMake Server ==]";
+
+static const std::string kRENAME_PROPERTY_VALUE = "rename";
+static const std::string kCHANGE_PROPERTY_VALUE = "change";
diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx
new file mode 100644
index 0000000..a2bdf49
--- /dev/null
+++ b/Source/cmServerProtocol.cxx
@@ -0,0 +1,1077 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmServerProtocol.h"
+
+#include "cmCacheManager.h"
+#include "cmExternalMakefileProjectGenerator.h"
+#include "cmFileMonitor.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmListFileCache.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmServer.h"
+#include "cmServerDictionary.h"
+#include "cmSourceFile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include "cmServerDictionary.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_jsoncpp_reader.h"
+#include "cm_jsoncpp_value.h"
+#endif
+
+#include <algorithm>
+#include <string>
+#include <vector>
+
+// Get rid of some windows macros:
+#undef max
+
+namespace {
+
+static 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.push_back("");
+  return configurations;
+}
+
+static bool hasString(const Json::Value& v, const std::string& s)
+{
+  return !v.isNull() &&
+    std::find_if(v.begin(), v.end(), [s](const Json::Value& i) {
+      return i.asString() == s;
+    }) != v.end();
+}
+
+template <class T>
+static Json::Value fromStringList(const T& in)
+{
+  Json::Value result = Json::arrayValue;
+  for (const std::string& i : in) {
+    result.append(i);
+  }
+  return result;
+}
+
+static std::vector<std::string> toStringList(const Json::Value& in)
+{
+  std::vector<std::string> result;
+  for (const auto& it : in) {
+    result.push_back(it.asString());
+  }
+  return result;
+}
+
+static void getCMakeInputs(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() + '/';
+  const std::vector<cmMakefile*> makefiles = gg->GetMakefiles();
+  for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
+    const std::vector<std::string> listFiles = (*it)->GetListFiles();
+
+    for (auto jt = listFiles.begin(); jt != listFiles.end(); ++jt) {
+
+      const std::string startOfFile = jt->substr(0, cmakeRootDir.size());
+      const bool isInternal = (startOfFile == cmakeRootDir);
+      const bool isTemporary = !isInternal && (jt->find(buildDir + '/') == 0);
+
+      std::string toAdd = *jt;
+      if (!sourceDir.empty()) {
+        const std::string& relative =
+          cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str());
+        if (toAdd.size() > relative.size())
+          toAdd = relative;
+      }
+
+      if (isInternal) {
+        if (internalFiles)
+          internalFiles->push_back(toAdd);
+      } else {
+        if (isTemporary) {
+          if (tmpFiles)
+            tmpFiles->push_back(toAdd);
+        } else {
+          if (explicitFiles)
+            explicitFiles->push_back(toAdd);
+        }
+      }
+    }
+  }
+}
+
+} // namespace
+
+cmServerRequest::cmServerRequest(cmServer* server, const std::string& t,
+                                 const std::string& c, const Json::Value& d)
+  : Type(t)
+  , Cookie(c)
+  , Data(d)
+  , m_Server(server)
+{
+}
+
+void cmServerRequest::ReportProgress(int min, int current, int max,
+                                     const std::string& message) const
+{
+  this->m_Server->WriteProgress(*this, min, current, max, message);
+}
+
+void cmServerRequest::ReportMessage(const std::string& message,
+                                    const std::string& title) const
+{
+  m_Server->WriteMessage(*this, message, title);
+}
+
+cmServerResponse cmServerRequest::Reply(const Json::Value& data) const
+{
+  cmServerResponse response(*this);
+  response.SetData(data);
+  return response;
+}
+
+cmServerResponse cmServerRequest::ReportError(const std::string& message) const
+{
+  cmServerResponse response(*this);
+  response.SetError(message);
+  return response;
+}
+
+cmServerResponse::cmServerResponse(const cmServerRequest& request)
+  : Type(request.Type)
+  , Cookie(request.Cookie)
+{
+}
+
+void cmServerResponse::SetData(const Json::Value& data)
+{
+  assert(this->m_Payload == PAYLOAD_UNKNOWN);
+  if (!data[kCOOKIE_KEY].isNull() || !data[kTYPE_KEY].isNull()) {
+    this->SetError("Response contains cookie or type field.");
+    return;
+  }
+  this->m_Payload = PAYLOAD_DATA;
+  this->m_Data = data;
+}
+
+void cmServerResponse::SetError(const std::string& message)
+{
+  assert(this->m_Payload == PAYLOAD_UNKNOWN);
+  this->m_Payload = PAYLOAD_ERROR;
+  this->m_ErrorMessage = message;
+}
+
+bool cmServerResponse::IsComplete() const
+{
+  return this->m_Payload != PAYLOAD_UNKNOWN;
+}
+
+bool cmServerResponse::IsError() const
+{
+  assert(this->m_Payload != PAYLOAD_UNKNOWN);
+  return this->m_Payload == PAYLOAD_ERROR;
+}
+
+std::string cmServerResponse::ErrorMessage() const
+{
+  if (this->m_Payload == PAYLOAD_ERROR) {
+    return this->m_ErrorMessage;
+  }
+  return std::string();
+}
+
+Json::Value cmServerResponse::Data() const
+{
+  assert(this->m_Payload != PAYLOAD_UNKNOWN);
+  return this->m_Data;
+}
+
+bool cmServerProtocol::Activate(cmServer* server,
+                                const cmServerRequest& request,
+                                std::string* errorMessage)
+{
+  assert(server);
+  this->m_Server = server;
+  this->m_CMakeInstance = std::make_unique<cmake>();
+  const bool result = this->DoActivate(request, errorMessage);
+  if (!result) {
+    this->m_CMakeInstance = CM_NULLPTR;
+  }
+  return result;
+}
+
+cmFileMonitor* cmServerProtocol::FileMonitor() const
+{
+  return this->m_Server ? this->m_Server->FileMonitor() : nullptr;
+}
+
+void cmServerProtocol::SendSignal(const std::string& name,
+                                  const Json::Value& data) const
+{
+  if (this->m_Server) {
+    this->m_Server->WriteSignal(name, data);
+  }
+}
+
+cmake* cmServerProtocol::CMakeInstance() const
+{
+  return this->m_CMakeInstance.get();
+}
+
+bool cmServerProtocol::DoActivate(const cmServerRequest& /*request*/,
+                                  std::string* /*errorMessage*/)
+{
+  return true;
+}
+
+std::pair<int, int> cmServerProtocol1_0::ProtocolVersion() const
+{
+  return std::make_pair(1, 0);
+}
+
+bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
+                                     std::string* errorMessage)
+{
+  std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString();
+  const std::string buildDirectory =
+    request.Data[kBUILD_DIRECTORY_KEY].asString();
+  std::string generator = request.Data[kGENERATOR_KEY].asString();
+  std::string extraGenerator = request.Data[kEXTRA_GENERATOR_KEY].asString();
+
+  if (buildDirectory.empty()) {
+    if (errorMessage) {
+      *errorMessage =
+        std::string("\"") + kBUILD_DIRECTORY_KEY + "\" is missing.";
+    }
+    return false;
+  }
+  cmake* cm = CMakeInstance();
+  if (cmSystemTools::PathExists(buildDirectory)) {
+    if (!cmSystemTools::FileIsDirectory(buildDirectory)) {
+      if (errorMessage) {
+        *errorMessage = std::string("\"") + kBUILD_DIRECTORY_KEY +
+          "\" exists but is not a directory.";
+      }
+      return false;
+    }
+
+    const std::string cachePath = cm->FindCacheFile(buildDirectory);
+    if (cm->LoadCache(cachePath)) {
+      cmState* state = cm->GetState();
+
+      // Check generator:
+      const std::string cachedGenerator =
+        std::string(state->GetCacheEntryValue("CMAKE_GENERATOR"));
+      if (cachedGenerator.empty() && generator.empty()) {
+        if (errorMessage) {
+          *errorMessage =
+            std::string("\"") + kGENERATOR_KEY + "\" is required but unset.";
+        }
+        return false;
+      }
+      if (generator.empty()) {
+        generator = cachedGenerator;
+      }
+      if (generator != cachedGenerator) {
+        if (errorMessage) {
+          *errorMessage = std::string("\"") + kGENERATOR_KEY +
+            "\" set but incompatible with configured generator.";
+        }
+        return false;
+      }
+
+      // check extra generator:
+      const std::string cachedExtraGenerator =
+        std::string(state->GetCacheEntryValue("CMAKE_EXTRA_GENERATOR"));
+      if (!cachedExtraGenerator.empty() && !extraGenerator.empty() &&
+          cachedExtraGenerator != extraGenerator) {
+        if (errorMessage) {
+          *errorMessage = std::string("\"") + kEXTRA_GENERATOR_KEY +
+            "\" is set but incompatible with configured extra generator.";
+        }
+        return false;
+      }
+      if (extraGenerator.empty()) {
+        extraGenerator = cachedExtraGenerator;
+      }
+
+      // check sourcedir:
+      const std::string cachedSourceDirectory =
+        std::string(state->GetCacheEntryValue("CMAKE_HOME_DIRECTORY"));
+      if (!cachedSourceDirectory.empty() && !sourceDirectory.empty() &&
+          cachedSourceDirectory != sourceDirectory) {
+        if (errorMessage) {
+          *errorMessage = std::string("\"") + kSOURCE_DIRECTORY_KEY +
+            "\" is set but incompatible with configured source directory.";
+        }
+        return false;
+      }
+      if (sourceDirectory.empty()) {
+        sourceDirectory = cachedSourceDirectory;
+      }
+    }
+  }
+
+  if (sourceDirectory.empty()) {
+    if (errorMessage) {
+      *errorMessage = std::string("\"") + kSOURCE_DIRECTORY_KEY +
+        "\" is unset but required.";
+    }
+    return false;
+  }
+  if (!cmSystemTools::FileIsDirectory(sourceDirectory)) {
+    if (errorMessage) {
+      *errorMessage =
+        std::string("\"") + kSOURCE_DIRECTORY_KEY + "\" is not a directory.";
+    }
+    return false;
+  }
+  if (generator.empty()) {
+    if (errorMessage) {
+      *errorMessage =
+        std::string("\"") + kGENERATOR_KEY + "\" is unset but required.";
+    }
+    return false;
+  }
+
+  const std::string fullGeneratorName =
+    cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
+      generator, extraGenerator);
+
+  cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
+  if (!gg) {
+    if (errorMessage) {
+      *errorMessage =
+        std::string("Could not set up the requested combination of \"") +
+        kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"";
+    }
+    return false;
+  }
+
+  cm->SetGlobalGenerator(gg);
+  cm->SetHomeDirectory(sourceDirectory);
+  cm->SetHomeOutputDirectory(buildDirectory);
+
+  this->m_State = STATE_ACTIVE;
+  return true;
+}
+
+void cmServerProtocol1_0::HandleCMakeFileChanges(const std::string& path,
+                                                 int event, int status)
+{
+  assert(status == 0);
+  static_cast<void>(status);
+
+  if (!m_isDirty) {
+    m_isDirty = true;
+    SendSignal(kDIRTY_SIGNAL, Json::objectValue);
+  }
+  Json::Value obj = Json::objectValue;
+  obj[kPATH_KEY] = path;
+  Json::Value properties = Json::arrayValue;
+  if (event & UV_RENAME) {
+    properties.append(kRENAME_PROPERTY_VALUE);
+  }
+  if (event & UV_CHANGE) {
+    properties.append(kCHANGE_PROPERTY_VALUE);
+  }
+
+  obj[kPROPERTIES_KEY] = properties;
+  SendSignal(kFILE_CHANGE_SIGNAL, obj);
+}
+
+const cmServerResponse cmServerProtocol1_0::Process(
+  const cmServerRequest& request)
+{
+  assert(this->m_State >= STATE_ACTIVE);
+
+  if (request.Type == kCACHE_TYPE) {
+    return this->ProcessCache(request);
+  }
+  if (request.Type == kCMAKE_INPUTS_TYPE) {
+    return this->ProcessCMakeInputs(request);
+  }
+  if (request.Type == kCODE_MODEL_TYPE) {
+    return this->ProcessCodeModel(request);
+  }
+  if (request.Type == kCOMPUTE_TYPE) {
+    return this->ProcessCompute(request);
+  }
+  if (request.Type == kCONFIGURE_TYPE) {
+    return this->ProcessConfigure(request);
+  }
+  if (request.Type == kFILESYSTEM_WATCHERS_TYPE) {
+    return this->ProcessFileSystemWatchers(request);
+  }
+  if (request.Type == kGLOBAL_SETTINGS_TYPE) {
+    return this->ProcessGlobalSettings(request);
+  }
+  if (request.Type == kSET_GLOBAL_SETTINGS_TYPE) {
+    return this->ProcessSetGlobalSettings(request);
+  }
+
+  return request.ReportError("Unknown command!");
+}
+
+bool cmServerProtocol1_0::IsExperimental() const
+{
+  return true;
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessCache(
+  const cmServerRequest& request)
+{
+  if (this->m_State < STATE_CONFIGURED) {
+    return request.ReportError("This project was not configured yet.");
+  }
+
+  cmState* state = this->CMakeInstance()->GetState();
+
+  Json::Value result = Json::objectValue;
+
+  std::vector<std::string> allKeys = state->GetCacheEntryKeys();
+
+  Json::Value list = Json::arrayValue;
+  std::vector<std::string> keys = toStringList(request.Data[kKEYS_KEY]);
+  if (keys.empty()) {
+    keys = allKeys;
+  } else {
+    for (auto i : keys) {
+      if (std::find_if(allKeys.begin(), allKeys.end(),
+                       [i](const std::string& j) { return i == j; }) ==
+          allKeys.end()) {
+        return request.ReportError("Key \"" + i + "\" not found in cache.");
+      }
+    }
+  }
+  std::sort(keys.begin(), keys.end());
+  for (auto key : keys) {
+    Json::Value entry = Json::objectValue;
+    entry[kKEY_KEY] = key;
+    entry[kTYPE_KEY] =
+      cmState::CacheEntryTypeToString(state->GetCacheEntryType(key));
+    entry[kVALUE_KEY] = state->GetCacheEntryValue(key);
+
+    Json::Value props = Json::objectValue;
+    bool haveProperties = false;
+    for (auto prop : state->GetCacheEntryPropertyList(key)) {
+      haveProperties = true;
+      props[prop] = state->GetCacheEntryProperty(key, prop);
+    }
+    if (haveProperties) {
+      entry[kPROPERTIES_KEY] = props;
+    }
+
+    list.append(entry);
+  }
+
+  result[kCACHE_KEY] = list;
+  return request.Reply(result);
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessCMakeInputs(
+  const cmServerRequest& request)
+{
+  if (this->m_State < STATE_CONFIGURED) {
+    return request.ReportError("This instance was not yet configured.");
+  }
+
+  const cmake* cm = this->CMakeInstance();
+  const cmGlobalGenerator* gg = cm->GetGlobalGenerator();
+  const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot();
+  const std::string buildDir = cm->GetHomeOutputDirectory();
+  const std::string sourceDir = cm->GetHomeDirectory();
+
+  Json::Value result = Json::objectValue;
+  result[kSOURCE_DIRECTORY_KEY] = sourceDir;
+  result[kCMAKE_ROOT_DIRECTORY_KEY] = cmakeRootDir;
+
+  std::vector<std::string> internalFiles;
+  std::vector<std::string> explicitFiles;
+  std::vector<std::string> tmpFiles;
+  getCMakeInputs(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);
+
+  result[kBUILD_FILES_KEY] = array;
+
+  return request.Reply(result);
+}
+
+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;
+  for (auto i : defines) {
+    result.push_back(i);
+  }
+  std::sort(result.begin(), result.end());
+  Defines = 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 i : in.IncludePathList) {
+      result = result ^ (hash<std::string>()(i.first) ^
+                         (i.second ? std::numeric_limits<size_t>::max() : 0));
+    }
+    for (auto 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 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 i : files) {
+    const std::string relPath =
+      cmSystemTools::RelativePath(baseDir.c_str(), i.c_str());
+    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();
+
+      std::string compileFlags = ld.Flags;
+      lg->AppendFlags(compileFlags, file->GetProperty("COMPILE_FLAGS"));
+      fileData.Flags = compileFlags;
+
+      fileData.IncludePathList = ld.IncludePathList;
+
+      std::set<std::string> defines;
+      lg->AppendDefines(defines, file->GetProperty("COMPILE_DEFINITIONS"));
+      const std::string defPropName =
+        "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
+      lg->AppendDefines(defines, file->GetProperty(defPropName));
+      defines.insert(ld.Defines.begin(), ld.Defines.end());
+
+      fileData.SetDefines(defines);
+    }
+
+    fileData.IsGenerated = file->GetPropertyAsBool("GENERATED");
+    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 it = fileGroups.begin(); it != fileGroups.end(); ++it) {
+    Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
+    if (!group.isNull())
+      result.append(group);
+  }
+
+  return result;
+}
+
+static Json::Value DumpTarget(cmGeneratorTarget* target,
+                              const std::string& config)
+{
+  cmLocalGenerator* lg = target->GetLocalGenerator();
+  const cmState* state = lg->GetState();
+
+  const cmState::TargetType type = target->GetType();
+  const std::string typeName = state->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[kTYPE_KEY] = typeName;
+  result[kFULL_NAME_KEY] = target->GetFullName(config);
+  result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
+  result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
+
+  if (target->HaveWellDefinedOutputFiles()) {
+    Json::Value artifacts = Json::arrayValue;
+    artifacts.append(target->GetFullPath(config, false));
+    if (target->IsDLLPlatform()) {
+      artifacts.append(target->GetFullPath(config, true));
+      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;
+    lg->GetTargetFlags(config, linkLibs, linkLanguageFlags, linkFlags,
+                       frameworkPath, linkPath, target, false);
+
+    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 (auto 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, true);
+    for (auto i : includePathList) {
+      ld.IncludePathList.push_back(
+        std::make_pair(i, target->IsSystemIncludeDirectory(i, config)));
+    }
+  }
+
+  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 (const auto& lgIt : generators) {
+    auto list = lgIt->GetGeneratorTargets();
+    targetList.insert(targetList.end(), list.begin(), list.end());
+  }
+  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, const std::string 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;
+
+    assert(projectIt.second.size() >
+           0); // All Projects must have at least one local generator
+    const cmLocalGenerator* lg = projectIt.second.at(0);
+
+    // Project structure information:
+    const cmMakefile* mf = lg->GetMakefile();
+    pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory();
+    pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory();
+    pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config);
+
+    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 (const std::string& c : getConfigurations(cm)) {
+    result.append(DumpConfiguration(cm, c));
+  }
+
+  return result;
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessCodeModel(
+  const cmServerRequest& request)
+{
+  if (this->m_State != STATE_COMPUTED) {
+    return request.ReportError("No build system was generated yet.");
+  }
+
+  Json::Value result = Json::objectValue;
+  result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(this->CMakeInstance());
+  return request.Reply(result);
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessCompute(
+  const cmServerRequest& request)
+{
+  if (this->m_State > STATE_CONFIGURED) {
+    return request.ReportError("This build system was already generated.");
+  }
+  if (this->m_State < STATE_CONFIGURED) {
+    return request.ReportError("This project was not configured yet.");
+  }
+
+  cmake* cm = this->CMakeInstance();
+  int ret = cm->Generate();
+
+  if (ret < 0) {
+    return request.ReportError("Failed to compute build system.");
+  }
+  m_State = STATE_COMPUTED;
+  return request.Reply(Json::Value());
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessConfigure(
+  const cmServerRequest& request)
+{
+  if (this->m_State == STATE_INACTIVE) {
+    return request.ReportError("This instance is inactive.");
+  }
+
+  FileMonitor()->StopMonitoring();
+
+  // Make sure the types of cacheArguments matches (if given):
+  std::vector<std::string> cacheArgs;
+  bool cacheArgumentsError = false;
+  const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY];
+  if (!passedArgs.isNull()) {
+    if (passedArgs.isString()) {
+      cacheArgs.push_back(passedArgs.asString());
+    } else if (passedArgs.isArray()) {
+      for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) {
+        if (!i->isString()) {
+          cacheArgumentsError = true;
+          break;
+        }
+        cacheArgs.push_back(i->asString());
+      }
+    } else {
+      cacheArgumentsError = true;
+    }
+  }
+  if (cacheArgumentsError) {
+    request.ReportError(
+      "cacheArguments must be unset, a string or an array of strings.");
+  }
+
+  cmake* cm = this->CMakeInstance();
+  std::string sourceDir = cm->GetHomeDirectory();
+  const std::string buildDir = cm->GetHomeOutputDirectory();
+
+  cmGlobalGenerator* gg = cm->GetGlobalGenerator();
+
+  if (buildDir.empty()) {
+    return request.ReportError(
+      "No build directory set via setGlobalSettings.");
+  }
+
+  if (cm->LoadCache(buildDir)) {
+    // build directory has been set up before
+    const char* cachedSourceDir =
+      cm->GetState()->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
+    if (!cachedSourceDir) {
+      return request.ReportError("No CMAKE_HOME_DIRECTORY found in cache.");
+    }
+    if (sourceDir.empty()) {
+      sourceDir = std::string(cachedSourceDir);
+      cm->SetHomeDirectory(sourceDir);
+    }
+
+    const char* cachedGenerator =
+      cm->GetState()->GetInitializedCacheValue("CMAKE_GENERATOR");
+    if (cachedGenerator) {
+      if (gg && gg->GetName() != cachedGenerator) {
+        return request.ReportError("Configured generator does not match with "
+                                   "CMAKE_GENERATOR found in cache.");
+      }
+    }
+  } else {
+    // build directory has not been set up before
+    if (sourceDir.empty()) {
+      return request.ReportError("No sourceDirectory set via "
+                                 "setGlobalSettings and no cache found in "
+                                 "buildDirectory.");
+    }
+  }
+
+  if (cm->AddCMakePaths() != 1) {
+    return request.ReportError("Failed to set CMake paths.");
+  }
+
+  if (!cm->SetCacheArgs(cacheArgs)) {
+    return request.ReportError("cacheArguments could not be set.");
+  }
+
+  int ret = cm->Configure();
+  if (ret < 0) {
+    return request.ReportError("Configuration failed.");
+  }
+
+  std::vector<std::string> toWatchList;
+  getCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr);
+
+  FileMonitor()->MonitorPaths(toWatchList,
+                              [this](const std::string& p, int e, int s) {
+                                this->HandleCMakeFileChanges(p, e, s);
+                              });
+
+  m_State = STATE_CONFIGURED;
+  m_isDirty = false;
+  return request.Reply(Json::Value());
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
+  const cmServerRequest& request)
+{
+  cmake* cm = this->CMakeInstance();
+  Json::Value obj = Json::objectValue;
+
+  // Capabilities information:
+  obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(true);
+
+  obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput();
+  obj[kTRACE_KEY] = cm->GetTrace();
+  obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand();
+  obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized();
+  obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused();
+  obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
+  obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
+
+  obj[kSOURCE_DIRECTORY_KEY] = cm->GetHomeDirectory();
+  obj[kBUILD_DIRECTORY_KEY] = cm->GetHomeOutputDirectory();
+
+  // Currently used generator:
+  cmGlobalGenerator* gen = cm->GetGlobalGenerator();
+  obj[kGENERATOR_KEY] = gen ? gen->GetName() : std::string();
+  obj[kEXTRA_GENERATOR_KEY] =
+    gen ? gen->GetExtraGeneratorName() : std::string();
+
+  return request.Reply(obj);
+}
+
+static void setBool(const cmServerRequest& request, const std::string& key,
+                    std::function<void(bool)> setter)
+{
+  if (request.Data[key].isNull()) {
+    return;
+  }
+  setter(request.Data[key].asBool());
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
+  const cmServerRequest& request)
+{
+  const std::vector<std::string> boolValues = {
+    kDEBUG_OUTPUT_KEY,       kTRACE_KEY,       kTRACE_EXPAND_KEY,
+    kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
+    kCHECK_SYSTEM_VARS_KEY
+  };
+  for (auto i : boolValues) {
+    if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
+      return request.ReportError("\"" + i +
+                                 "\" must be unset or a bool value.");
+    }
+  }
+
+  cmake* cm = this->CMakeInstance();
+
+  setBool(request, kDEBUG_OUTPUT_KEY,
+          [cm](bool e) { cm->SetDebugOutputOn(e); });
+  setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); });
+  setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); });
+  setBool(request, kWARN_UNINITIALIZED_KEY,
+          [cm](bool e) { cm->SetWarnUninitialized(e); });
+  setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); });
+  setBool(request, kWARN_UNUSED_CLI_KEY,
+          [cm](bool e) { cm->SetWarnUnusedCli(e); });
+  setBool(request, kCHECK_SYSTEM_VARS_KEY,
+          [cm](bool e) { cm->SetCheckSystemVars(e); });
+
+  return request.Reply(Json::Value());
+}
+
+cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
+  const cmServerRequest& request)
+{
+  const cmFileMonitor* const fm = FileMonitor();
+  Json::Value result = Json::objectValue;
+  Json::Value files = Json::arrayValue;
+  for (const auto& f : fm->WatchedFiles()) {
+    files.append(f);
+  }
+  Json::Value directories = Json::arrayValue;
+  for (const auto& d : fm->WatchedDirectories()) {
+    directories.append(d);
+  }
+  result[kWATCHED_FILES_KEY] = files;
+  result[kWATCHED_DIRECTORIES_KEY] = directories;
+
+  return request.Reply(result);
+}
diff --git a/Source/cmServerProtocol.h b/Source/cmServerProtocol.h
new file mode 100644
index 0000000..5238d5d
--- /dev/null
+++ b/Source/cmServerProtocol.h
@@ -0,0 +1,134 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#pragma once
+
+#include "cmListFileCache.h"
+#include "cmake.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_jsoncpp_writer.h"
+#endif
+
+#include <memory>
+#include <string>
+
+class cmake;
+class cmFileMonitor;
+class cmServer;
+
+class cmServerRequest;
+
+class cmServerResponse
+{
+public:
+  explicit cmServerResponse(const cmServerRequest& request);
+
+  void SetData(const Json::Value& data);
+  void SetError(const std::string& message);
+
+  bool IsComplete() const;
+  bool IsError() const;
+  std::string ErrorMessage() const;
+  Json::Value Data() const;
+
+  const std::string Type;
+  const std::string Cookie;
+
+private:
+  enum PayLoad
+  {
+    PAYLOAD_UNKNOWN,
+    PAYLOAD_ERROR,
+    PAYLOAD_DATA
+  };
+  PayLoad m_Payload = PAYLOAD_UNKNOWN;
+  std::string m_ErrorMessage;
+  Json::Value m_Data;
+};
+
+class cmServerRequest
+{
+public:
+  cmServerResponse Reply(const Json::Value& data) const;
+  cmServerResponse ReportError(const std::string& message) const;
+
+  const std::string Type;
+  const std::string Cookie;
+  const Json::Value Data;
+
+private:
+  cmServerRequest(cmServer* server, const std::string& t, const std::string& c,
+                  const Json::Value& d);
+
+  void ReportProgress(int min, int current, int max,
+                      const std::string& message) const;
+  void ReportMessage(const std::string& message,
+                     const std::string& title) const;
+
+  cmServer* m_Server;
+
+  friend class cmServer;
+};
+
+class cmServerProtocol
+{
+public:
+  virtual ~cmServerProtocol() {}
+
+  virtual std::pair<int, int> ProtocolVersion() const = 0;
+  virtual bool IsExperimental() const = 0;
+  virtual const cmServerResponse Process(const cmServerRequest& request) = 0;
+
+  bool Activate(cmServer* server, const cmServerRequest& request,
+                std::string* errorMessage);
+
+  cmFileMonitor* FileMonitor() const;
+  void SendSignal(const std::string& name, const Json::Value& data) const;
+
+protected:
+  cmake* CMakeInstance() const;
+  // Implement protocol specific activation tasks here. Called from Activate().
+  virtual bool DoActivate(const cmServerRequest& request,
+                          std::string* errorMessage);
+
+private:
+  std::unique_ptr<cmake> m_CMakeInstance;
+  cmServer* m_Server = nullptr; // not owned!
+
+  friend class cmServer;
+};
+
+class cmServerProtocol1_0 : public cmServerProtocol
+{
+public:
+  std::pair<int, int> ProtocolVersion() const override;
+  bool IsExperimental() const override;
+  const cmServerResponse Process(const cmServerRequest& request) override;
+
+private:
+  bool DoActivate(const cmServerRequest& request,
+                  std::string* errorMessage) override;
+
+  void HandleCMakeFileChanges(const std::string& path, int event, int status);
+
+  // Handle requests:
+  cmServerResponse ProcessCache(const cmServerRequest& request);
+  cmServerResponse ProcessCMakeInputs(const cmServerRequest& request);
+  cmServerResponse ProcessCodeModel(const cmServerRequest& request);
+  cmServerResponse ProcessCompute(const cmServerRequest& request);
+  cmServerResponse ProcessConfigure(const cmServerRequest& request);
+  cmServerResponse ProcessGlobalSettings(const cmServerRequest& request);
+  cmServerResponse ProcessSetGlobalSettings(const cmServerRequest& request);
+  cmServerResponse ProcessFileSystemWatchers(const cmServerRequest& request);
+
+  enum State
+  {
+    STATE_INACTIVE,
+    STATE_ACTIVE,
+    STATE_CONFIGURED,
+    STATE_COMPUTED
+  };
+  State m_State = STATE_INACTIVE;
+
+  bool m_isDirty = false;
+};
diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx
index 5f4cfee..8ce0b18 100644
--- a/Source/cmSetCommand.cxx
+++ b/Source/cmSetCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetCommand.h"
 
 // cmSetCommand
 bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
                                cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -31,13 +22,14 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
     putEnvArg += "=";
 
     // what is the current value if any
-    const char* currValue = getenv(varName);
+    std::string currValue;
+    const bool currValueSet = cmSystemTools::GetEnv(varName, currValue);
     delete[] varName;
 
     // will it be set to something, then set it
     if (args.size() > 1 && !args[1].empty()) {
       // but only if it is different from current value
-      if (!currValue || strcmp(currValue, args[1].c_str())) {
+      if (!currValueSet || currValue != args[1]) {
         putEnvArg += args[1];
         cmSystemTools::PutEnv(putEnvArg);
       }
@@ -45,7 +37,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
     }
 
     // if it will be cleared, then clear it if it isn't already clear
-    if (currValue) {
+    if (currValueSet) {
       cmSystemTools::PutEnv(putEnvArg);
     }
     return true;
@@ -58,8 +50,8 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
   }
   // SET (VAR PARENT_SCOPE) // Removes the definition of VAR
   // in the parent scope.
-  else if (args.size() == 2 && args[args.size() - 1] == "PARENT_SCOPE") {
-    this->Makefile->RaiseScope(variable, 0);
+  if (args.size() == 2 && args[args.size() - 1] == "PARENT_SCOPE") {
+    this->Makefile->RaiseScope(variable, CM_NULLPTR);
     return true;
   }
 
@@ -73,7 +65,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
   bool force = false; // optional
   bool parentScope = false;
   cmState::CacheEntryType type = cmState::STRING; // required if cache
-  const char* docstring = 0;                      // required if cache
+  const char* docstring = CM_NULLPTR;             // required if cache
 
   unsigned int ignoreLastArgs = 0;
   // look for PARENT_SCOPE argument
diff --git a/Source/cmSetCommand.h b/Source/cmSetCommand.h
index 65af8ac..94f7cf0 100644
--- a/Source/cmSetCommand.h
+++ b/Source/cmSetCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetCommand_h
 #define cmSetCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmSetCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSetCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set"; }
+  std::string GetName() const CM_OVERRIDE { return "set"; }
 
   cmTypeMacro(cmSetCommand, cmCommand);
 };
diff --git a/Source/cmSetDirectoryPropertiesCommand.cxx b/Source/cmSetDirectoryPropertiesCommand.cxx
index ca758da..b0de021 100644
--- a/Source/cmSetDirectoryPropertiesCommand.cxx
+++ b/Source/cmSetDirectoryPropertiesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetDirectoryPropertiesCommand.h"
 
 #include "cmake.h"
@@ -17,7 +8,7 @@
 bool cmSetDirectoryPropertiesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -45,7 +36,8 @@ bool cmSetDirectoryPropertiesCommand::RunCommand(
     if (prop == "VARIABLES") {
       errors = "Variables and cache variables should be set using SET command";
       return false;
-    } else if (prop == "MACROS") {
+    }
+    if (prop == "MACROS") {
       errors = "Commands and macros cannot be set using SET_CMAKE_PROPERTIES";
       return false;
     }
diff --git a/Source/cmSetDirectoryPropertiesCommand.h b/Source/cmSetDirectoryPropertiesCommand.h
index a393eee..9abefda 100644
--- a/Source/cmSetDirectoryPropertiesCommand.h
+++ b/Source/cmSetDirectoryPropertiesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetDirectoryPropertiesCommand_h
 #define cmSetDirectoryPropertiesCommand_h
 
@@ -17,24 +8,30 @@
 class cmSetDirectoryPropertiesCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmSetDirectoryPropertiesCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmSetDirectoryPropertiesCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_directory_properties"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "set_directory_properties";
+  }
 
   /**
    * Static entry point for use by other commands
diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx
index 73f7437..2a4101f 100644
--- a/Source/cmSetPropertyCommand.cxx
+++ b/Source/cmSetPropertyCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetPropertyCommand.h"
 
 #include "cmSetSourceFilesPropertiesCommand.h"
@@ -139,7 +130,7 @@ bool cmSetPropertyCommand::HandleGlobalMode()
   const char* name = this->PropertyName.c_str();
   const char* value = this->PropertyValue.c_str();
   if (this->Remove) {
-    value = 0;
+    value = CM_NULLPTR;
   }
   if (this->AppendMode) {
     cm->AppendProperty(name, value ? value : "", this->AppendAsString);
@@ -189,7 +180,7 @@ bool cmSetPropertyCommand::HandleDirectoryMode()
   const char* name = this->PropertyName.c_str();
   const char* value = this->PropertyValue.c_str();
   if (this->Remove) {
-    value = 0;
+    value = CM_NULLPTR;
   }
   if (this->AppendMode) {
     mf->AppendProperty(name, value ? value : "", this->AppendAsString);
@@ -230,7 +221,7 @@ bool cmSetPropertyCommand::HandleTarget(cmTarget* target)
   const char* name = this->PropertyName.c_str();
   const char* value = this->PropertyValue.c_str();
   if (this->Remove) {
-    value = 0;
+    value = CM_NULLPTR;
   }
   if (this->AppendMode) {
     target->AppendProperty(name, value, this->AppendAsString);
@@ -269,7 +260,7 @@ bool cmSetPropertyCommand::HandleSource(cmSourceFile* sf)
   const char* name = this->PropertyName.c_str();
   const char* value = this->PropertyValue.c_str();
   if (this->Remove) {
-    value = 0;
+    value = CM_NULLPTR;
   }
 
   if (this->AppendMode) {
@@ -317,7 +308,7 @@ bool cmSetPropertyCommand::HandleTest(cmTest* test)
   const char* name = this->PropertyName.c_str();
   const char* value = this->PropertyValue.c_str();
   if (this->Remove) {
-    value = 0;
+    value = CM_NULLPTR;
   }
   if (this->AppendMode) {
     test->AppendProperty(name, value, this->AppendAsString);
diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h
index a85d652..01295c1 100644
--- a/Source/cmSetPropertyCommand.h
+++ b/Source/cmSetPropertyCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetsPropertiesCommand_h
 #define cmSetsPropertiesCommand_h
 
@@ -19,24 +10,24 @@ class cmSetPropertyCommand : public cmCommand
 public:
   cmSetPropertyCommand();
 
-  virtual cmCommand* Clone() { return new cmSetPropertyCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSetPropertyCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_property"; }
+  std::string GetName() const CM_OVERRIDE { return "set_property"; }
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   cmTypeMacro(cmSetPropertyCommand, cmCommand);
 
diff --git a/Source/cmSetSourceFilesPropertiesCommand.cxx b/Source/cmSetSourceFilesPropertiesCommand.cxx
index 976f3c8..0021589 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.cxx
+++ b/Source/cmSetSourceFilesPropertiesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetSourceFilesPropertiesCommand.h"
 
 #include "cmSourceFile.h"
diff --git a/Source/cmSetSourceFilesPropertiesCommand.h b/Source/cmSetSourceFilesPropertiesCommand.h
index 20e6b93..c683ac0 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.h
+++ b/Source/cmSetSourceFilesPropertiesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetSourceFilesPropertiesCommand_h
 #define cmSetSourceFilesPropertiesCommand_h
 
@@ -17,19 +8,25 @@
 class cmSetSourceFilesPropertiesCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmSetSourceFilesPropertiesCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmSetSourceFilesPropertiesCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_source_files_properties"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "set_source_files_properties";
+  }
 
   cmTypeMacro(cmSetSourceFilesPropertiesCommand, cmCommand);
 
diff --git a/Source/cmSetTargetPropertiesCommand.cxx b/Source/cmSetTargetPropertiesCommand.cxx
index 86c8016..200b42d 100644
--- a/Source/cmSetTargetPropertiesCommand.cxx
+++ b/Source/cmSetTargetPropertiesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetTargetPropertiesCommand.h"
 
 #include "cmGlobalGenerator.h"
diff --git a/Source/cmSetTargetPropertiesCommand.h b/Source/cmSetTargetPropertiesCommand.h
index 122c15e..6e2a242 100644
--- a/Source/cmSetTargetPropertiesCommand.h
+++ b/Source/cmSetTargetPropertiesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetTargetsPropertiesCommand_h
 #define cmSetTargetsPropertiesCommand_h
 
@@ -17,19 +8,19 @@
 class cmSetTargetPropertiesCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmSetTargetPropertiesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSetTargetPropertiesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_target_properties"; }
+  std::string GetName() const CM_OVERRIDE { return "set_target_properties"; }
 
   /**
    *  Used by this command and cmSetPropertiesCommand
diff --git a/Source/cmSetTestsPropertiesCommand.cxx b/Source/cmSetTestsPropertiesCommand.cxx
index 2fb137f..5abb84e 100644
--- a/Source/cmSetTestsPropertiesCommand.cxx
+++ b/Source/cmSetTestsPropertiesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetTestsPropertiesCommand.h"
 
 #include "cmTest.h"
@@ -18,7 +9,7 @@
 bool cmSetTestsPropertiesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmSetTestsPropertiesCommand.h b/Source/cmSetTestsPropertiesCommand.h
index e469b2a..3f5ce21 100644
--- a/Source/cmSetTestsPropertiesCommand.h
+++ b/Source/cmSetTestsPropertiesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSetTestsPropertiesCommand_h
 #define cmSetTestsPropertiesCommand_h
 
@@ -17,19 +8,19 @@
 class cmSetTestsPropertiesCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmSetTestsPropertiesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSetTestsPropertiesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the input file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "set_tests_properties"; }
+  std::string GetName() const CM_OVERRIDE { return "set_tests_properties"; }
 
   cmTypeMacro(cmSetTestsPropertiesCommand, cmCommand);
 
diff --git a/Source/cmSiteNameCommand.cxx b/Source/cmSiteNameCommand.cxx
index 702af4d..dbd3ed9 100644
--- a/Source/cmSiteNameCommand.cxx
+++ b/Source/cmSiteNameCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSiteNameCommand.h"
 
 #include <cmsys/RegularExpression.hxx>
@@ -55,7 +46,8 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args,
   // try to find the hostname for this computer
   if (!cmSystemTools::IsOff(hostname_cmd.c_str())) {
     std::string host;
-    cmSystemTools::RunSingleCommand(hostname_cmd.c_str(), &host, 0, 0, 0,
+    cmSystemTools::RunSingleCommand(hostname_cmd.c_str(), &host, CM_NULLPTR,
+                                    CM_NULLPTR, CM_NULLPTR,
                                     cmSystemTools::OUTPUT_NONE);
 
     // got the hostname
diff --git a/Source/cmSiteNameCommand.h b/Source/cmSiteNameCommand.h
index a4812f7..5578b03 100644
--- a/Source/cmSiteNameCommand.h
+++ b/Source/cmSiteNameCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSiteNameCommand_h
 #define cmSiteNameCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmSiteNameCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSiteNameCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "site_name"; }
+  std::string GetName() const CM_OVERRIDE { return "site_name"; }
 
   cmTypeMacro(cmSiteNameCommand, cmCommand);
 };
diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx
index 5b0acee..5d37578 100644
--- a/Source/cmSourceFile.cxx
+++ b/Source/cmSourceFile.cxx
@@ -1,25 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceFile.h"
 
+#include "cmCustomCommand.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmProperty.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
+#include <sstream>
+
 cmSourceFile::cmSourceFile(cmMakefile* mf, const std::string& name)
   : Location(mf, name)
 {
-  this->CustomCommand = 0;
+  this->CustomCommand = CM_NULLPTR;
   this->FindFullPathFailed = false;
   this->IsUiFile = (".ui" == cmSystemTools::GetFilenameLastExtension(
                                this->Location.GetName()));
@@ -27,7 +23,7 @@ cmSourceFile::cmSourceFile(cmMakefile* mf, const std::string& name)
 
 cmSourceFile::~cmSourceFile()
 {
-  this->SetCustomCommand(0);
+  this->SetCustomCommand(CM_NULLPTR);
 }
 
 std::string const& cmSourceFile::GetExtension() const
@@ -135,7 +131,7 @@ bool cmSourceFile::FindFullPath(std::string* error)
 
   // The file is not generated.  It must exist on disk.
   cmMakefile const* mf = this->Location.GetMakefile();
-  const char* tryDirs[3] = { 0, 0, 0 };
+  const char* tryDirs[3] = { CM_NULLPTR, CM_NULLPTR, CM_NULLPTR };
   if (this->Location.DirectoryIsAmbiguous()) {
     tryDirs[0] = mf->GetCurrentSourceDirectory();
     tryDirs[1] = mf->GetCurrentBinaryDirectory();
@@ -294,10 +290,9 @@ const char* cmSourceFile::GetProperty(const std::string& prop) const
   // Check for computed properties.
   if (prop == "LOCATION") {
     if (this->FullPath.empty()) {
-      return 0;
-    } else {
-      return this->FullPath.c_str();
+      return CM_NULLPTR;
     }
+    return this->FullPath.c_str();
   }
 
   const char* retVal = this->Properties.GetPropertyValue(prop);
diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h
index b1623bd..b193f65 100644
--- a/Source/cmSourceFile.h
+++ b/Source/cmSourceFile.h
@@ -1,23 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSourceFile_h
 #define cmSourceFile_h
 
-#include "cmSourceFileLocation.h"
+#include <cmConfigure.h>
 
-#include "cmCustomCommand.h"
 #include "cmPropertyMap.h"
+#include "cmSourceFileLocation.h"
+
+#include <string>
+#include <vector>
 
-class cmake;
+class cmCustomCommand;
+class cmMakefile;
 
 /** \class cmSourceFile
  * \brief Represent a class loaded from a makefile.
@@ -62,7 +57,7 @@ public:
    * horrible interface, but is necessary for backwards
    * compatibility).
    */
-  std::string const& GetFullPath(std::string* error = 0);
+  std::string const& GetFullPath(std::string* error = CM_NULLPTR);
   std::string const& GetFullPath() const;
 
   /**
diff --git a/Source/cmSourceFileLocation.cxx b/Source/cmSourceFileLocation.cxx
index 3219f36..4e0880e 100644
--- a/Source/cmSourceFileLocation.cxx
+++ b/Source/cmSourceFileLocation.cxx
@@ -1,25 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceFileLocation.h"
 
+#include <cmConfigure.h>
+
 #include "cmAlgorithms.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSystemTools.h"
+#include "cmake.h"
 
-#include "assert.h"
+#include <algorithm>
+#include <assert.h>
+#include <vector>
 
 cmSourceFileLocation::cmSourceFileLocation()
-  : Makefile(0)
+  : Makefile(CM_NULLPTR)
   , AmbiguousDirectory(true)
   , AmbiguousExtension(true)
 {
@@ -177,10 +173,7 @@ bool cmSourceFileLocation::MatchesAmbiguousExtension(
   }
   std::vector<std::string> hdrExts =
     mf->GetCMakeInstance()->GetHeaderExtensions();
-  if (std::find(hdrExts.begin(), hdrExts.end(), ext) != hdrExts.end()) {
-    return true;
-  }
-  return false;
+  return std::find(hdrExts.begin(), hdrExts.end(), ext) != hdrExts.end();
 }
 
 bool cmSourceFileLocation::Matches(cmSourceFileLocation const& loc)
diff --git a/Source/cmSourceFileLocation.h b/Source/cmSourceFileLocation.h
index 7989173..aa2e6c7 100644
--- a/Source/cmSourceFileLocation.h
+++ b/Source/cmSourceFileLocation.h
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSourceFileLocation_h
 #define cmSourceFileLocation_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
 
 class cmMakefile;
 
diff --git a/Source/cmSourceGroup.cxx b/Source/cmSourceGroup.cxx
index 394b33a..104e959 100644
--- a/Source/cmSourceGroup.cxx
+++ b/Source/cmSourceGroup.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceGroup.h"
 
 class cmSourceGroupInternals
@@ -86,11 +77,7 @@ bool cmSourceGroup::MatchesRegex(const char* name)
 
 bool cmSourceGroup::MatchesFiles(const char* name)
 {
-  std::set<std::string>::const_iterator i = this->GroupFiles.find(name);
-  if (i != this->GroupFiles.end()) {
-    return true;
-  }
-  return false;
+  return this->GroupFiles.find(name) != this->GroupFiles.end();
 }
 
 void cmSourceGroup::AssignSource(const cmSourceFile* sf)
@@ -127,7 +114,7 @@ cmSourceGroup* cmSourceGroup::LookupChild(const char* name) const
   }
 
   // if no child with this name was found return NULL
-  return NULL;
+  return CM_NULLPTR;
 }
 
 cmSourceGroup* cmSourceGroup::MatchChildrenFiles(const char* name)
@@ -147,7 +134,7 @@ cmSourceGroup* cmSourceGroup::MatchChildrenFiles(const char* name)
       return result;
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 cmSourceGroup* cmSourceGroup::MatchChildrenRegex(const char* name)
@@ -168,7 +155,7 @@ cmSourceGroup* cmSourceGroup::MatchChildrenRegex(const char* name)
     return this;
   }
 
-  return 0;
+  return CM_NULLPTR;
 }
 
 std::vector<cmSourceGroup> const& cmSourceGroup::GetGroupChildren() const
diff --git a/Source/cmSourceGroup.h b/Source/cmSourceGroup.h
index 8603e95..545da81 100644
--- a/Source/cmSourceGroup.h
+++ b/Source/cmSourceGroup.h
@@ -1,23 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSourceGroup_h
 #define cmSourceGroup_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
 #include <cmsys/RegularExpression.hxx>
+#include <set>
+#include <string>
+#include <vector>
 
 class cmSourceFile;
-
 class cmSourceGroupInternals;
 
 /** \class cmSourceGroup
@@ -34,7 +27,7 @@ class cmSourceGroup
 {
 public:
   cmSourceGroup(const char* name, const char* regex,
-                const char* parentName = 0);
+                const char* parentName = CM_NULLPTR);
   cmSourceGroup(cmSourceGroup const& r);
   ~cmSourceGroup();
   cmSourceGroup& operator=(cmSourceGroup const&);
diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx
index 252819c..2b176b5 100644
--- a/Source/cmSourceGroupCommand.cxx
+++ b/Source/cmSourceGroupCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceGroupCommand.h"
 
 // cmSourceGroupCommand
 bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -28,7 +19,7 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
   std::vector<std::string> folders =
     cmSystemTools::tokenize(args[0], delimiter);
 
-  cmSourceGroup* sg = 0;
+  cmSourceGroup* sg = CM_NULLPTR;
   sg = this->Makefile->GetSourceGroup(folders);
   if (!sg) {
     this->Makefile->AddSourceGroup(folders);
diff --git a/Source/cmSourceGroupCommand.h b/Source/cmSourceGroupCommand.h
index 0458656..e3639df 100644
--- a/Source/cmSourceGroupCommand.h
+++ b/Source/cmSourceGroupCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSourceGroupCommand_h
 #define cmSourceGroupCommand_h
 
@@ -26,19 +17,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmSourceGroupCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSourceGroupCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "source_group"; }
+  std::string GetName() const CM_OVERRIDE { return "source_group"; }
 
   cmTypeMacro(cmSourceGroupCommand, cmCommand);
 };
diff --git a/Source/cmStandardIncludes.h b/Source/cmStandardIncludes.h
index 6669e5c..0aab6d9 100644
--- a/Source/cmStandardIncludes.h
+++ b/Source/cmStandardIncludes.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 /**
  * Include header files as a function of the build process, compiler,
  * and operating system.
@@ -18,18 +9,6 @@
 
 #include <cmConfigure.h>
 
-#include <cmsys/Configure.hxx>
-
-#ifdef _MSC_VER
-#pragma warning(disable : 4786)
-#pragma warning(disable : 4503)
-#endif
-
-#ifdef __ICL
-#pragma warning(disable : 985)
-#pragma warning(disable : 1572) /* floating-point equality test */
-#endif
-
 // Provide fixed-size integer types.
 #include <cm_kwiml.h>
 
@@ -67,73 +46,9 @@ typedef unsigned short mode_t;
 /* Poison this operator to avoid common mistakes.  */
 extern void operator<<(std::ostream&, const std::ostringstream&);
 
-/** Standard documentation entry for cmDocumentation's formatting.  */
-struct cmDocumentationEntry
-{
-  std::string Name;
-  std::string Brief;
-  cmDocumentationEntry() {}
-  cmDocumentationEntry(const char* doc[2])
-  {
-    if (doc[0])
-      this->Name = doc[0];
-    if (doc[1])
-      this->Brief = doc[1];
-  }
-  cmDocumentationEntry(const char* n, const char* b)
-  {
-    if (n)
-      this->Name = n;
-    if (b)
-      this->Brief = b;
-  }
-};
-
-/** Data structure to represent a single command line.  */
-class cmCustomCommandLine : public std::vector<std::string>
-{
-public:
-  typedef std::vector<std::string> Superclass;
-  typedef Superclass::iterator iterator;
-  typedef Superclass::const_iterator const_iterator;
-};
-
-/** Data structure to represent a list of command lines.  */
-class cmCustomCommandLines : public std::vector<cmCustomCommandLine>
-{
-public:
-  typedef std::vector<cmCustomCommandLine> Superclass;
-  typedef Superclass::iterator iterator;
-  typedef Superclass::const_iterator const_iterator;
-};
-
-// All subclasses of cmCommand or cmCTestGenericHandler should
-// invoke this macro.
-#define cmTypeMacro(thisClass, superclass)                                    \
-  virtual const char* GetNameOfClass() { return #thisClass; }                 \
-  typedef superclass Superclass;                                              \
-  static bool IsTypeOf(const char* type)                                      \
-  {                                                                           \
-    if (!strcmp(#thisClass, type)) {                                          \
-      return true;                                                            \
-    }                                                                         \
-    return Superclass::IsTypeOf(type);                                        \
-  }                                                                           \
-  virtual bool IsA(const char* type) { return thisClass::IsTypeOf(type); }    \
-  static thisClass* SafeDownCast(cmObject* c)                                 \
-  {                                                                           \
-    if (c && c->IsA(#thisClass)) {                                            \
-      return static_cast<thisClass*>(c);                                      \
-    }                                                                         \
-    return 0;                                                                 \
-  }                                                                           \
-  class cmTypeMacro_UseTrailingSemicolon
-
-enum cmTargetLinkLibraryType
-{
-  GENERAL_LibraryType,
-  DEBUG_LibraryType,
-  OPTIMIZED_LibraryType
-};
+#include "cmCustomCommandLines.h"
+#include "cmDocumentationEntry.h"
+#include "cmTargetLinkLibraryType.h"
+#include "cmTypeMacro.h"
 
 #endif
diff --git a/Source/cmStandardLexer.h b/Source/cmStandardLexer.h
index 94ed276..234aef5 100644
--- a/Source/cmStandardLexer.h
+++ b/Source/cmStandardLexer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmStandardLexer_h
 #define cmStandardLexer_h
 
diff --git a/Source/cmState.cxx b/Source/cmState.cxx
index 04f07ce..0e73879 100644
--- a/Source/cmState.cxx
+++ b/Source/cmState.cxx
@@ -1,24 +1,29 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmState.h"
 
 #include "cmAlgorithms.h"
 #include "cmCacheManager.h"
 #include "cmCommand.h"
 #include "cmDefinitions.h"
+#include "cmListFileCache.h"
+#include "cmSystemTools.h"
+#include "cmTypeMacro.h"
 #include "cmVersion.h"
 #include "cmake.h"
 
+#include <algorithm>
 #include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <iterator>
+#include <stdio.h>
+#include <string.h>
+#include <utility>
+
+static std::string const kBINARY_DIR = "BINARY_DIR";
+static std::string const kBUILDSYSTEM_TARGETS = "BUILDSYSTEM_TARGETS";
+static std::string const kSOURCE_DIR = "SOURCE_DIR";
+static std::string const kSUBDIRECTORIES = "SUBDIRECTORIES";
 
 struct cmState::SnapshotDataType
 {
@@ -68,8 +73,6 @@ struct cmState::BuildsystemDirectoryStateType
   std::string Location;
   std::string OutputLocation;
 
-  std::vector<std::string> CurrentSourceDirectoryComponents;
-  std::vector<std::string> CurrentBinaryDirectoryComponents;
   // The top-most directories for relative path conversion.  Both the
   // source and destination location of a relative path conversion
   // must be underneath one of these directories (both under source or
@@ -87,6 +90,8 @@ struct cmState::BuildsystemDirectoryStateType
   std::vector<std::string> CompileOptions;
   std::vector<cmListFileBacktrace> CompileOptionsBacktraces;
 
+  std::vector<std::string> NormalTargetNames;
+
   std::string ProjectName;
 
   cmPropertyMap Properties;
@@ -135,12 +140,12 @@ const char* cmState::GetTargetTypeName(cmState::TargetType targetType)
       return "UNKNOWN_LIBRARY";
   }
   assert(0 && "Unexpected target type");
-  return 0;
+  return CM_NULLPTR;
 }
 
 const char* cmCacheEntryTypes[] = { "BOOL",          "PATH",     "FILEPATH",
                                     "STRING",        "INTERNAL", "STATIC",
-                                    "UNINITIALIZED", 0 };
+                                    "UNINITIALIZED", CM_NULLPTR };
 
 const char* cmState::CacheEntryTypeToString(cmState::CacheEntryType type)
 {
@@ -204,7 +209,7 @@ const char* cmState::GetCacheEntryValue(std::string const& key) const
 {
   cmCacheManager::CacheEntry* e = this->CacheManager->GetCacheEntry(key);
   if (!e) {
-    return 0;
+    return CM_NULLPTR;
   }
   return e->Value.c_str();
 }
@@ -246,13 +251,21 @@ void cmState::SetCacheEntryBoolProperty(std::string const& key,
   it.SetProperty(propertyName, value);
 }
 
+std::vector<std::string> cmState::GetCacheEntryPropertyList(
+  const std::string& key)
+{
+  cmCacheManager::CacheIterator it =
+    this->CacheManager->GetCacheIterator(key.c_str());
+  return it.GetPropertyList();
+}
+
 const char* cmState::GetCacheEntryProperty(std::string const& key,
                                            std::string const& propertyName)
 {
   cmCacheManager::CacheIterator it =
     this->CacheManager->GetCacheIterator(key.c_str());
   if (!it.PropertyExists(propertyName)) {
-    return 0;
+    return CM_NULLPTR;
   }
   return it.GetProperty(propertyName);
 }
@@ -288,7 +301,7 @@ void cmState::RemoveCacheEntryProperty(std::string const& key,
                                        std::string const& propertyName)
 {
   this->CacheManager->GetCacheIterator(key.c_str())
-    .SetProperty(propertyName, (void*)0);
+    .SetProperty(propertyName, (void*)CM_NULLPTR);
 }
 
 cmState::Snapshot cmState::Reset()
@@ -309,6 +322,7 @@ cmState::Snapshot cmState::Reset()
     it->CompileOptions.clear();
     it->CompileOptionsBacktraces.clear();
     it->DirectoryEnd = pos;
+    it->NormalTargetNames.clear();
     it->Properties.clear();
     it->Children.clear();
   }
@@ -366,7 +380,7 @@ cmPropertyDefinition const* cmState::GetPropertyDefinition(
       this->PropertyDefinitions.find(scope)->second;
     return &defs.find(name)->second;
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 bool cmState::IsPropertyDefined(const std::string& name,
@@ -483,7 +497,7 @@ void cmState::RemoveUnscriptableCommands()
 
 cmCommand* cmState::GetCommand(std::string const& name) const
 {
-  cmCommand* command = 0;
+  cmCommand* command = CM_NULLPTR;
   std::string sName = cmSystemTools::LowerCase(name);
   std::map<std::string, cmCommand*>::const_iterator pos =
     this->Commands.find(sName);
@@ -574,10 +588,6 @@ void cmState::SetSourceDirectory(std::string const& sourceDirectory)
 {
   this->SourceDirectory = sourceDirectory;
   cmSystemTools::ConvertToUnixSlashes(this->SourceDirectory);
-
-  cmSystemTools::SplitPath(
-    cmSystemTools::CollapseFullPath(this->SourceDirectory),
-    this->SourceDirectoryComponents);
 }
 
 const char* cmState::GetSourceDirectory() const
@@ -585,19 +595,10 @@ const char* cmState::GetSourceDirectory() const
   return this->SourceDirectory.c_str();
 }
 
-std::vector<std::string> const& cmState::GetSourceDirectoryComponents() const
-{
-  return this->SourceDirectoryComponents;
-}
-
 void cmState::SetBinaryDirectory(std::string const& binaryDirectory)
 {
   this->BinaryDirectory = binaryDirectory;
   cmSystemTools::ConvertToUnixSlashes(this->BinaryDirectory);
-
-  cmSystemTools::SplitPath(
-    cmSystemTools::CollapseFullPath(this->BinaryDirectory),
-    this->BinaryDirectoryComponents);
 }
 
 void cmState::SetWindowsShell(bool windowsShell)
@@ -675,11 +676,6 @@ const char* cmState::GetBinaryDirectory() const
   return this->BinaryDirectory.c_str();
 }
 
-std::vector<std::string> const& cmState::GetBinaryDirectoryComponents() const
-{
-  return this->BinaryDirectoryComponents;
-}
-
 void cmState::Directory::ComputeRelativePathTopSource()
 {
   // Relative path conversion inside the source tree is not used to
@@ -961,8 +957,6 @@ void cmState::Directory::SetCurrentSource(std::string const& dir)
   cmSystemTools::ConvertToUnixSlashes(loc);
   loc = cmSystemTools::CollapseFullPath(loc);
 
-  cmSystemTools::SplitPath(
-    loc, this->DirectoryState->CurrentSourceDirectoryComponents);
   this->ComputeRelativePathTopSource();
 
   this->Snapshot_.SetDefinition("CMAKE_CURRENT_SOURCE_DIR", loc);
@@ -980,8 +974,6 @@ void cmState::Directory::SetCurrentBinary(std::string const& dir)
   cmSystemTools::ConvertToUnixSlashes(loc);
   loc = cmSystemTools::CollapseFullPath(loc);
 
-  cmSystemTools::SplitPath(
-    loc, this->DirectoryState->CurrentBinaryDirectoryComponents);
   this->ComputeRelativePathTopBinary();
 
   this->Snapshot_.SetDefinition("CMAKE_CURRENT_BINARY_DIR", loc);
@@ -992,18 +984,6 @@ void cmState::Snapshot::SetListFile(const std::string& listfile)
   *this->Position->ExecutionListFile = listfile;
 }
 
-std::vector<std::string> const&
-cmState::Directory::GetCurrentSourceComponents() const
-{
-  return this->DirectoryState->CurrentSourceDirectoryComponents;
-}
-
-std::vector<std::string> const&
-cmState::Directory::GetCurrentBinaryComponents() const
-{
-  return this->DirectoryState->CurrentBinaryDirectoryComponents;
-}
-
 const char* cmState::Directory::GetRelativePathTopSource() const
 {
   return this->DirectoryState->RelativePathTopSource.c_str();
@@ -1189,7 +1169,7 @@ void cmState::Snapshot::SetDefinition(std::string const& name,
 
 void cmState::Snapshot::RemoveDefinition(std::string const& name)
 {
-  this->Position->Vars->Set(name, 0);
+  this->Position->Vars->Set(name, CM_NULLPTR);
 }
 
 std::vector<std::string> cmState::Snapshot::UnusedKeys() const
@@ -1278,8 +1258,9 @@ void cmState::Snapshot::SetDefaultDefinitions()
   this->SetDefinition("CMAKE_HOST_UNIX", "1");
 #endif
 #if defined(__CYGWIN__)
-  if (cmSystemTools::IsOn(
-        cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32"))) {
+  std::string legacy;
+  if (cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32", legacy) &&
+      cmSystemTools::IsOn(legacy.c_str())) {
     this->SetDefinition("WIN32", "1");
     this->SetDefinition("CMAKE_HOST_WIN32", "1");
   }
@@ -1684,7 +1665,32 @@ const char* cmState::Directory::GetProperty(const std::string& prop,
       return parent.GetDirectory().GetCurrentSource();
     }
     return "";
-  } else if (prop == "LISTFILE_STACK") {
+  }
+  if (prop == kBINARY_DIR) {
+    output = this->GetCurrentBinary();
+    return output.c_str();
+  }
+  if (prop == kSOURCE_DIR) {
+    output = this->GetCurrentSource();
+    return output.c_str();
+  }
+  if (prop == kSUBDIRECTORIES) {
+    std::vector<std::string> child_dirs;
+    std::vector<cmState::Snapshot> const& children =
+      this->DirectoryState->Children;
+    for (std::vector<cmState::Snapshot>::const_iterator ci = children.begin();
+         ci != children.end(); ++ci) {
+      child_dirs.push_back(ci->GetDirectory().GetCurrentSource());
+    }
+    output = cmJoin(child_dirs, ";");
+    return output.c_str();
+  }
+  if (prop == kBUILDSYSTEM_TARGETS) {
+    output = cmJoin(this->DirectoryState->NormalTargetNames, ";");
+    return output.c_str();
+  }
+
+  if (prop == "LISTFILE_STACK") {
     std::vector<std::string> listFiles;
     cmState::Snapshot snp = this->Snapshot_;
     while (snp.IsValid()) {
@@ -1694,10 +1700,12 @@ const char* cmState::Directory::GetProperty(const std::string& prop,
     std::reverse(listFiles.begin(), listFiles.end());
     output = cmJoin(listFiles, ";");
     return output.c_str();
-  } else if (prop == "CACHE_VARIABLES") {
+  }
+  if (prop == "CACHE_VARIABLES") {
     output = cmJoin(this->Snapshot_.State->GetCacheEntryKeys(), ";");
     return output.c_str();
-  } else if (prop == "VARIABLES") {
+  }
+  if (prop == "VARIABLES") {
     std::vector<std::string> res = this->Snapshot_.ClosureKeys();
     std::vector<std::string> cacheKeys =
       this->Snapshot_.State->GetCacheEntryKeys();
@@ -1705,13 +1713,16 @@ const char* cmState::Directory::GetProperty(const std::string& prop,
     std::sort(res.begin(), res.end());
     output = cmJoin(res, ";");
     return output.c_str();
-  } else if (prop == "INCLUDE_DIRECTORIES") {
+  }
+  if (prop == "INCLUDE_DIRECTORIES") {
     output = cmJoin(this->GetIncludeDirectoriesEntries(), ";");
     return output.c_str();
-  } else if (prop == "COMPILE_OPTIONS") {
+  }
+  if (prop == "COMPILE_OPTIONS") {
     output = cmJoin(this->GetCompileOptionsEntries(), ";");
     return output.c_str();
-  } else if (prop == "COMPILE_DEFINITIONS") {
+  }
+  if (prop == "COMPILE_DEFINITIONS") {
     output = cmJoin(this->GetCompileDefinitionsEntries(), ";");
     return output.c_str();
   }
@@ -1745,6 +1756,11 @@ std::vector<std::string> cmState::Directory::GetPropertyKeys() const
   return keys;
 }
 
+void cmState::Directory::AddNormalTargetName(std::string const& name)
+{
+  this->DirectoryState->NormalTargetNames.push_back(name);
+}
+
 bool operator==(const cmState::Snapshot& lhs, const cmState::Snapshot& rhs)
 {
   return lhs.Position == rhs.Position;
diff --git a/Source/cmState.h b/Source/cmState.h
index 18c45b8..feed1c7 100644
--- a/Source/cmState.h
+++ b/Source/cmState.h
@@ -1,30 +1,27 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmState_h
 #define cmState_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmAlgorithms.h"
+#include "cmDefinitions.h"
 #include "cmLinkedTree.h"
 #include "cmPolicies.h"
+#include "cmProperty.h"
 #include "cmPropertyDefinitionMap.h"
 #include "cmPropertyMap.h"
 
-class cmake;
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+class cmCacheManager;
 class cmCommand;
-class cmDefinitions;
 class cmListFileBacktrace;
-class cmCacheManager;
+class cmPropertyDefinition;
 
 class cmState
 {
@@ -55,7 +52,7 @@ public:
   class Snapshot
   {
   public:
-    Snapshot(cmState* state = 0);
+    Snapshot(cmState* state = CM_NULLPTR);
     Snapshot(cmState* state, PositionType position);
 
     const char* GetDefinition(std::string const& name) const;
@@ -129,9 +126,6 @@ public:
     const char* GetCurrentBinary() const;
     void SetCurrentBinary(std::string const& dir);
 
-    std::vector<std::string> const& GetCurrentSourceComponents() const;
-    std::vector<std::string> const& GetCurrentBinaryComponents() const;
-
     const char* GetRelativePathTopSource() const;
     const char* GetRelativePathTopBinary() const;
     void SetRelativePathTopSource(const char* dir);
@@ -172,6 +166,8 @@ public:
     bool GetPropertyAsBool(const std::string& prop) const;
     std::vector<std::string> GetPropertyKeys() const;
 
+    void AddNormalTargetName(std::string const& name);
+
   private:
     void ComputeRelativePathTopSource();
     void ComputeRelativePathTopBinary();
@@ -247,6 +243,7 @@ public:
                              std::string const& value);
   void SetCacheEntryBoolProperty(std::string const& key,
                                  std::string const& propertyName, bool value);
+  std::vector<std::string> GetCacheEntryPropertyList(std::string const& key);
   const char* GetCacheEntryProperty(std::string const& key,
                                     std::string const& propertyName);
   bool GetCacheEntryPropertyAsBool(std::string const& key,
@@ -305,9 +302,6 @@ public:
   const char* GetBinaryDirectory() const;
   void SetBinaryDirectory(std::string const& binaryDirectory);
 
-  std::vector<std::string> const& GetSourceDirectoryComponents() const;
-  std::vector<std::string> const& GetBinaryDirectoryComponents() const;
-
   void SetWindowsShell(bool windowsShell);
   bool UseWindowsShell() const;
   void SetWindowsVSIDE(bool windowsVSIDE);
@@ -343,8 +337,6 @@ private:
   cmLinkedTree<SnapshotDataType> SnapshotData;
   cmLinkedTree<cmDefinitions> VarTree;
 
-  std::vector<std::string> SourceDirectoryComponents;
-  std::vector<std::string> BinaryDirectoryComponents;
   std::string SourceDirectory;
   std::string BinaryDirectory;
   bool IsInTryCompile;
diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx
index a348aef..c73025a 100644
--- a/Source/cmStringCommand.cxx
+++ b/Source/cmStringCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmStringCommand.h"
 
 #include "cmCryptoHash.h"
@@ -26,7 +17,7 @@
 bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("must be called with at least one argument.");
     return false;
   }
@@ -34,43 +25,61 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
   const std::string& subCommand = args[0];
   if (subCommand == "REGEX") {
     return this->HandleRegexCommand(args);
-  } else if (subCommand == "REPLACE") {
+  }
+  if (subCommand == "REPLACE") {
     return this->HandleReplaceCommand(args);
-  } else if (subCommand == "MD5" || subCommand == "SHA1" ||
-             subCommand == "SHA224" || subCommand == "SHA256" ||
-             subCommand == "SHA384" || subCommand == "SHA512") {
+  }
+  if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
+      subCommand == "SHA256" || subCommand == "SHA384" ||
+      subCommand == "SHA512") {
     return this->HandleHashCommand(args);
-  } else if (subCommand == "TOLOWER") {
+  }
+  if (subCommand == "TOLOWER") {
     return this->HandleToUpperLowerCommand(args, false);
-  } else if (subCommand == "TOUPPER") {
+  }
+  if (subCommand == "TOUPPER") {
     return this->HandleToUpperLowerCommand(args, true);
-  } else if (subCommand == "COMPARE") {
+  }
+  if (subCommand == "COMPARE") {
     return this->HandleCompareCommand(args);
-  } else if (subCommand == "ASCII") {
+  }
+  if (subCommand == "ASCII") {
     return this->HandleAsciiCommand(args);
-  } else if (subCommand == "CONFIGURE") {
+  }
+  if (subCommand == "CONFIGURE") {
     return this->HandleConfigureCommand(args);
-  } else if (subCommand == "LENGTH") {
+  }
+  if (subCommand == "LENGTH") {
     return this->HandleLengthCommand(args);
-  } else if (subCommand == "APPEND") {
+  }
+  if (subCommand == "APPEND") {
     return this->HandleAppendCommand(args);
-  } else if (subCommand == "CONCAT") {
+  }
+  if (subCommand == "CONCAT") {
     return this->HandleConcatCommand(args);
-  } else if (subCommand == "SUBSTRING") {
+  }
+  if (subCommand == "SUBSTRING") {
     return this->HandleSubstringCommand(args);
-  } else if (subCommand == "STRIP") {
+  }
+  if (subCommand == "STRIP") {
     return this->HandleStripCommand(args);
-  } else if (subCommand == "RANDOM") {
+  }
+  if (subCommand == "RANDOM") {
     return this->HandleRandomCommand(args);
-  } else if (subCommand == "FIND") {
+  }
+  if (subCommand == "FIND") {
     return this->HandleFindCommand(args);
-  } else if (subCommand == "TIMESTAMP") {
+  }
+  if (subCommand == "TIMESTAMP") {
     return this->HandleTimestampCommand(args);
-  } else if (subCommand == "MAKE_C_IDENTIFIER") {
+  }
+  if (subCommand == "MAKE_C_IDENTIFIER") {
     return this->HandleMakeCIdentifierCommand(args);
-  } else if (subCommand == "GENEX_STRIP") {
+  }
+  if (subCommand == "GENEX_STRIP") {
     return this->HandleGenexStripCommand(args);
-  } else if (subCommand == "UUID") {
+  }
+  if (subCommand == "UUID") {
     return this->HandleUuidCommand(args);
   }
 
@@ -89,7 +98,7 @@ bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
     return false;
   }
 
-  cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
+  CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
   if (hash.get()) {
     std::string out = hash->HashString(args[2]);
     this->Makefile->AddDefinition(args[1], out.c_str());
@@ -158,7 +167,8 @@ bool cmStringCommand::HandleConfigureCommand(
   if (args.size() < 2) {
     this->SetError("No input string specified.");
     return false;
-  } else if (args.size() < 3) {
+  }
+  if (args.size() < 3) {
     this->SetError("No output variable specified.");
     return false;
   }
@@ -203,14 +213,16 @@ bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
       return false;
     }
     return this->RegexMatch(args);
-  } else if (mode == "MATCHALL") {
+  }
+  if (mode == "MATCHALL") {
     if (args.size() < 5) {
       this->SetError("sub-command REGEX, mode MATCHALL needs "
                      "at least 5 arguments total to command.");
       return false;
     }
     return this->RegexMatchAll(args);
-  } else if (mode == "REPLACE") {
+  }
+  if (mode == "REPLACE") {
     if (args.size() < 6) {
       this->SetError("sub-command REGEX, mode REPLACE needs "
                      "at least 6 arguments total to command.");
@@ -485,7 +497,8 @@ bool cmStringCommand::HandleCompareCommand(
   }
   std::string mode = args[1];
   if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
-      (mode == "GREATER")) {
+      (mode == "LESS_EQUAL") || (mode == "GREATER") ||
+      (mode == "GREATER_EQUAL")) {
     if (args.size() < 5) {
       std::string e = "sub-command COMPARE, mode ";
       e += mode;
@@ -500,8 +513,12 @@ bool cmStringCommand::HandleCompareCommand(
     bool result;
     if (mode == "LESS") {
       result = (left < right);
+    } else if (mode == "LESS_EQUAL") {
+      result = (left <= right);
     } else if (mode == "GREATER") {
       result = (left > right);
+    } else if (mode == "GREATER_EQUAL") {
+      result = (left >= right);
     } else if (mode == "EQUAL") {
       result = (left == right);
     } else // if(mode == "NOTEQUAL")
@@ -780,7 +797,8 @@ bool cmStringCommand::HandleTimestampCommand(
   if (args.size() < 2) {
     this->SetError("sub-command TIMESTAMP requires at least one argument.");
     return false;
-  } else if (args.size() > 4) {
+  }
+  if (args.size() > 4) {
     this->SetError("sub-command TIMESTAMP takes at most three arguments.");
     return false;
   }
diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h
index 23d482c..edb138d 100644
--- a/Source/cmStringCommand.h
+++ b/Source/cmStringCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmStringCommand_h
 #define cmStringCommand_h
 
@@ -29,24 +20,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmStringCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmStringCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "string"; }
+  std::string GetName() const CM_OVERRIDE { return "string"; }
 
   cmTypeMacro(cmStringCommand, cmCommand);
 
diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx
index 401f588..fe7f659 100644
--- a/Source/cmSubdirCommand.cxx
+++ b/Source/cmSubdirCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSubdirCommand.h"
 
 // cmSubdirCommand
 bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmSubdirCommand.h b/Source/cmSubdirCommand.h
index 9da91c4..c425852 100644
--- a/Source/cmSubdirCommand.h
+++ b/Source/cmSubdirCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSubdirCommand_h
 #define cmSubdirCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmSubdirCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSubdirCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "subdirs"; }
+  std::string GetName() const CM_OVERRIDE { return "subdirs"; }
 
   cmTypeMacro(cmSubdirCommand, cmCommand);
 };
diff --git a/Source/cmSubdirDependsCommand.cxx b/Source/cmSubdirDependsCommand.cxx
index c80fb94..b5b4148 100644
--- a/Source/cmSubdirDependsCommand.cxx
+++ b/Source/cmSubdirDependsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSubdirDependsCommand.h"
 
 bool cmSubdirDependsCommand::InitialPass(std::vector<std::string> const&,
diff --git a/Source/cmSubdirDependsCommand.h b/Source/cmSubdirDependsCommand.h
index a15ee3e..0f3deb6 100644
--- a/Source/cmSubdirDependsCommand.h
+++ b/Source/cmSubdirDependsCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSubdirDependsCommand_h
 #define cmSubdirDependsCommand_h
 
@@ -17,10 +8,10 @@
 class cmSubdirDependsCommand : public cmCommand
 {
 public:
-  virtual cmCommand* Clone() { return new cmSubdirDependsCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "subdir_depends"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmSubdirDependsCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "subdir_depends"; }
   cmTypeMacro(cmSubdirDependsCommand, cmCommand);
 };
 
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index 7dece47..3d8fdf5 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -1,31 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSystemTools.h"
 
 #include "cmAlgorithms.h"
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#ifdef __QNX__
-#include <malloc.h> /* for malloc/free on QNX */
-#endif
-#include <cmsys/Directory.hxx>
-#include <cmsys/Encoding.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <cmsys/System.h>
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmArchiveWrite.h"
 #include "cmLocale.h"
@@ -34,8 +12,38 @@
 #define __LA_INT64_T la_int64_t
 #endif
 #endif
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cmCryptoHash.h"
+#endif
+
+#if defined(CMAKE_USE_ELF_PARSER)
+#include "cmELF.h"
+#endif
+
+#if defined(CMAKE_USE_MACH_PARSER)
+#include "cmMachO.h"
+#endif
+
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/Encoding.hxx>
 #include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <cmsys/System.h>
+#include <cmsys/SystemTools.hxx>
 #include <cmsys/Terminal.h>
+#include <ctype.h>
+#include <errno.h>
+#include <iostream>
+#include <set>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
 
 #if defined(_WIN32)
 #include <windows.h>
@@ -43,33 +51,21 @@
 #include <wincrypt.h>
 #else
 #include <sys/time.h>
-#include <sys/types.h>
-#include <sys/wait.h>
 #include <unistd.h>
 #include <utime.h>
 #endif
 
-#if defined(__APPLE__)
-#include <mach-o/dyld.h>
-#endif
-
-#include <sys/stat.h>
-
 #if defined(_WIN32) &&                                                        \
   (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
 #include <io.h>
 #endif
 
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#include "cmCryptoHash.h"
-#endif
-
-#if defined(CMAKE_USE_ELF_PARSER)
-#include "cmELF.h"
+#if defined(__APPLE__)
+#include <mach-o/dyld.h>
 #endif
 
-#if defined(CMAKE_USE_MACH_PARSER)
-#include "cmMachO.h"
+#ifdef __QNX__
+#include <malloc.h> /* for malloc/free on QNX */
 #endif
 
 static bool cm_isspace(char c)
@@ -142,6 +138,7 @@ private:
 };
 #elif defined(__APPLE__)
 #include <crt_externs.h>
+
 #define environ (*_NSGetEnviron())
 #endif
 
@@ -191,7 +188,8 @@ void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
   }
 }
 #else
-void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64)
+void cmSystemTools::ExpandRegistryValues(std::string& source,
+                                         KeyWOW64 /*unused*/)
 {
   cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
   while (regEntry.find(source)) {
@@ -228,14 +226,16 @@ std::string cmSystemTools::HelpFileName(std::string name)
 std::string cmSystemTools::TrimWhitespace(const std::string& s)
 {
   std::string::const_iterator start = s.begin();
-  while (start != s.end() && cm_isspace(*start))
+  while (start != s.end() && cm_isspace(*start)) {
     ++start;
-  if (start == s.end())
+  }
+  if (start == s.end()) {
     return "";
-
+  }
   std::string::const_iterator stop = s.end() - 1;
-  while (cm_isspace(*stop))
+  while (cm_isspace(*stop)) {
     --stop;
+  }
   return std::string(start, stop + 1);
 }
 
@@ -330,9 +330,8 @@ void cmSystemTools::Message(const char* m1, const char* title)
     (*s_MessageCallback)(m1, title, s_DisableMessages,
                          s_MessageCallbackClientData);
     return;
-  } else {
-    std::cerr << m1 << std::endl << std::flush;
   }
+  std::cerr << m1 << std::endl << std::flush;
 }
 
 void cmSystemTools::ReportLastSystemError(const char* msg)
@@ -581,7 +580,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
        a != command.end(); ++a) {
     argv.push_back(a->c_str());
   }
-  argv.push_back(0);
+  argv.push_back(CM_NULLPTR);
 
   cmsysProcess* cp = cmsysProcess_New();
   cmsysProcess_SetCommand(cp, &*argv.begin());
@@ -593,12 +592,12 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
   if (outputflag == OUTPUT_PASSTHROUGH) {
     cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
     cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
-    captureStdOut = 0;
-    captureStdErr = 0;
+    captureStdOut = CM_NULLPTR;
+    captureStdErr = CM_NULLPTR;
   } else if (outputflag == OUTPUT_MERGE ||
              (captureStdErr && captureStdErr == captureStdOut)) {
     cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
-    captureStdErr = 0;
+    captureStdErr = CM_NULLPTR;
   }
   assert(!captureStdErr || captureStdErr != captureStdOut);
 
@@ -612,7 +611,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
   int pipe;
   if (outputflag != OUTPUT_PASSTHROUGH &&
       (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
-    while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, 0)) > 0) {
+    while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) >
+           0) {
       // Translate NULL characters in the output into valid text.
       // Visual Studio 7 puts these characters in the output of its
       // build process.
@@ -640,7 +640,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
     }
   }
 
-  cmsysProcess_WaitForExit(cp, 0);
+  cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   if (captureStdOut) {
     captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
   }
@@ -702,7 +702,7 @@ bool cmSystemTools::RunSingleCommand(const char* command,
 
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
 
-  if (args.size() < 1) {
+  if (args.empty()) {
     return false;
   }
   return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
@@ -1430,7 +1430,7 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
 
   /* Use uname if it's present, else uid. */
   p = archive_entry_uname(entry);
-  if ((p == NULL) || (*p == '\0')) {
+  if ((p == CM_NULLPTR) || (*p == '\0')) {
     sprintf(tmp, "%lu ", (unsigned long)archive_entry_uid(entry));
     p = tmp;
   }
@@ -1441,7 +1441,7 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
   fprintf(out, "%-*s ", (int)u_width, p);
   /* Use gname if it's present, else gid. */
   p = archive_entry_gname(entry);
-  if (p != NULL && p[0] != '\0') {
+  if (p != CM_NULLPTR && p[0] != '\0') {
     fprintf(out, "%s", p);
     w = strlen(p);
   } else {
@@ -1475,7 +1475,7 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
 
   /* Format the time using 'ls -l' conventions. */
   tim = archive_entry_mtime(entry);
-#define HALF_YEAR (time_t)365 * 86400 / 2
+#define HALF_YEAR ((time_t)365 * 86400 / 2)
 #if defined(_WIN32) && !defined(__CYGWIN__)
 /* Windows' strftime function does not support %e format. */
 #define DAY_FMT "%d"
@@ -1684,7 +1684,8 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
     if (pipe == cmsysProcess_Pipe_Timeout) {
       // Timeout has been exceeded.
       return pipe;
-    } else if (pipe == cmsysProcess_Pipe_STDOUT) {
+    }
+    if (pipe == cmsysProcess_Pipe_STDOUT) {
       // Append to the stdout buffer.
       std::vector<char>::size_type size = out.size();
       out.insert(out.end(), data, data + length);
@@ -1700,13 +1701,13 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
         line.append(&out[0], outiter - out.begin());
         out.erase(out.begin(), out.end());
         return cmsysProcess_Pipe_STDOUT;
-      } else if (!err.empty()) {
+      }
+      if (!err.empty()) {
         line.append(&err[0], erriter - err.begin());
         err.erase(err.begin(), err.end());
         return cmsysProcess_Pipe_STDERR;
-      } else {
-        return cmsysProcess_Pipe_None;
       }
+      return cmsysProcess_Pipe_None;
     }
   }
 }
@@ -1756,9 +1757,7 @@ bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
   if (!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite)) {
     return false;
   }
-  if (!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite)) {
-    return false;
-  }
+  return SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite) != 0;
 #else
   struct stat fromStat;
   if (stat(fromFile, &fromStat) < 0) {
@@ -1768,11 +1767,8 @@ bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
   struct utimbuf buf;
   buf.actime = fromStat.st_atime;
   buf.modtime = fromStat.st_mtime;
-  if (utime(toFile, &buf) < 0) {
-    return false;
-  }
+  return utime(toFile, &buf) >= 0;
 #endif
-  return true;
 }
 
 cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
@@ -1818,16 +1814,11 @@ bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
   if (!h) {
     return false;
   }
-  if (!SetFileTime(h, &t->timeCreation, &t->timeLastAccess,
-                   &t->timeLastWrite)) {
-    return false;
-  }
+  return SetFileTime(h, &t->timeCreation, &t->timeLastAccess,
+                     &t->timeLastWrite) != 0;
 #else
-  if (utime(fname, &t->timeBuf) < 0) {
-    return false;
-  }
+  return utime(fname, &t->timeBuf) >= 0;
 #endif
-  return true;
 }
 
 #ifdef _WIN32
@@ -1873,7 +1864,7 @@ unsigned int cmSystemTools::RandomSeed()
 
   // Try using a real random source.
   cmsys::ifstream fin;
-  fin.rdbuf()->pubsetbuf(0, 0); // Unbuffered read.
+  fin.rdbuf()->pubsetbuf(CM_NULLPTR, 0); // Unbuffered read.
   fin.open("/dev/urandom");
   if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
       fin.gcount() == sizeof(seed)) {
@@ -1882,7 +1873,7 @@ unsigned int cmSystemTools::RandomSeed()
 
   // Fall back to the time and pid.
   struct timeval t;
-  gettimeofday(&t, 0);
+  gettimeofday(&t, CM_NULLPTR);
   unsigned int pid = static_cast<unsigned int>(getpid());
   unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
   unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
@@ -1930,11 +1921,11 @@ void cmSystemTools::FindCMakeResources(const char* argv0)
   }
   if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
     // The executable is inside an application bundle.
-    // Look for ../bin (install tree) and then fall back to
+    // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
     // ../../../bin (build tree).
     exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
-    if (cmSystemTools::FileExists((exe_dir + "/bin/cmake").c_str())) {
-      exe_dir += "/bin";
+    if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
+      exe_dir += CMAKE_BIN_DIR;
     } else {
       exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
       exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
@@ -1985,13 +1976,20 @@ void cmSystemTools::FindCMakeResources(const char* argv0)
   }
 
 #ifdef CMAKE_BUILD_WITH_CMAKE
-  // Install tree has "<prefix>/bin/cmake" and "<prefix><CMAKE_DATA_DIR>".
-  std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
-  cmSystemToolsCMakeRoot = dir + CMAKE_DATA_DIR;
-  if (!cmSystemTools::FileExists(
+  // Install tree has
+  // - "<prefix><CMAKE_BIN_DIR>/cmake"
+  // - "<prefix><CMAKE_DATA_DIR>"
+  if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
+    std::string const prefix =
+      exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
+    cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
+  }
+  if (cmSystemToolsCMakeRoot.empty() ||
+      !cmSystemTools::FileExists(
         (cmSystemToolsCMakeRoot + "/Modules/CMake.cmake").c_str())) {
     // Build tree has "<build>/bin[/<config>]/cmake" and
     // "<build>/CMakeFiles/CMakeSourceDir.txt".
+    std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
     std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
     cmsys::ifstream fin(src_dir_txt.c_str());
     std::string src_dir;
@@ -2059,9 +2057,9 @@ void cmSystemTools::MakefileColorEcho(int color, const char* message,
   // However, we can test for some situations when the answer is most
   // likely no.
   int assumeTTY = cmsysTerminal_Color_AssumeTTY;
-  if (cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
-      cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
-      cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
+  if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
+      cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
+      cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
     // Avoid printing color escapes during dashboard builds.
     assumeTTY = 0;
   }
@@ -2108,11 +2106,8 @@ bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
   // If the symlink points at an extended version of the same name
   // assume it is the soname.
   std::string name = cmSystemTools::GetFilenameName(fullPath);
-  if (soname.length() > name.length() &&
-      soname.substr(0, name.length()) == name) {
-    return true;
-  }
-  return false;
+  return soname.length() > name.length() &&
+    soname.compare(0, name.length(), name) == 0;
 }
 
 bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
@@ -2193,8 +2188,8 @@ bool cmSystemTools::ChangeRPath(std::string const& file,
 
     // Get the RPATH and RUNPATH entries from it.
     int se_count = 0;
-    cmELF::StringEntry const* se[2] = { 0, 0 };
-    const char* se_name[2] = { 0, 0 };
+    cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
+    const char* se_name[2] = { CM_NULLPTR, CM_NULLPTR };
     if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
       se[se_count] = se_rpath;
       se_name[se_count] = "RPATH";
@@ -2210,13 +2205,12 @@ bool cmSystemTools::ChangeRPath(std::string const& file,
         // The new rpath is empty and there is no rpath anyway so it is
         // okay.
         return true;
-      } else {
-        if (emsg) {
-          *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
-          *emsg += elf.GetErrorMessage();
-        }
-        return false;
       }
+      if (emsg) {
+        *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
+        *emsg += elf.GetErrorMessage();
+      }
+      return false;
     }
 
     for (int i = 0; i < se_count; ++i) {
@@ -2373,10 +2367,11 @@ bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
 
     if (lhs < rhs) {
       // lhs < rhs, so true if operation is LESS
-      return op == cmSystemTools::OP_LESS;
-    } else if (lhs > rhs) {
+      return (op & cmSystemTools::OP_LESS) != 0;
+    }
+    if (lhs > rhs) {
       // lhs > rhs, so true if operation is GREATER
-      return op == cmSystemTools::OP_GREATER;
+      return (op & cmSystemTools::OP_GREATER) != 0;
     }
 
     if (*endr == '.') {
@@ -2388,7 +2383,7 @@ bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
     }
   }
   // lhs == rhs, so true if operation is EQUAL
-  return op == cmSystemTools::OP_EQUAL;
+  return (op & cmSystemTools::OP_EQUAL) != 0;
 }
 
 bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
@@ -2405,6 +2400,90 @@ bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
                                        rhs.c_str());
 }
 
+bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
+                                            std::string const& rhs)
+{
+  return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
+                                       lhs.c_str(), rhs.c_str());
+}
+
+static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
+                                                         const char* rhs)
+{
+  size_t i = 0;
+  /* Step forward until we find a difference or both strings end together.
+     The difference may lie on the null-terminator of one string.  */
+  while (lhs[i] == rhs[i] && lhs[i] != 0) {
+    ++i;
+  }
+  return i;
+}
+
+static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
+{
+  /* Step back until we are not preceded by a digit.  */
+  while (i > 0 && isdigit(s[i - 1])) {
+    --i;
+  }
+  return i;
+}
+
+static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
+{
+  /* Step forward over digits.  */
+  while (isdigit(s[i])) {
+    ++i;
+  }
+  return i;
+}
+
+static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
+{
+  size_t i = b;
+  /* Step forward over zeros that are followed by another digit.  */
+  while (s[i] == '0' && isdigit(s[i + 1])) {
+    ++i;
+  }
+  return i - b;
+}
+
+static int cm_strverscmp(const char* lhs, const char* rhs)
+{
+  size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
+  if (lhs[i] != rhs[i]) {
+    /* The strings differ starting at 'i'.  Check for a digit sequence.  */
+    size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
+    if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
+      /* A digit sequence starts at 'b', preceding or at 'i'.  */
+
+      /* Look for leading zeros, implying a leading decimal point.  */
+      size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
+      size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
+      if (lhs_zeros != rhs_zeros) {
+        /* The side with more leading zeros orders first.  */
+        return rhs_zeros > lhs_zeros ? 1 : -1;
+      }
+      if (lhs_zeros == 0) {
+        /* No leading zeros; compare digit sequence lengths.  */
+        size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
+        size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
+        if (lhs_end != rhs_end) {
+          /* The side with fewer digits orders first.  */
+          return lhs_end > rhs_end ? 1 : -1;
+        }
+      }
+    }
+  }
+
+  /* Ordering was not decided by digit sequence lengths; compare bytes.  */
+  return lhs[i] - rhs[i];
+}
+
+int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
+{
+  return cm_strverscmp(lhs.c_str(), rhs.c_str());
+}
+
 bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
                                 bool* removed)
 {
@@ -2424,7 +2503,7 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
     // Get the RPATH and RUNPATH entries from it and sort them by index
     // in the dynamic section header.
     int se_count = 0;
-    cmELF::StringEntry const* se[2] = { 0, 0 };
+    cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
     if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
       se[se_count++] = se_rpath;
     }
diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h
index df2c1f7..9817a3c 100644
--- a/Source/cmSystemTools.h
+++ b/Source/cmSystemTools.h
@@ -1,21 +1,15 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmSystemTools_h
 #define cmSystemTools_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <cmsys/Process.h>
 #include <cmsys/SystemTools.hxx>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 class cmSystemToolsFileTime;
 
@@ -64,33 +58,35 @@ public:
    *  title as a const char*, and a reference to bool that when
    *  set to false, will disable furthur messages (cancel).
    */
-  static void SetMessageCallback(MessageCallback f, void* clientData = 0);
+  static void SetMessageCallback(MessageCallback f,
+                                 void* clientData = CM_NULLPTR);
 
   /**
    * Display an error message.
    */
-  static void Error(const char* m, const char* m2 = 0, const char* m3 = 0,
-                    const char* m4 = 0);
+  static void Error(const char* m, const char* m2 = CM_NULLPTR,
+                    const char* m3 = CM_NULLPTR, const char* m4 = CM_NULLPTR);
 
   /**
    * Display a message.
    */
-  static void Message(const char* m, const char* title = 0);
+  static void Message(const char* m, const char* title = CM_NULLPTR);
 
   typedef void (*OutputCallback)(const char*, size_t length, void*);
 
   ///! Send a string to stdout
   static void Stdout(const char* s);
   static void Stdout(const char* s, size_t length);
-  static void SetStdoutCallback(OutputCallback, void* clientData = 0);
+  static void SetStdoutCallback(OutputCallback, void* clientData = CM_NULLPTR);
 
   ///! Send a string to stderr
   static void Stderr(const char* s);
   static void Stderr(const char* s, size_t length);
-  static void SetStderrCallback(OutputCallback, void* clientData = 0);
+  static void SetStderrCallback(OutputCallback, void* clientData = CM_NULLPTR);
 
   typedef bool (*InterruptCallback)(void*);
-  static void SetInterruptCallback(InterruptCallback f, void* clientData = 0);
+  static void SetInterruptCallback(InterruptCallback f,
+                                   void* clientData = CM_NULLPTR);
   static bool GetInterruptFlag();
 
   ///! Return true if there was an error at any point.
@@ -220,9 +216,10 @@ public:
     OUTPUT_PASSTHROUGH
   };
   static bool RunSingleCommand(const char* command,
-                               std::string* captureStdOut = 0,
-                               std::string* captureStdErr = 0, int* retVal = 0,
-                               const char* dir = 0,
+                               std::string* captureStdOut = CM_NULLPTR,
+                               std::string* captureStdErr = CM_NULLPTR,
+                               int* retVal = CM_NULLPTR,
+                               const char* dir = CM_NULLPTR,
                                OutputOption outputflag = OUTPUT_MERGE,
                                double timeout = 0.0);
   /**
@@ -231,9 +228,10 @@ public:
    * be in comand[1]...command[command.size()]
    */
   static bool RunSingleCommand(std::vector<std::string> const& command,
-                               std::string* captureStdOut = 0,
-                               std::string* captureStdErr = 0, int* retVal = 0,
-                               const char* dir = 0,
+                               std::string* captureStdOut = CM_NULLPTR,
+                               std::string* captureStdErr = CM_NULLPTR,
+                               int* retVal = CM_NULLPTR,
+                               const char* dir = CM_NULLPTR,
                                OutputOption outputflag = OUTPUT_MERGE,
                                double timeout = 0.0);
 
@@ -280,9 +278,11 @@ public:
 
   enum CompareOp
   {
-    OP_LESS,
-    OP_GREATER,
-    OP_EQUAL
+    OP_EQUAL = 1,
+    OP_LESS = 2,
+    OP_GREATER = 4,
+    OP_LESS_EQUAL = OP_LESS | OP_EQUAL,
+    OP_GREATER_EQUAL = OP_GREATER | OP_EQUAL
   };
 
   /**
@@ -293,6 +293,18 @@ public:
                                   std::string const& rhs);
   static bool VersionCompareGreater(std::string const& lhs,
                                     std::string const& rhs);
+  static bool VersionCompareGreaterEq(std::string const& lhs,
+                                      std::string const& rhs);
+
+  /**
+   * Compare two ASCII strings using natural versioning order.
+   * Non-numerical characters are compared directly.
+   * Numerical characters are first globbed such that, e.g.
+   * `test000 < test01 < test0 < test1 < test10`.
+   * Return a value less than, equal to, or greater than zero if lhs
+   * precedes, equals, or succeeds rhs in the defined ordering.
+   */
+  static int strverscmp(std::string const& lhs, std::string const& rhs);
 
   /**
    * Determine the file type based on the extension
@@ -435,12 +447,14 @@ public:
 
   /** Try to set the RPATH in an ELF binary.  */
   static bool ChangeRPath(std::string const& file, std::string const& oldRPath,
-                          std::string const& newRPath, std::string* emsg = 0,
-                          bool* changed = 0);
+                          std::string const& newRPath,
+                          std::string* emsg = CM_NULLPTR,
+                          bool* changed = CM_NULLPTR);
 
   /** Try to remove the RPATH from an ELF binary.  */
-  static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
-                          bool* removed = 0);
+  static bool RemoveRPath(std::string const& file,
+                          std::string* emsg = CM_NULLPTR,
+                          bool* removed = CM_NULLPTR);
 
   /** Check whether the RPATH in an ELF binary contains the path
       given.  */
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index f435a1d..54e0bea 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -1,33 +1,32 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTarget.h"
 
 #include "cmAlgorithms.h"
-#include "cmComputeLinkInformation.h"
 #include "cmGeneratorExpression.h"
-#include "cmGeneratorExpressionDAGChecker.h"
+#include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmListFileCache.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
+#include "cmProperty.h"
 #include "cmSourceFile.h"
+#include "cmSourceFileLocation.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
+
+#include <algorithm>
 #include <assert.h>
 #include <cmsys/RegularExpression.hxx>
-#include <errno.h>
 #include <map>
 #include <set>
-#include <stdlib.h> // required for atof
-#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <sstream>
+#include <string.h>
+
+#if defined(CMake_HAVE_CXX_UNORDERED_SET)
+#include <unordered_set>
+#define UNORDERED_SET std::unordered_set
+#elif defined(CMAKE_BUILD_WITH_CMAKE)
 #include <cmsys/hash_set.hxx>
 #define UNORDERED_SET cmsys::hash_set
 #else
@@ -51,34 +50,28 @@ public:
   std::vector<cmListFileBacktrace> LinkImplementationPropertyBacktraces;
 };
 
-cmTarget::cmTarget()
+cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
+                   Visibility vis, cmMakefile* mf)
 {
-  this->Makefile = 0;
+  assert(mf);
+  this->Name = name;
+  this->TargetTypeValue = type;
+  this->Makefile = mf;
   this->HaveInstallRule = false;
   this->DLLPlatform = false;
   this->IsAndroid = false;
-  this->IsImportedTarget = false;
-  this->ImportedGloballyVisible = false;
+  this->IsImportedTarget =
+    (vis == VisibilityImported || vis == VisibilityImportedGlobally);
+  this->ImportedGloballyVisible = vis == VisibilityImportedGlobally;
   this->BuildInterfaceIncludesAppended = false;
-}
 
-void cmTarget::SetType(cmState::TargetType type, const std::string& name)
-{
-  this->Name = name;
   // only add dependency information for library targets
-  this->TargetTypeValue = type;
   if (this->TargetTypeValue >= cmState::STATIC_LIBRARY &&
       this->TargetTypeValue <= cmState::MODULE_LIBRARY) {
     this->RecordDependencies = true;
   } else {
     this->RecordDependencies = false;
   }
-}
-
-void cmTarget::SetMakefile(cmMakefile* mf)
-{
-  // Set our makefile.
-  this->Makefile = mf;
 
   // Check whether this is a DLL platform.
   this->DLLPlatform =
@@ -93,63 +86,64 @@ void cmTarget::SetMakefile(cmMakefile* mf)
   // Setup default property values.
   if (this->GetType() != cmState::INTERFACE_LIBRARY &&
       this->GetType() != cmState::UTILITY) {
-    this->SetPropertyDefault("ANDROID_API", 0);
-    this->SetPropertyDefault("ANDROID_API_MIN", 0);
-    this->SetPropertyDefault("ANDROID_ARCH", 0);
-    this->SetPropertyDefault("ANDROID_STL_TYPE", 0);
-    this->SetPropertyDefault("ANDROID_SKIP_ANT_STEP", 0);
-    this->SetPropertyDefault("ANDROID_PROCESS_MAX", 0);
-    this->SetPropertyDefault("ANDROID_PROGUARD", 0);
-    this->SetPropertyDefault("ANDROID_PROGUARD_CONFIG_PATH", 0);
-    this->SetPropertyDefault("ANDROID_SECURE_PROPS_PATH", 0);
-    this->SetPropertyDefault("ANDROID_NATIVE_LIB_DIRECTORIES", 0);
-    this->SetPropertyDefault("ANDROID_NATIVE_LIB_DEPENDENCIES", 0);
-    this->SetPropertyDefault("ANDROID_JAVA_SOURCE_DIR", 0);
-    this->SetPropertyDefault("ANDROID_JAR_DIRECTORIES", 0);
-    this->SetPropertyDefault("ANDROID_JAR_DEPENDENCIES", 0);
-    this->SetPropertyDefault("ANDROID_ASSETS_DIRECTORIES", 0);
-    this->SetPropertyDefault("ANDROID_ANT_ADDITIONAL_OPTIONS", 0);
-    this->SetPropertyDefault("INSTALL_NAME_DIR", 0);
+    this->SetPropertyDefault("ANDROID_API", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_API_MIN", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_ARCH", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_STL_TYPE", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_SKIP_ANT_STEP", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_PROCESS_MAX", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_PROGUARD", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_PROGUARD_CONFIG_PATH", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_SECURE_PROPS_PATH", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_NATIVE_LIB_DIRECTORIES", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_NATIVE_LIB_DEPENDENCIES", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_JAVA_SOURCE_DIR", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_JAR_DIRECTORIES", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_JAR_DEPENDENCIES", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_ASSETS_DIRECTORIES", CM_NULLPTR);
+    this->SetPropertyDefault("ANDROID_ANT_ADDITIONAL_OPTIONS", CM_NULLPTR);
+    this->SetPropertyDefault("INSTALL_NAME_DIR", CM_NULLPTR);
     this->SetPropertyDefault("INSTALL_RPATH", "");
     this->SetPropertyDefault("INSTALL_RPATH_USE_LINK_PATH", "OFF");
     this->SetPropertyDefault("SKIP_BUILD_RPATH", "OFF");
     this->SetPropertyDefault("BUILD_WITH_INSTALL_RPATH", "OFF");
-    this->SetPropertyDefault("ARCHIVE_OUTPUT_DIRECTORY", 0);
-    this->SetPropertyDefault("LIBRARY_OUTPUT_DIRECTORY", 0);
-    this->SetPropertyDefault("RUNTIME_OUTPUT_DIRECTORY", 0);
-    this->SetPropertyDefault("PDB_OUTPUT_DIRECTORY", 0);
-    this->SetPropertyDefault("COMPILE_PDB_OUTPUT_DIRECTORY", 0);
-    this->SetPropertyDefault("Fortran_FORMAT", 0);
-    this->SetPropertyDefault("Fortran_MODULE_DIRECTORY", 0);
-    this->SetPropertyDefault("GNUtoMS", 0);
-    this->SetPropertyDefault("OSX_ARCHITECTURES", 0);
-    this->SetPropertyDefault("IOS_INSTALL_COMBINED", 0);
-    this->SetPropertyDefault("AUTOMOC", 0);
-    this->SetPropertyDefault("AUTOUIC", 0);
-    this->SetPropertyDefault("AUTORCC", 0);
-    this->SetPropertyDefault("AUTOMOC_MOC_OPTIONS", 0);
-    this->SetPropertyDefault("AUTOUIC_OPTIONS", 0);
-    this->SetPropertyDefault("AUTORCC_OPTIONS", 0);
-    this->SetPropertyDefault("LINK_DEPENDS_NO_SHARED", 0);
-    this->SetPropertyDefault("LINK_INTERFACE_LIBRARIES", 0);
-    this->SetPropertyDefault("WIN32_EXECUTABLE", 0);
-    this->SetPropertyDefault("MACOSX_BUNDLE", 0);
-    this->SetPropertyDefault("MACOSX_RPATH", 0);
-    this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", 0);
-    this->SetPropertyDefault("C_CLANG_TIDY", 0);
-    this->SetPropertyDefault("C_COMPILER_LAUNCHER", 0);
-    this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", 0);
-    this->SetPropertyDefault("C_STANDARD", 0);
-    this->SetPropertyDefault("C_STANDARD_REQUIRED", 0);
-    this->SetPropertyDefault("C_EXTENSIONS", 0);
-    this->SetPropertyDefault("CXX_CLANG_TIDY", 0);
-    this->SetPropertyDefault("CXX_COMPILER_LAUNCHER", 0);
-    this->SetPropertyDefault("CXX_INCLUDE_WHAT_YOU_USE", 0);
-    this->SetPropertyDefault("CXX_STANDARD", 0);
-    this->SetPropertyDefault("CXX_STANDARD_REQUIRED", 0);
-    this->SetPropertyDefault("CXX_EXTENSIONS", 0);
-    this->SetPropertyDefault("LINK_SEARCH_START_STATIC", 0);
-    this->SetPropertyDefault("LINK_SEARCH_END_STATIC", 0);
+    this->SetPropertyDefault("ARCHIVE_OUTPUT_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("LIBRARY_OUTPUT_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("RUNTIME_OUTPUT_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("PDB_OUTPUT_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("COMPILE_PDB_OUTPUT_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("Fortran_FORMAT", CM_NULLPTR);
+    this->SetPropertyDefault("Fortran_MODULE_DIRECTORY", CM_NULLPTR);
+    this->SetPropertyDefault("GNUtoMS", CM_NULLPTR);
+    this->SetPropertyDefault("OSX_ARCHITECTURES", CM_NULLPTR);
+    this->SetPropertyDefault("IOS_INSTALL_COMBINED", CM_NULLPTR);
+    this->SetPropertyDefault("AUTOMOC", CM_NULLPTR);
+    this->SetPropertyDefault("AUTOUIC", CM_NULLPTR);
+    this->SetPropertyDefault("AUTORCC", CM_NULLPTR);
+    this->SetPropertyDefault("AUTOMOC_MOC_OPTIONS", CM_NULLPTR);
+    this->SetPropertyDefault("AUTOUIC_OPTIONS", CM_NULLPTR);
+    this->SetPropertyDefault("AUTORCC_OPTIONS", CM_NULLPTR);
+    this->SetPropertyDefault("LINK_DEPENDS_NO_SHARED", CM_NULLPTR);
+    this->SetPropertyDefault("LINK_INTERFACE_LIBRARIES", CM_NULLPTR);
+    this->SetPropertyDefault("WIN32_EXECUTABLE", CM_NULLPTR);
+    this->SetPropertyDefault("MACOSX_BUNDLE", CM_NULLPTR);
+    this->SetPropertyDefault("MACOSX_RPATH", CM_NULLPTR);
+    this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
+    this->SetPropertyDefault("C_CLANG_TIDY", CM_NULLPTR);
+    this->SetPropertyDefault("C_COMPILER_LAUNCHER", CM_NULLPTR);
+    this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
+    this->SetPropertyDefault("LINK_WHAT_YOU_USE", CM_NULLPTR);
+    this->SetPropertyDefault("C_STANDARD", CM_NULLPTR);
+    this->SetPropertyDefault("C_STANDARD_REQUIRED", CM_NULLPTR);
+    this->SetPropertyDefault("C_EXTENSIONS", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_CLANG_TIDY", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_COMPILER_LAUNCHER", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_STANDARD", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_STANDARD_REQUIRED", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_EXTENSIONS", CM_NULLPTR);
+    this->SetPropertyDefault("LINK_SEARCH_START_STATIC", CM_NULLPTR);
+    this->SetPropertyDefault("LINK_SEARCH_END_STATIC", CM_NULLPTR);
   }
 
   // Collect the set of configuration types.
@@ -166,7 +160,7 @@ void cmTarget::SetMakefile(cmMakefile* mf)
       "PDB_OUTPUT_DIRECTORY_",
       "COMPILE_PDB_OUTPUT_DIRECTORY_",
       "MAP_IMPORTED_CONFIG_",
-      0
+      CM_NULLPTR
     };
     for (std::vector<std::string>::iterator ci = configNames.begin();
          ci != configNames.end(); ++ci) {
@@ -178,7 +172,7 @@ void cmTarget::SetMakefile(cmMakefile* mf)
         }
         std::string property = *p;
         property += configUpper;
-        this->SetPropertyDefault(property, 0);
+        this->SetPropertyDefault(property, CM_NULLPTR);
       }
 
       // Initialize per-configuration name postfix property from the
@@ -190,7 +184,7 @@ void cmTarget::SetMakefile(cmMakefile* mf)
           this->TargetTypeValue != cmState::INTERFACE_LIBRARY) {
         std::string property = cmSystemTools::UpperCase(*ci);
         property += "_POSTFIX";
-        this->SetPropertyDefault(property, 0);
+        this->SetPropertyDefault(property, CM_NULLPTR);
       }
     }
   }
@@ -234,27 +228,28 @@ void cmTarget::SetMakefile(cmMakefile* mf)
 
   if (this->GetType() != cmState::INTERFACE_LIBRARY &&
       this->GetType() != cmState::UTILITY) {
-    this->SetPropertyDefault("C_VISIBILITY_PRESET", 0);
-    this->SetPropertyDefault("CXX_VISIBILITY_PRESET", 0);
-    this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", 0);
+    this->SetPropertyDefault("C_VISIBILITY_PRESET", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_VISIBILITY_PRESET", CM_NULLPTR);
+    this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", CM_NULLPTR);
   }
 
   if (this->TargetTypeValue == cmState::EXECUTABLE) {
-    this->SetPropertyDefault("ANDROID_GUI", 0);
-    this->SetPropertyDefault("CROSSCOMPILING_EMULATOR", 0);
-    this->SetPropertyDefault("ENABLE_EXPORTS", 0);
+    this->SetPropertyDefault("ANDROID_GUI", CM_NULLPTR);
+    this->SetPropertyDefault("CROSSCOMPILING_EMULATOR", CM_NULLPTR);
+    this->SetPropertyDefault("ENABLE_EXPORTS", CM_NULLPTR);
   }
   if (this->TargetTypeValue == cmState::SHARED_LIBRARY ||
       this->TargetTypeValue == cmState::MODULE_LIBRARY) {
     this->SetProperty("POSITION_INDEPENDENT_CODE", "True");
   }
-  if (this->TargetTypeValue == cmState::SHARED_LIBRARY) {
-    this->SetPropertyDefault("WINDOWS_EXPORT_ALL_SYMBOLS", 0);
+  if (this->TargetTypeValue == cmState::SHARED_LIBRARY ||
+      this->TargetTypeValue == cmState::EXECUTABLE) {
+    this->SetPropertyDefault("WINDOWS_EXPORT_ALL_SYMBOLS", CM_NULLPTR);
   }
 
   if (this->GetType() != cmState::INTERFACE_LIBRARY &&
       this->GetType() != cmState::UTILITY) {
-    this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", 0);
+    this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", CM_NULLPTR);
   }
 
   // Record current policies for later use.
@@ -269,8 +264,8 @@ void cmTarget::SetMakefile(cmMakefile* mf)
 
   if (this->GetType() != cmState::INTERFACE_LIBRARY &&
       this->GetType() != cmState::UTILITY) {
-    this->SetPropertyDefault("JOB_POOL_COMPILE", 0);
-    this->SetPropertyDefault("JOB_POOL_LINK", 0);
+    this->SetPropertyDefault("JOB_POOL_COMPILE", CM_NULLPTR);
+    this->SetPropertyDefault("JOB_POOL_LINK", CM_NULLPTR);
   }
 }
 
@@ -287,8 +282,9 @@ cmListFileBacktrace const* cmTarget::GetUtilityBacktrace(
 {
   std::map<std::string, cmListFileBacktrace>::const_iterator i =
     this->UtilityBacktraces.find(u);
-  if (i == this->UtilityBacktraces.end())
-    return 0;
+  if (i == this->UtilityBacktraces.end()) {
+    return CM_NULLPTR;
+  }
 
   return &i->second;
 }
@@ -403,7 +399,7 @@ cmSourceFile* cmTarget::AddSourceCMP0049(const std::string& s)
 {
   std::string src = this->ProcessSourceItemCMP0049(s);
   if (!s.empty() && src.empty()) {
-    return 0;
+    return CM_NULLPTR;
   }
   return this->AddSource(src);
 }
@@ -474,7 +470,7 @@ cmSourceFile* cmTarget::AddSource(const std::string& src)
     this->Internal->SourceBacktraces.push_back(lfbt);
   }
   if (cmGeneratorExpression::Find(src) != std::string::npos) {
-    return 0;
+    return CM_NULLPTR;
   }
   return this->Makefile->GetOrCreateSource(src);
 }
@@ -580,8 +576,7 @@ bool cmTarget::PushTLLCommandTrace(TLLSignature signature,
   return ret;
 }
 
-void cmTarget::GetTllSignatureTraces(std::ostringstream& s,
-                                     TLLSignature sig) const
+void cmTarget::GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const
 {
   const char* sigString =
     (sig == cmTarget::KeywordTLLSignature ? "keyword" : "plain");
@@ -592,7 +587,8 @@ void cmTarget::GetTllSignatureTraces(std::ostringstream& s,
        it != this->TLLCommands.end(); ++it) {
     if (it->first == sig) {
       cmListFileContext lfc = it->second;
-      lfc.FilePath = converter.Convert(lfc.FilePath, cmOutputConverter::HOME);
+      lfc.FilePath = converter.ConvertToRelativePath(
+        this->Makefile->GetState()->GetSourceDirectory(), lfc.FilePath);
       s << " * " << lfc << std::endl;
     }
   }
@@ -764,12 +760,14 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
       << prop << "\" is not allowed.";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
-  } else if (prop == "NAME") {
+  }
+  if (prop == "NAME") {
     std::ostringstream e;
     e << "NAME property is read-only\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
-  } else if (prop == "INCLUDE_DIRECTORIES") {
+  }
+  if (prop == "INCLUDE_DIRECTORIES") {
     this->Internal->IncludeDirectoriesEntries.clear();
     this->Internal->IncludeDirectoriesBacktraces.clear();
     if (value) {
@@ -846,12 +844,14 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
       << prop << "\" is not allowed.";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
-  } else if (prop == "NAME") {
+  }
+  if (prop == "NAME") {
     std::ostringstream e;
     e << "NAME property is read-only\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
-  } else if (prop == "INCLUDE_DIRECTORIES") {
+  }
+  if (prop == "INCLUDE_DIRECTORIES") {
     if (value && *value) {
       this->Internal->IncludeDirectoriesEntries.push_back(value);
       cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
@@ -1047,19 +1047,13 @@ void cmTarget::CheckProperty(const std::string& prop,
   }
 }
 
-void cmTarget::MarkAsImported(bool global)
-{
-  this->IsImportedTarget = true;
-  this->ImportedGloballyVisible = global;
-}
-
 bool cmTarget::HandleLocationPropertyPolicy(cmMakefile* context) const
 {
   if (this->IsImported()) {
     return true;
   }
   std::ostringstream e;
-  const char* modal = 0;
+  const char* modal = CM_NULLPTR;
   cmake::MessageType messageType = cmake::AUTHOR_WARNING;
   switch (context->GetPolicyStatus(cmPolicies::CMP0026)) {
     case cmPolicies::WARN:
@@ -1101,7 +1095,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
          "The property \""
       << prop << "\" is not allowed.";
     context->IssueMessage(cmake::FATAL_ERROR, e.str());
-    return 0;
+    return CM_NULLPTR;
   }
 
   // Watch for special "computed" properties that are dependent on
@@ -1114,7 +1108,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
     static const std::string propLOCATION = "LOCATION";
     if (prop == propLOCATION) {
       if (!this->HandleLocationPropertyPolicy(context)) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       // Set the LOCATION property of the target.
@@ -1143,7 +1137,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
     // Support "LOCATION_<CONFIG>".
     else if (cmHasLiteralPrefix(prop, "LOCATION_")) {
       if (!this->HandleLocationPropertyPolicy(context)) {
-        return 0;
+        return CM_NULLPTR;
       }
       const char* configName = prop.c_str() + 9;
 
@@ -1161,11 +1155,12 @@ const char* cmTarget::GetProperty(const std::string& prop,
       }
     }
     // Support "<CONFIG>_LOCATION".
-    else if (cmHasLiteralSuffix(prop, "_LOCATION")) {
+    else if (cmHasLiteralSuffix(prop, "_LOCATION") &&
+             !cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
       std::string configName(prop.c_str(), prop.size() - 9);
       if (configName != "IMPORTED") {
         if (!this->HandleLocationPropertyPolicy(context)) {
-          return 0;
+          return CM_NULLPTR;
         }
         if (this->IsImported()) {
           this->Properties.SetProperty(
@@ -1212,7 +1207,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
   if (specialProps.count(prop)) {
     if (prop == propLINK_LIBRARIES) {
       if (this->Internal->LinkImplementationPropertyEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       static std::string output;
@@ -1220,51 +1215,60 @@ const char* cmTarget::GetProperty(const std::string& prop,
       return output.c_str();
     }
     // the type property returns what type the target is
-    else if (prop == propTYPE) {
+    if (prop == propTYPE) {
       return cmState::GetTargetTypeName(this->GetType());
-    } else if (prop == propINCLUDE_DIRECTORIES) {
+    }
+    if (prop == propINCLUDE_DIRECTORIES) {
       if (this->Internal->IncludeDirectoriesEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       static std::string output;
       output = cmJoin(this->Internal->IncludeDirectoriesEntries, ";");
       return output.c_str();
-    } else if (prop == propCOMPILE_FEATURES) {
+    }
+    if (prop == propCOMPILE_FEATURES) {
       if (this->Internal->CompileFeaturesEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       static std::string output;
       output = cmJoin(this->Internal->CompileFeaturesEntries, ";");
       return output.c_str();
-    } else if (prop == propCOMPILE_OPTIONS) {
+    }
+    if (prop == propCOMPILE_OPTIONS) {
       if (this->Internal->CompileOptionsEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       static std::string output;
       output = cmJoin(this->Internal->CompileOptionsEntries, ";");
       return output.c_str();
-    } else if (prop == propCOMPILE_DEFINITIONS) {
+    }
+    if (prop == propCOMPILE_DEFINITIONS) {
       if (this->Internal->CompileDefinitionsEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       static std::string output;
       output = cmJoin(this->Internal->CompileDefinitionsEntries, ";");
       return output.c_str();
-    } else if (prop == propIMPORTED) {
+    }
+    if (prop == propIMPORTED) {
       return this->IsImported() ? "TRUE" : "FALSE";
-    } else if (prop == propNAME) {
+    }
+    if (prop == propNAME) {
       return this->GetName().c_str();
-    } else if (prop == propBINARY_DIR) {
+    }
+    if (prop == propBINARY_DIR) {
       return this->GetMakefile()->GetCurrentBinaryDirectory();
-    } else if (prop == propSOURCE_DIR) {
+    }
+    if (prop == propSOURCE_DIR) {
       return this->GetMakefile()->GetCurrentSourceDirectory();
-    } else if (prop == propSOURCES) {
+    }
+    if (prop == propSOURCES) {
       if (this->Internal->SourceEntries.empty()) {
-        return 0;
+        return CM_NULLPTR;
       }
 
       std::ostringstream ss;
@@ -1429,8 +1433,8 @@ std::string cmTarget::ImportedGetFullPath(const std::string& config,
 
   std::string result;
 
-  const char* loc = 0;
-  const char* imp = 0;
+  const char* loc = CM_NULLPTR;
+  const char* imp = CM_NULLPTR;
   std::string suffix;
 
   if (this->GetType() != cmState::INTERFACE_LIBRARY &&
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index 71ba0cd..dd9097a 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -1,43 +1,37 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTarget_h
 #define cmTarget_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
+#include "cmAlgorithms.h"
 #include "cmCustomCommand.h"
 #include "cmListFileCache.h"
 #include "cmPolicies.h"
 #include "cmPropertyMap.h"
+#include "cmState.h"
+#include "cmTargetLinkLibraryType.h"
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
 
-#include <cmsys/auto_ptr.hxx>
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 #include <unordered_map>
 #else
 #include <cmsys/hash_map.hxx>
 #endif
 #endif
 
-class cmake;
 class cmMakefile;
 class cmSourceFile;
-class cmGlobalGenerator;
-class cmListFileBacktrace;
-class cmTarget;
-class cmGeneratorTarget;
-class cmTargetTraceDependencies;
-
 class cmTargetInternals;
+
 class cmTargetInternalPointer
 {
 public:
@@ -60,7 +54,16 @@ private:
 class cmTarget
 {
 public:
-  cmTarget();
+  enum Visibility
+  {
+    VisibilityNormal,
+    VisibilityImported,
+    VisibilityImportedGlobally
+  };
+
+  cmTarget(std::string const& name, cmState::TargetType type, Visibility vis,
+           cmMakefile* mf);
+
   enum CustomCommandType
   {
     PRE_BUILD,
@@ -73,18 +76,10 @@ public:
    */
   cmState::TargetType GetType() const { return this->TargetTypeValue; }
 
-  /**
-   * Set the target type
-   */
-  void SetType(cmState::TargetType f, const std::string& name);
-
-  void MarkAsImported(bool global = false);
-
   ///! Set/Get the name of the target
   const std::string& GetName() const { return this->Name; }
 
-  ///! Set the cmMakefile that owns this target
-  void SetMakefile(cmMakefile* mf);
+  /** Get the cmMakefile that owns this target.  */
   cmMakefile* GetMakefile() const { return this->Makefile; }
 
 #define DECLARE_TARGET_POLICY(POLICY)                                         \
@@ -156,7 +151,7 @@ public:
   };
   bool PushTLLCommandTrace(TLLSignature signature,
                            cmListFileContext const& lfc);
-  void GetTllSignatureTraces(std::ostringstream& s, TLLSignature sig) const;
+  void GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const;
 
   void MergeLinkLibraries(cmMakefile& mf, const std::string& selfname,
                           const LinkLibraryVectorType& libs);
@@ -195,7 +190,7 @@ public:
    * name as would be specified to the ADD_EXECUTABLE or UTILITY_SOURCE
    * commands. It is not a full path nor does it have an extension.
    */
-  void AddUtility(const std::string& u, cmMakefile* makefile = 0);
+  void AddUtility(const std::string& u, cmMakefile* makefile = CM_NULLPTR);
   ///! Get the utilities used by this target
   std::set<std::string> const& GetUtilities() const { return this->Utilities; }
   cmListFileBacktrace const* GetUtilityBacktrace(const std::string& u) const;
@@ -331,7 +326,7 @@ private:
 };
 
 #ifdef CMAKE_BUILD_WITH_CMAKE
-#ifdef CMake_HAVE_CXX11_UNORDERED_MAP
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
 typedef std::unordered_map<std::string, cmTarget> cmTargets;
 #else
 typedef cmsys::hash_map<std::string, cmTarget> cmTargets;
diff --git a/Source/cmTargetCompileDefinitionsCommand.cxx b/Source/cmTargetCompileDefinitionsCommand.cxx
index 0711a5c..9f08ba7 100644
--- a/Source/cmTargetCompileDefinitionsCommand.cxx
+++ b/Source/cmTargetCompileDefinitionsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileDefinitionsCommand.h"
 
 #include "cmAlgorithms.h"
diff --git a/Source/cmTargetCompileDefinitionsCommand.h b/Source/cmTargetCompileDefinitionsCommand.h
index 29d86c5..b49f616 100644
--- a/Source/cmTargetCompileDefinitionsCommand.h
+++ b/Source/cmTargetCompileDefinitionsCommand.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetCompileDefinitionsCommand_h
 #define cmTargetCompileDefinitionsCommand_h
 
@@ -21,30 +11,36 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTargetCompileDefinitionsCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmTargetCompileDefinitionsCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "target_compile_definitions"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "target_compile_definitions";
+  }
 
   cmTypeMacro(cmTargetCompileDefinitionsCommand, cmTargetPropCommandBase);
 
 private:
-  virtual void HandleImportedTarget(const std::string& tgt);
-  virtual void HandleMissingTarget(const std::string& name);
+  void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
+  void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
 
-  virtual bool HandleDirectContent(cmTarget* tgt,
-                                   const std::vector<std::string>& content,
-                                   bool prepend, bool system);
-  virtual std::string Join(const std::vector<std::string>& content);
+  bool HandleDirectContent(cmTarget* tgt,
+                           const std::vector<std::string>& content,
+                           bool prepend, bool system) CM_OVERRIDE;
+  std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmTargetCompileFeaturesCommand.cxx b/Source/cmTargetCompileFeaturesCommand.cxx
index 3ac791a..7636347 100644
--- a/Source/cmTargetCompileFeaturesCommand.cxx
+++ b/Source/cmTargetCompileFeaturesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileFeaturesCommand.h"
 
 #include "cmAlgorithms.h"
diff --git a/Source/cmTargetCompileFeaturesCommand.h b/Source/cmTargetCompileFeaturesCommand.h
index 3d883e9..8273e02 100644
--- a/Source/cmTargetCompileFeaturesCommand.h
+++ b/Source/cmTargetCompileFeaturesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetCompileFeaturesCommand_h
 #define cmTargetCompileFeaturesCommand_h
 
@@ -16,23 +7,23 @@
 
 class cmTargetCompileFeaturesCommand : public cmTargetPropCommandBase
 {
-  virtual cmCommand* Clone() { return new cmTargetCompileFeaturesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileFeaturesCommand; }
 
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
-  virtual std::string GetName() const { return "target_compile_features"; }
+  std::string GetName() const CM_OVERRIDE { return "target_compile_features"; }
 
   cmTypeMacro(cmTargetCompileFeaturesCommand, cmTargetPropCommandBase);
 
 private:
-  virtual void HandleImportedTarget(const std::string& tgt);
-  virtual void HandleMissingTarget(const std::string& name);
+  void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
+  void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
 
-  virtual bool HandleDirectContent(cmTarget* tgt,
-                                   const std::vector<std::string>& content,
-                                   bool prepend, bool system);
-  virtual std::string Join(const std::vector<std::string>& content);
+  bool HandleDirectContent(cmTarget* tgt,
+                           const std::vector<std::string>& content,
+                           bool prepend, bool system) CM_OVERRIDE;
+  std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmTargetCompileOptionsCommand.cxx b/Source/cmTargetCompileOptionsCommand.cxx
index 065f618..eb66dd3 100644
--- a/Source/cmTargetCompileOptionsCommand.cxx
+++ b/Source/cmTargetCompileOptionsCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileOptionsCommand.h"
 
 #include "cmAlgorithms.h"
diff --git a/Source/cmTargetCompileOptionsCommand.h b/Source/cmTargetCompileOptionsCommand.h
index 231448b..f5b4c70 100644
--- a/Source/cmTargetCompileOptionsCommand.h
+++ b/Source/cmTargetCompileOptionsCommand.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetCompileOptionsCommand_h
 #define cmTargetCompileOptionsCommand_h
 
@@ -21,30 +11,30 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTargetCompileOptionsCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileOptionsCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "target_compile_options"; }
+  std::string GetName() const CM_OVERRIDE { return "target_compile_options"; }
 
   cmTypeMacro(cmTargetCompileOptionsCommand, cmTargetPropCommandBase);
 
 private:
-  virtual void HandleImportedTarget(const std::string& tgt);
-  virtual void HandleMissingTarget(const std::string& name);
+  void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
+  void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
 
-  virtual bool HandleDirectContent(cmTarget* tgt,
-                                   const std::vector<std::string>& content,
-                                   bool prepend, bool system);
-  virtual std::string Join(const std::vector<std::string>& content);
+  bool HandleDirectContent(cmTarget* tgt,
+                           const std::vector<std::string>& content,
+                           bool prepend, bool system) CM_OVERRIDE;
+  std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmTargetDepend.h b/Source/cmTargetDepend.h
index 954d8f6..acea6ea 100644
--- a/Source/cmTargetDepend.h
+++ b/Source/cmTargetDepend.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetDepend_h
 #define cmTargetDepend_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmGeneratorTarget;
diff --git a/Source/cmTargetExport.h b/Source/cmTargetExport.h
index 2781337..634148b 100644
--- a/Source/cmTargetExport.h
+++ b/Source/cmTargetExport.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetExport_h
 #define cmTargetExport_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmGeneratorTarget;
diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx
index 4486b0e..37b9598 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.cxx
+++ b/Source/cmTargetIncludeDirectoriesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetIncludeDirectoriesCommand.h"
 
 #include "cmGeneratorExpression.h"
diff --git a/Source/cmTargetIncludeDirectoriesCommand.h b/Source/cmTargetIncludeDirectoriesCommand.h
index 4c907bd..671627a 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.h
+++ b/Source/cmTargetIncludeDirectoriesCommand.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetIncludeDirectoriesCommand_h
 #define cmTargetIncludeDirectoriesCommand_h
 
@@ -21,34 +11,40 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTargetIncludeDirectoriesCommand; }
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmTargetIncludeDirectoriesCommand;
+  }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "target_include_directories"; }
+  std::string GetName() const CM_OVERRIDE
+  {
+    return "target_include_directories";
+  }
 
   cmTypeMacro(cmTargetIncludeDirectoriesCommand, cmTargetPropCommandBase);
 
 private:
-  virtual void HandleImportedTarget(const std::string& tgt);
-  virtual void HandleMissingTarget(const std::string& name);
+  void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
+  void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
 
-  virtual bool HandleDirectContent(cmTarget* tgt,
-                                   const std::vector<std::string>& content,
-                                   bool prepend, bool system);
-  virtual void HandleInterfaceContent(cmTarget* tgt,
-                                      const std::vector<std::string>& content,
-                                      bool prepend, bool system);
+  bool HandleDirectContent(cmTarget* tgt,
+                           const std::vector<std::string>& content,
+                           bool prepend, bool system) CM_OVERRIDE;
+  void HandleInterfaceContent(cmTarget* tgt,
+                              const std::vector<std::string>& content,
+                              bool prepend, bool system) CM_OVERRIDE;
 
-  virtual std::string Join(const std::vector<std::string>& content);
+  std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx
index 774577a..e714309 100644
--- a/Source/cmTargetLinkLibrariesCommand.cxx
+++ b/Source/cmTargetLinkLibrariesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetLinkLibrariesCommand.h"
 
 #include "cmGeneratorExpression.h"
@@ -22,7 +13,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
   // must have one argument
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -91,7 +82,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass(
 
   if (this->Target->GetType() == cmState::UTILITY) {
     std::ostringstream e;
-    const char* modal = 0;
+    const char* modal = CM_NULLPTR;
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
     switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0039)) {
       case cmPolicies::WARN:
@@ -307,7 +298,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
   if (!this->Target->PushTLLCommandTrace(
         sig, this->Makefile->GetExecutionContext())) {
     std::ostringstream e;
-    const char* modal = 0;
+    const char* modal = CM_NULLPTR;
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
     switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0023)) {
       case cmPolicies::WARN:
@@ -353,10 +344,9 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
         "INTERFACE_LINK_LIBRARIES",
         this->Target->GetDebugGeneratorExpressions(lib, llt).c_str());
       return true;
-    } else if (this->CurrentProcessingState !=
-                 ProcessingKeywordPublicInterface &&
-               this->CurrentProcessingState !=
-                 ProcessingPlainPublicInterface) {
+    }
+    if (this->CurrentProcessingState != ProcessingKeywordPublicInterface &&
+        this->CurrentProcessingState != ProcessingPlainPublicInterface) {
       if (this->Target->GetType() == cmState::STATIC_LIBRARY) {
         std::string configLib =
           this->Target->GetDebugGeneratorExpressions(lib, llt);
diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h
index 016993d..85888f9 100644
--- a/Source/cmTargetLinkLibrariesCommand.h
+++ b/Source/cmTargetLinkLibrariesCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetLinkLibrariesCommand_h
 #define cmTargetLinkLibrariesCommand_h
 
@@ -27,19 +18,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTargetLinkLibrariesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTargetLinkLibrariesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "target_link_libraries"; }
+  std::string GetName() const CM_OVERRIDE { return "target_link_libraries"; }
 
   cmTypeMacro(cmTargetLinkLibrariesCommand, cmCommand);
 
diff --git a/Source/cmTargetLinkLibraryType.h b/Source/cmTargetLinkLibraryType.h
new file mode 100644
index 0000000..192c6da
--- /dev/null
+++ b/Source/cmTargetLinkLibraryType.h
@@ -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.  */
+#ifndef cmTargetLinkLibraryType_h
+#define cmTargetLinkLibraryType_h
+
+enum cmTargetLinkLibraryType
+{
+  GENERAL_LibraryType,
+  DEBUG_LibraryType,
+  OPTIMIZED_LibraryType
+};
+
+#endif
diff --git a/Source/cmTargetPropCommandBase.cxx b/Source/cmTargetPropCommandBase.cxx
index 487074f..a00360b 100644
--- a/Source/cmTargetPropCommandBase.cxx
+++ b/Source/cmTargetPropCommandBase.cxx
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetPropCommandBase.h"
 
 #include "cmGlobalGenerator.h"
diff --git a/Source/cmTargetPropCommandBase.h b/Source/cmTargetPropCommandBase.h
index 88591dc..de0a7d3 100644
--- a/Source/cmTargetPropCommandBase.h
+++ b/Source/cmTargetPropCommandBase.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2013 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetPropCommandBase_h
 #define cmTargetPropCommandBase_h
 
diff --git a/Source/cmTargetSourcesCommand.cxx b/Source/cmTargetSourcesCommand.cxx
index 64372dc..2170247 100644
--- a/Source/cmTargetSourcesCommand.cxx
+++ b/Source/cmTargetSourcesCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetSourcesCommand.h"
 
 #include "cmGeneratorExpression.h"
diff --git a/Source/cmTargetSourcesCommand.h b/Source/cmTargetSourcesCommand.h
index 304e176..8f88b25 100644
--- a/Source/cmTargetSourcesCommand.h
+++ b/Source/cmTargetSourcesCommand.h
@@ -1,15 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Stephen Kelly <steveire at gmail.com>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTargetSourcesCommand_h
 #define cmTargetSourcesCommand_h
 
@@ -21,31 +11,31 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTargetSourcesCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTargetSourcesCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "target_sources"; }
+  std::string GetName() const CM_OVERRIDE { return "target_sources"; }
 
   cmTypeMacro(cmTargetSourcesCommand, cmTargetPropCommandBase);
 
 private:
-  virtual void HandleImportedTarget(const std::string& tgt);
-  virtual void HandleMissingTarget(const std::string& name);
+  void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
+  void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
 
-  virtual bool HandleDirectContent(cmTarget* tgt,
-                                   const std::vector<std::string>& content,
-                                   bool prepend, bool system);
+  bool HandleDirectContent(cmTarget* tgt,
+                           const std::vector<std::string>& content,
+                           bool prepend, bool system) CM_OVERRIDE;
 
-  virtual std::string Join(const std::vector<std::string>& content);
+  std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
 };
 
 #endif
diff --git a/Source/cmTest.cxx b/Source/cmTest.cxx
index 0658e95..4d0cbaa 100644
--- a/Source/cmTest.cxx
+++ b/Source/cmTest.cxx
@@ -1,20 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTest.h"
 
-#include "cmSystemTools.h"
-
 #include "cmMakefile.h"
-#include "cmake.h"
+#include "cmProperty.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 
 cmTest::cmTest(cmMakefile* mf)
   : Backtrace(mf->GetBacktrace())
diff --git a/Source/cmTest.h b/Source/cmTest.h
index db68008..274a924 100644
--- a/Source/cmTest.h
+++ b/Source/cmTest.h
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTest_h
 #define cmTest_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmCustomCommand.h"
 #include "cmListFileCache.h"
 #include "cmPropertyMap.h"
+
+#include <string>
+#include <vector>
+
 class cmMakefile;
 
 /** \class cmTest
diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx
index e599825..3ea59cb 100644
--- a/Source/cmTestGenerator.cxx
+++ b/Source/cmTestGenerator.cxx
@@ -1,21 +1,21 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTestGenerator.h"
 
 #include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
 #include "cmLocalGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmProperty.h"
+#include "cmPropertyMap.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmTest.h"
+#include "cm_auto_ptr.hxx"
+
+#include <map>
+#include <ostream>
+#include <utility>
 
 cmTestGenerator::cmTestGenerator(
   cmTest* test, std::vector<std::string> const& configurations)
@@ -24,7 +24,7 @@ cmTestGenerator::cmTestGenerator(
 {
   this->ActionsPerConfig = !test->GetOldStyle();
   this->TestGenerated = false;
-  this->LG = 0;
+  this->LG = CM_NULLPTR;
 }
 
 cmTestGenerator::~cmTestGenerator()
@@ -83,7 +83,7 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os,
 
     // Prepend with the emulator when cross compiling if required.
     const char* emulator = target->GetProperty("CROSSCOMPILING_EMULATOR");
-    if (emulator != 0) {
+    if (emulator != CM_NULLPTR) {
       std::vector<std::string> emulatorWithArgs;
       cmSystemTools::ExpandListArgument(emulator, emulatorWithArgs);
       std::string emulatorExe(emulatorWithArgs[0]);
diff --git a/Source/cmTestGenerator.h b/Source/cmTestGenerator.h
index f946a1c..b350806 100644
--- a/Source/cmTestGenerator.h
+++ b/Source/cmTestGenerator.h
@@ -1,21 +1,18 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTestGenerator_h
 #define cmTestGenerator_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include "cmScriptGenerator.h"
 
-class cmTest;
+#include <iosfwd>
+#include <string>
+#include <vector>
+
 class cmLocalGenerator;
+class cmTest;
 
 /** \class cmTestGenerator
  * \brief Support class for generating install scripts.
@@ -27,18 +24,20 @@ public:
   cmTestGenerator(cmTest* test,
                   std::vector<std::string> const& configurations =
                     std::vector<std::string>());
-  virtual ~cmTestGenerator();
+  ~cmTestGenerator() CM_OVERRIDE;
 
   void Compute(cmLocalGenerator* lg);
 
 protected:
-  virtual void GenerateScriptConfigs(std::ostream& os, Indent const& indent);
-  virtual void GenerateScriptActions(std::ostream& os, Indent const& indent);
-  virtual void GenerateScriptForConfig(std::ostream& os,
-                                       const std::string& config,
-                                       Indent const& indent);
-  virtual void GenerateScriptNoConfig(std::ostream& os, Indent const& indent);
-  virtual bool NeedsScriptNoConfig() const;
+  void GenerateScriptConfigs(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptActions(std::ostream& os,
+                             Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptForConfig(std::ostream& os, const std::string& config,
+                               Indent const& indent) CM_OVERRIDE;
+  void GenerateScriptNoConfig(std::ostream& os,
+                              Indent const& indent) CM_OVERRIDE;
+  bool NeedsScriptNoConfig() const CM_OVERRIDE;
   void GenerateOldStyle(std::ostream& os, Indent const& indent);
 
   cmLocalGenerator* LG;
diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx
index c624d0f..6a8c9c6 100644
--- a/Source/cmTimestamp.cxx
+++ b/Source/cmTimestamp.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTimestamp.h"
 
 #include <cstdlib>
@@ -22,7 +13,7 @@
 std::string cmTimestamp::CurrentTime(const std::string& formatString,
                                      bool utcFlag)
 {
-  time_t currentTimeT = time(0);
+  time_t currentTimeT = time(CM_NULLPTR);
   if (currentTimeT == time_t(-1)) {
     return std::string();
   }
@@ -56,14 +47,14 @@ std::string cmTimestamp::CreateTimestampFromTimeT(time_t timeT,
   struct tm timeStruct;
   memset(&timeStruct, 0, sizeof(timeStruct));
 
-  struct tm* ptr = (struct tm*)0;
+  struct tm* ptr = (struct tm*)CM_NULLPTR;
   if (utcFlag) {
     ptr = gmtime(&timeT);
   } else {
     ptr = localtime(&timeT);
   }
 
-  if (ptr == 0) {
+  if (ptr == CM_NULLPTR) {
     return std::string();
   }
 
@@ -93,10 +84,9 @@ time_t cmTimestamp::CreateUtcTimeTFromTm(struct tm& tm) const
 #else
   // From Linux timegm() manpage.
 
-  std::string tz_old = "TZ=";
-  if (const char* tz = cmSystemTools::GetEnv("TZ")) {
-    tz_old += tz;
-  }
+  std::string tz_old = "";
+  cmSystemTools::GetEnv("TZ", tz_old);
+  tz_old = "TZ=" + tz_old;
 
   // The standard says that "TZ=" or "TZ=[UNRECOGNIZED_TZ]" means UTC.
   // It seems that "TZ=" does NOT work, at least under Windows
@@ -124,6 +114,8 @@ std::string cmTimestamp::AddTimestampComponent(char flag,
   formatString += flag;
 
   switch (flag) {
+    case 'a':
+    case 'b':
     case 'd':
     case 'H':
     case 'I':
@@ -152,7 +144,7 @@ std::string cmTimestamp::AddTimestampComponent(char flag,
         return std::string();
       }
 
-      std::stringstream ss;
+      std::ostringstream ss;
       ss << static_cast<long int>(difftime(timeT, unixEpoch));
       return ss.str();
     }
diff --git a/Source/cmTimestamp.h b/Source/cmTimestamp.h
index 77e1f7a..44e397b 100644
--- a/Source/cmTimestamp.h
+++ b/Source/cmTimestamp.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTimestamp_h
 #define cmTimestamp_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include <string>
diff --git a/Source/cmTryCompileCommand.cxx b/Source/cmTryCompileCommand.cxx
index 7930d23..933818e 100644
--- a/Source/cmTryCompileCommand.cxx
+++ b/Source/cmTryCompileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTryCompileCommand.h"
 
 // cmTryCompileCommand
diff --git a/Source/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h
index e50d54c..45d92df 100644
--- a/Source/cmTryCompileCommand.h
+++ b/Source/cmTryCompileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTryCompileCommand_h
 #define cmTryCompileCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTryCompileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTryCompileCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "try_compile"; }
+  std::string GetName() const CM_OVERRIDE { return "try_compile"; }
 
   cmTypeMacro(cmTryCompileCommand, cmCoreTryCompile);
 };
diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx
index 19837a7..5c9e41a 100644
--- a/Source/cmTryRunCommand.cxx
+++ b/Source/cmTryRunCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTryRunCommand.h"
 
 #include "cmTryCompileCommand.h"
@@ -124,8 +115,9 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
       std::string runOutputContents;
       if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING") &&
           !this->Makefile->IsDefinitionSet("CMAKE_CROSSCOMPILING_EMULATOR")) {
-        this->DoNotRunExecutable(runArgs, argv[3],
-                                 captureRunOutput ? &runOutputContents : 0);
+        this->DoNotRunExecutable(runArgs, argv[3], captureRunOutput
+                                   ? &runOutputContents
+                                   : CM_NULLPTR);
       } else {
         this->RunExecutable(runArgs, &runOutputContents);
       }
@@ -186,9 +178,9 @@ void cmTryRunCommand::RunExecutable(const std::string& runArgs,
     finalCommand += runArgs;
   }
   int timeout = 0;
-  bool worked =
-    cmSystemTools::RunSingleCommand(finalCommand.c_str(), out, out, &retVal, 0,
-                                    cmSystemTools::OUTPUT_NONE, timeout);
+  bool worked = cmSystemTools::RunSingleCommand(
+    finalCommand.c_str(), out, out, &retVal, CM_NULLPTR,
+    cmSystemTools::OUTPUT_NONE, timeout);
   // set the run var
   char retChar[1000];
   if (worked) {
@@ -230,7 +222,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
     this->RunResultVariable + "__TRYRUN_OUTPUT";
   bool error = false;
 
-  if (this->Makefile->GetDefinition(this->RunResultVariable) == 0) {
+  if (this->Makefile->GetDefinition(this->RunResultVariable) == CM_NULLPTR) {
     // if the variables doesn't exist, create it with a helpful error text
     // and mark it as advanced
     std::string comment;
@@ -252,8 +244,8 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
   }
 
   // is the output from the executable used ?
-  if (out != 0) {
-    if (this->Makefile->GetDefinition(internalRunOutputName) == 0) {
+  if (out != CM_NULLPTR) {
+    if (this->Makefile->GetDefinition(internalRunOutputName) == CM_NULLPTR) {
       // if the variables doesn't exist, create it with a helpful error text
       // and mark it as advanced
       std::string comment;
@@ -301,7 +293,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
       comment += " to\n"
                  "   the exit code (in many cases 0 for success), otherwise "
                  "enter \"FAILED_TO_RUN\".\n";
-      if (out != 0) {
+      if (out != CM_NULLPTR) {
         comment += internalRunOutputName;
         comment +=
           "\n   contains the text the executable "
@@ -332,7 +324,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
            << this->Makefile->GetDefinition(this->RunResultVariable)
            << "\"\n     CACHE STRING \"Result from TRY_RUN\" FORCE)\n\n";
 
-      if (out != 0) {
+      if (out != CM_NULLPTR) {
         file << "set( " << internalRunOutputName << " \n     \""
              << this->Makefile->GetDefinition(internalRunOutputName)
              << "\"\n     CACHE STRING \"Output from TRY_RUN\" FORCE)\n\n";
@@ -345,7 +337,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
                                "please set the following cache variables "
                                "appropriately:\n";
     errorMessage += "   " + this->RunResultVariable + " (advanced)\n";
-    if (out != 0) {
+    if (out != CM_NULLPTR) {
       errorMessage += "   " + internalRunOutputName + " (advanced)\n";
     }
     errorMessage += detailsString;
@@ -353,7 +345,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
     return;
   }
 
-  if (out != 0) {
+  if (out != CM_NULLPTR) {
     (*out) = this->Makefile->GetDefinition(internalRunOutputName);
   }
 }
diff --git a/Source/cmTryRunCommand.h b/Source/cmTryRunCommand.h
index 26c0777..b569b0b 100644
--- a/Source/cmTryRunCommand.h
+++ b/Source/cmTryRunCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmTryRunCommand_h
 #define cmTryRunCommand_h
 
@@ -25,19 +16,19 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmTryRunCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmTryRunCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "try_run"; }
+  std::string GetName() const CM_OVERRIDE { return "try_run"; }
 
   cmTypeMacro(cmTryRunCommand, cmCoreTryCompile);
 
diff --git a/Source/cmTypeMacro.h b/Source/cmTypeMacro.h
new file mode 100644
index 0000000..b302ff1
--- /dev/null
+++ b/Source/cmTypeMacro.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 cmTypeMacro_h
+#define cmTypeMacro_h
+
+// All subclasses of cmCommand or cmCTestGenericHandler should
+// invoke this macro.
+#define cmTypeMacro(thisClass, superclass)                                    \
+  const char* GetNameOfClass() CM_OVERRIDE { return #thisClass; }             \
+  typedef superclass Superclass;                                              \
+  static bool IsTypeOf(const char* type)                                      \
+  {                                                                           \
+    if (!strcmp(#thisClass, type)) {                                          \
+      return true;                                                            \
+    }                                                                         \
+    return Superclass::IsTypeOf(type);                                        \
+  }                                                                           \
+  bool IsA(const char* type) CM_OVERRIDE                                      \
+  {                                                                           \
+    return thisClass::IsTypeOf(type);                                         \
+  }                                                                           \
+  static thisClass* SafeDownCast(cmObject* c)                                 \
+  {                                                                           \
+    if (c && c->IsA(#thisClass)) {                                            \
+      return static_cast<thisClass*>(c);                                      \
+    }                                                                         \
+    return 0;                                                                 \
+  }                                                                           \
+  class cmTypeMacro_UseTrailingSemicolon
+
+#endif
diff --git a/Source/cmUnsetCommand.cxx b/Source/cmUnsetCommand.cxx
index c04c44a..746c435 100644
--- a/Source/cmUnsetCommand.cxx
+++ b/Source/cmUnsetCommand.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUnsetCommand.h"
 
 // cmUnsetCommand
 bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args,
                                  cmExecutionStatus&)
 {
-  if (args.size() < 1 || args.size() > 2) {
+  if (args.empty() || args.size() > 2) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
@@ -36,23 +27,21 @@ bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args,
     return true;
   }
   // unset(VAR)
-  else if (args.size() == 1) {
+  if (args.size() == 1) {
     this->Makefile->RemoveDefinition(variable);
     return true;
   }
   // unset(VAR CACHE)
-  else if ((args.size() == 2) && (args[1] == "CACHE")) {
+  if ((args.size() == 2) && (args[1] == "CACHE")) {
     this->Makefile->RemoveCacheDefinition(variable);
     return true;
   }
   // unset(VAR PARENT_SCOPE)
-  else if ((args.size() == 2) && (args[1] == "PARENT_SCOPE")) {
-    this->Makefile->RaiseScope(variable, 0);
+  if ((args.size() == 2) && (args[1] == "PARENT_SCOPE")) {
+    this->Makefile->RaiseScope(variable, CM_NULLPTR);
     return true;
   }
   // ERROR: second argument isn't CACHE or PARENT_SCOPE
-  else {
-    this->SetError("called with an invalid second argument");
-    return false;
-  }
+  this->SetError("called with an invalid second argument");
+  return false;
 }
diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h
index faa8f9b..b3f045a 100644
--- a/Source/cmUnsetCommand.h
+++ b/Source/cmUnsetCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmUnsetCommand_h
 #define cmUnsetCommand_h
 
@@ -25,24 +16,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmUnsetCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmUnsetCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "unset"; }
+  std::string GetName() const CM_OVERRIDE { return "unset"; }
 
   cmTypeMacro(cmUnsetCommand, cmCommand);
 };
diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx
index 1eb493a..e2b6b1a 100644
--- a/Source/cmUseMangledMesaCommand.cxx
+++ b/Source/cmUseMangledMesaCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUseMangledMesaCommand.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmUseMangledMesaCommand.h b/Source/cmUseMangledMesaCommand.h
index 5a97a61..a5fa146 100644
--- a/Source/cmUseMangledMesaCommand.h
+++ b/Source/cmUseMangledMesaCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmUseMangledMesaCommand_h
 #define cmUseMangledMesaCommand_h
 
@@ -18,11 +9,11 @@ class cmUseMangledMesaCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmUseMangledMesaCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmUseMangledMesaCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "use_mangled_mesa"; }
-  virtual bool IsScriptable() const { return true; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmUseMangledMesaCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "use_mangled_mesa"; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 protected:
   void CopyAndFullPathMesaHeader(const char* source, const char* outdir);
 };
diff --git a/Source/cmUtilitySourceCommand.cxx b/Source/cmUtilitySourceCommand.cxx
index f7d766e..08ea21e 100644
--- a/Source/cmUtilitySourceCommand.cxx
+++ b/Source/cmUtilitySourceCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUtilitySourceCommand.h"
 
 // cmUtilitySourceCommand
@@ -38,7 +29,7 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
 
   bool haveCacheValue = false;
   if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING")) {
-    haveCacheValue = (cacheValue != 0);
+    haveCacheValue = (cacheValue != CM_NULLPTR);
     if (!haveCacheValue) {
       std::string msg = "UTILITY_SOURCE is used in cross compiling mode for ";
       msg += cacheEntry;
@@ -50,7 +41,7 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
   } else {
     cmState* state = this->Makefile->GetState();
     haveCacheValue =
-      (cacheValue && (strstr(cacheValue, "(IntDir)") == 0 ||
+      (cacheValue && (strstr(cacheValue, "(IntDir)") == CM_NULLPTR ||
                       (intDir && strcmp(intDir, "$(IntDir)") == 0)) &&
        (state->GetCacheMajorVersion() != 0 &&
         state->GetCacheMinorVersion() != 0));
diff --git a/Source/cmUtilitySourceCommand.h b/Source/cmUtilitySourceCommand.h
index a709de1..6ee5f3e 100644
--- a/Source/cmUtilitySourceCommand.h
+++ b/Source/cmUtilitySourceCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmUtilitySourceCommand_h
 #define cmUtilitySourceCommand_h
 
@@ -18,10 +9,10 @@ class cmUtilitySourceCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmUtilitySourceCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmUtilitySourceCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "utility_source"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmUtilitySourceCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "utility_source"; }
 };
 
 #endif
diff --git a/Source/cmUtils.hxx b/Source/cmUtils.hxx
new file mode 100644
index 0000000..3f65872
--- /dev/null
+++ b/Source/cmUtils.hxx
@@ -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 cmUtils_hxx
+#define cmUtils_hxx
+
+#include <cmsys/SystemTools.hxx>
+
+// Use the make system's VERBOSE environment variable to enable
+// verbose output. This can be skipped by also setting CMAKE_NO_VERBOSE
+// (which is set by the Eclipse and KDevelop generators).
+inline bool isCMakeVerbose()
+{
+  return (cmSystemTools::HasEnv("VERBOSE") &&
+          !cmSystemTools::HasEnv("CMAKE_NO_VERBOSE"));
+}
+
+#endif
diff --git a/Source/cmUuid.cxx b/Source/cmUuid.cxx
index 6d09bdf..904bcbb 100644
--- a/Source/cmUuid.cxx
+++ b/Source/cmUuid.cxx
@@ -1,20 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUuid.h"
 
-#include <string.h>
-
 #include "cm_sha2.h"
+
 #include <cmsys/MD5.h>
+#include <string.h>
 
 cmUuid::cmUuid()
 {
@@ -180,13 +171,14 @@ bool cmUuid::IntFromHexDigit(char input, char& output) const
   if (input >= '0' && input <= '9') {
     output = char(input - '0');
     return true;
-  } else if (input >= 'a' && input <= 'f') {
+  }
+  if (input >= 'a' && input <= 'f') {
     output = char(input - 'a' + 0xA);
     return true;
-  } else if (input >= 'A' && input <= 'F') {
+  }
+  if (input >= 'A' && input <= 'F') {
     output = char(input - 'A' + 0xA);
     return true;
-  } else {
-    return false;
   }
+  return false;
 }
diff --git a/Source/cmUuid.h b/Source/cmUuid.h
index 2bd7ec5..1bc2229 100644
--- a/Source/cmUuid.h
+++ b/Source/cmUuid.h
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmUuid_h
 #define cmUuid_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 /** \class cmUuid
  * \brief Utility class to generate UUIDs as defined by RFC4122
diff --git a/Source/cmVS140CLFlagTable.h b/Source/cmVS140CLFlagTable.h
new file mode 100644
index 0000000..317cc18
--- /dev/null
+++ b/Source/cmVS140CLFlagTable.h
@@ -0,0 +1,237 @@
+static cmVS7FlagTable cmVS140CLFlagTable[] = {
+
+  // Enum Properties
+  { "DebugInformationFormat", "", "None", "None", 0 },
+  { "DebugInformationFormat", "Z7", "C7 compatible", "OldStyle", 0 },
+  { "DebugInformationFormat", "Zi", "Program Database", "ProgramDatabase", 0 },
+  { "DebugInformationFormat", "ZI", "Program Database for Edit And Continue",
+    "EditAndContinue", 0 },
+
+  { "WarningLevel", "W0", "Turn Off All Warnings", "TurnOffAllWarnings", 0 },
+  { "WarningLevel", "W1", "Level1", "Level1", 0 },
+  { "WarningLevel", "W2", "Level2", "Level2", 0 },
+  { "WarningLevel", "W3", "Level3", "Level3", 0 },
+  { "WarningLevel", "W4", "Level4", "Level4", 0 },
+  { "WarningLevel", "Wall", "EnableAllWarnings", "EnableAllWarnings", 0 },
+
+  { "Optimization", "", "Custom", "Custom", 0 },
+  { "Optimization", "Od", "Disabled", "Disabled", 0 },
+  { "Optimization", "O1", "Minimize Size", "MinSpace", 0 },
+  { "Optimization", "O2", "Maximize Speed", "MaxSpeed", 0 },
+  { "Optimization", "Ox", "Full Optimization", "Full", 0 },
+
+  { "InlineFunctionExpansion", "", "Default", "Default", 0 },
+  { "InlineFunctionExpansion", "Ob0", "Disabled", "Disabled", 0 },
+  { "InlineFunctionExpansion", "Ob1", "Only __inline", "OnlyExplicitInline",
+    0 },
+  { "InlineFunctionExpansion", "Ob2", "Any Suitable", "AnySuitable", 0 },
+
+  { "FavorSizeOrSpeed", "Os", "Favor small code", "Size", 0 },
+  { "FavorSizeOrSpeed", "Ot", "Favor fast code", "Speed", 0 },
+  { "FavorSizeOrSpeed", "", "Neither", "Neither", 0 },
+
+  { "ExceptionHandling", "EHa", "Yes with SEH Exceptions", "Async", 0 },
+  { "ExceptionHandling", "EHsc", "Yes", "Sync", 0 },
+  { "ExceptionHandling", "EHs", "Yes with Extern C functions", "SyncCThrow",
+    0 },
+  { "ExceptionHandling", "", "No", "false", 0 },
+
+  { "BasicRuntimeChecks", "RTCs", "Stack Frames", "StackFrameRuntimeCheck",
+    0 },
+  { "BasicRuntimeChecks", "RTCu", "Uninitialized variables",
+    "UninitializedLocalUsageCheck", 0 },
+  { "BasicRuntimeChecks", "RTC1", "Both (/RTC1, equiv. to /RTCsu)",
+    "EnableFastChecks", 0 },
+  { "BasicRuntimeChecks", "", "Default", "Default", 0 },
+
+  { "RuntimeLibrary", "MT", "Multi-threaded", "MultiThreaded", 0 },
+  { "RuntimeLibrary", "MTd", "Multi-threaded Debug", "MultiThreadedDebug", 0 },
+  { "RuntimeLibrary", "MD", "Multi-threaded DLL", "MultiThreadedDLL", 0 },
+  { "RuntimeLibrary", "MDd", "Multi-threaded Debug DLL",
+    "MultiThreadedDebugDLL", 0 },
+
+  { "StructMemberAlignment", "Zp1", "1 Byte", "1Byte", 0 },
+  { "StructMemberAlignment", "Zp2", "2 Bytes", "2Bytes", 0 },
+  { "StructMemberAlignment", "Zp4", "4 Byte", "4Bytes", 0 },
+  { "StructMemberAlignment", "Zp8", "8 Bytes", "8Bytes", 0 },
+  { "StructMemberAlignment", "Zp16", "16 Bytes", "16Bytes", 0 },
+  { "StructMemberAlignment", "", "Default", "Default", 0 },
+
+  { "BufferSecurityCheck", "GS-", "Disable Security Check", "false", 0 },
+  { "BufferSecurityCheck", "GS", "Enable Security Check", "true", 0 },
+
+  { "EnableEnhancedInstructionSet", "arch:SSE", "Streaming SIMD Extensions",
+    "StreamingSIMDExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "arch:SSE2", "Streaming SIMD Extensions 2",
+    "StreamingSIMDExtensions2", 0 },
+  { "EnableEnhancedInstructionSet", "arch:AVX", "Advanced Vector Extensions",
+    "AdvancedVectorExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "arch:AVX2",
+    "Advanced Vector Extensions 2", "AdvancedVectorExtensions2", 0 },
+  { "EnableEnhancedInstructionSet", "arch:IA32", "No Enhanced Instructions",
+    "NoExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "", "Not Set", "NotSet", 0 },
+
+  { "FloatingPointModel", "fp:precise", "Precise", "Precise", 0 },
+  { "FloatingPointModel", "fp:strict", "Strict", "Strict", 0 },
+  { "FloatingPointModel", "fp:fast", "Fast", "Fast", 0 },
+
+  { "PrecompiledHeader", "Yc", "Create", "Create",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "PrecompiledHeader", "Yu", "Use", "Use",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+
+  { "AssemblerOutput", "", "No Listing", "NoListing", 0 },
+  { "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
+  { "AssemblerOutput", "FAc", "Assembly With Machine Code",
+    "AssemblyAndMachineCode", 0 },
+  { "AssemblerOutput", "FAs", "Assembly With Source Code",
+    "AssemblyAndSourceCode", 0 },
+  { "AssemblerOutput", "FAcs", "Assembly, Machine Code and Source", "All", 0 },
+
+  { "CallingConvention", "Gd", "__cdecl", "Cdecl", 0 },
+  { "CallingConvention", "Gr", "__fastcall", "FastCall", 0 },
+  { "CallingConvention", "Gz", "__stdcall", "StdCall", 0 },
+  { "CallingConvention", "Gv", "__vectorcall", "VectorCall", 0 },
+
+  { "CompileAs", "", "Default", "Default", 0 },
+  { "CompileAs", "TC", "Compile as C Code", "CompileAsC", 0 },
+  { "CompileAs", "TP", "Compile as C++ Code", "CompileAsCpp", 0 },
+
+  { "ErrorReporting", "errorReport:none", "Do Not Send Report", "None", 0 },
+  { "ErrorReporting", "errorReport:prompt", "Prompt Immediately", "Prompt",
+    0 },
+  { "ErrorReporting", "errorReport:queue", "Queue For Next Login", "Queue",
+    0 },
+  { "ErrorReporting", "errorReport:send", "Send Automatically", "Send", 0 },
+
+  { "CompileAsManaged", "", "No Common Language RunTime Support", "false", 0 },
+  { "CompileAsManaged", "clr", "Common Language RunTime Support", "true", 0 },
+  { "CompileAsManaged", "clr:pure",
+    "Pure MSIL Common Language RunTime Support", "Pure", 0 },
+  { "CompileAsManaged", "clr:safe",
+    "Safe MSIL Common Language RunTime Support", "Safe", 0 },
+  { "CompileAsManaged", "clr:oldSyntax",
+    "Common Language RunTime Support, Old Syntax", "OldSyntax", 0 },
+
+  { "CppLanguageStandard", "", "Default", "Default", 0 },
+  { "CppLanguageStandard", "std=c++98", "C++03", "c++98", 0 },
+  { "CppLanguageStandard", "std=c++11", "C++11", "c++11", 0 },
+  { "CppLanguageStandard", "std=c++1y", "C++14", "c++1y", 0 },
+  { "CppLanguageStandard", "std=c++14", "C++14", "c++1y", 0 },
+  { "CppLanguageStandard", "std=gnu++98", "C++03 (GNU Dialect)", "gnu++98",
+    0 },
+  { "CppLanguageStandard", "std=gnu++11", "C++11 (GNU Dialect)", "gnu++11",
+    0 },
+  { "CppLanguageStandard", "std=gnu++1y", "C++14 (GNU Dialect)", "gnu++1y",
+    0 },
+  { "CppLanguageStandard", "std=gnu++14", "C++14 (GNU Dialect)", "gnu++1y",
+    0 },
+
+  // Bool Properties
+  { "CompileAsWinRT", "ZW", "", "true", 0 },
+  { "WinRTNoStdLib", "ZW:nostdlib", "", "true", 0 },
+  { "SuppressStartupBanner", "nologo", "", "true", 0 },
+  { "TreatWarningAsError", "WX-", "", "false", 0 },
+  { "TreatWarningAsError", "WX", "", "true", 0 },
+  { "SDLCheck", "sdl-", "", "false", 0 },
+  { "SDLCheck", "sdl", "", "true", 0 },
+  { "IntrinsicFunctions", "Oi", "", "true", 0 },
+  { "OmitFramePointers", "Oy-", "", "false", 0 },
+  { "OmitFramePointers", "Oy", "", "true", 0 },
+  { "EnableFiberSafeOptimizations", "GT", "", "true", 0 },
+  { "WholeProgramOptimization", "GL", "", "true", 0 },
+  { "UndefineAllPreprocessorDefinitions", "u", "", "true", 0 },
+  { "IgnoreStandardIncludePath", "X", "", "true", 0 },
+  { "PreprocessToFile", "P", "", "true", 0 },
+  { "PreprocessSuppressLineNumbers", "EP", "", "true", 0 },
+  { "PreprocessKeepComments", "C", "", "true", 0 },
+  { "StringPooling", "GF-", "", "false", 0 },
+  { "StringPooling", "GF", "", "true", 0 },
+  { "MinimalRebuild", "Gm-", "", "false", 0 },
+  { "MinimalRebuild", "Gm", "", "true", 0 },
+  { "SmallerTypeCheck", "RTCc", "", "true", 0 },
+  { "FunctionLevelLinking", "Gy-", "", "false", 0 },
+  { "FunctionLevelLinking", "Gy", "", "true", 0 },
+  { "EnableParallelCodeGeneration", "Qpar-", "", "false", 0 },
+  { "EnableParallelCodeGeneration", "Qpar", "", "true", 0 },
+  { "FloatingPointExceptions", "fp:except-", "", "false", 0 },
+  { "FloatingPointExceptions", "fp:except", "", "true", 0 },
+  { "CreateHotpatchableImage", "hotpatch", "", "true", 0 },
+  { "DisableLanguageExtensions", "Za", "", "true", 0 },
+  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t-", "", "false", 0 },
+  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0 },
+  { "ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0 },
+  { "ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0 },
+  { "RuntimeTypeInfo", "GR-", "", "false", 0 },
+  { "RuntimeTypeInfo", "GR", "", "true", 0 },
+  { "OpenMPSupport", "openmp-", "", "false", 0 },
+  { "OpenMPSupport", "openmp", "", "true", 0 },
+  { "ExpandAttributedSource", "Fx", "", "true", 0 },
+  { "UseUnicodeForAssemblerListing", "FAu", "", "true", 0 },
+  { "ShowIncludes", "showIncludes", "", "true", 0 },
+  { "EnablePREfast", "analyze-", "", "false", 0 },
+  { "EnablePREfast", "analyze", "", "true", 0 },
+  { "UseFullPaths", "FC", "", "true", 0 },
+  { "OmitDefaultLibName", "Zl", "", "true", 0 },
+
+  // Bool Properties With Argument
+  { "MultiProcessorCompilation", "MP", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "ProcessorNumber", "MP", "Multi-processor Compilation", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "GenerateXMLDocumentationFiles", "doc", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "XMLDocumentationFileName", "doc", "Generate XML Documentation Files", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "BrowseInformation", "FR", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "BrowseInformationFile", "FR", "Enable Browse Information", "",
+    cmVS7FlagTable::UserValueRequired },
+
+  // String List Properties
+  { "AdditionalIncludeDirectories", "I", "Additional Include Directories", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "AdditionalUsingDirectories", "AI", "Additional #using Directories", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "PreprocessorDefinitions", "D ", "Preprocessor Definitions", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "UndefinePreprocessorDefinitions", "U",
+    "Undefine Preprocessor Definitions", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "DisableSpecificWarnings", "wd", "Disable Specific Warnings", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "ForcedIncludeFiles", "FI", "Forced Include File", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "ForcedUsingFiles", "FU", "Forced #using File", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "PREfastLog", "analyze:log", "Code Analysis Log", "",
+    cmVS7FlagTable::UserFollowing },
+  { "PREfastAdditionalPlugins", "analyze:plugin",
+    "Additional Code Analysis Native plugins", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "TreatSpecificWarningsAsErrors", "we", "Treat Specific Warnings As Errors",
+    "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+
+  // String Properties
+  // Skip [TrackerLogDirectory] - no command line Switch.
+  { "PreprocessOutputPath", "Fi", "Preprocess Output Path", "",
+    cmVS7FlagTable::UserValue },
+  { "PrecompiledHeaderFile", "Yc", "Precompiled Header Name", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "PrecompiledHeaderFile", "Yu", "Precompiled Header Name", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "PrecompiledHeaderOutputFile", "Fp", "Precompiled Header Output File", "",
+    cmVS7FlagTable::UserValue },
+  { "AssemblerListingLocation", "Fa", "ASM List Location", "",
+    cmVS7FlagTable::UserValue },
+  { "ObjectFileName", "Fo", "Object File Name", "",
+    cmVS7FlagTable::UserValue },
+  { "ProgramDataBaseFileName", "Fd", "Program Database File Name", "",
+    cmVS7FlagTable::UserValue },
+  // Skip [XMLDocumentationFileName] - no command line Switch.
+  // Skip [BrowseInformationFile] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  { 0, 0, 0, 0, 0 }
+};
diff --git a/Source/cmVS141CLFlagTable.h b/Source/cmVS141CLFlagTable.h
new file mode 100644
index 0000000..895b3e8
--- /dev/null
+++ b/Source/cmVS141CLFlagTable.h
@@ -0,0 +1,249 @@
+static cmVS7FlagTable cmVS141CLFlagTable[] = {
+
+  // Enum Properties
+  { "DebugInformationFormat", "", "None", "None", 0 },
+  { "DebugInformationFormat", "Z7", "C7 compatible", "OldStyle", 0 },
+  { "DebugInformationFormat", "Zi", "Program Database", "ProgramDatabase", 0 },
+  { "DebugInformationFormat", "ZI", "Program Database for Edit And Continue",
+    "EditAndContinue", 0 },
+
+  { "WarningLevel", "W0", "Turn Off All Warnings", "TurnOffAllWarnings", 0 },
+  { "WarningLevel", "W1", "Level1", "Level1", 0 },
+  { "WarningLevel", "W2", "Level2", "Level2", 0 },
+  { "WarningLevel", "W3", "Level3", "Level3", 0 },
+  { "WarningLevel", "W4", "Level4", "Level4", 0 },
+  { "WarningLevel", "Wall", "EnableAllWarnings", "EnableAllWarnings", 0 },
+
+  { "Optimization", "", "Custom", "Custom", 0 },
+  { "Optimization", "Od", "Disabled", "Disabled", 0 },
+  { "Optimization", "O1", "Minimize Size", "MinSpace", 0 },
+  { "Optimization", "O2", "Maximize Speed", "MaxSpeed", 0 },
+  { "Optimization", "Ox", "Full Optimization", "Full", 0 },
+
+  { "InlineFunctionExpansion", "", "Default", "Default", 0 },
+  { "InlineFunctionExpansion", "Ob0", "Disabled", "Disabled", 0 },
+  { "InlineFunctionExpansion", "Ob1", "Only __inline", "OnlyExplicitInline",
+    0 },
+  { "InlineFunctionExpansion", "Ob2", "Any Suitable", "AnySuitable", 0 },
+
+  { "FavorSizeOrSpeed", "Os", "Favor small code", "Size", 0 },
+  { "FavorSizeOrSpeed", "Ot", "Favor fast code", "Speed", 0 },
+  { "FavorSizeOrSpeed", "", "Neither", "Neither", 0 },
+
+  { "ExceptionHandling", "EHa", "Yes with SEH Exceptions", "Async", 0 },
+  { "ExceptionHandling", "EHsc", "Yes", "Sync", 0 },
+  { "ExceptionHandling", "EHs", "Yes with Extern C functions", "SyncCThrow",
+    0 },
+  { "ExceptionHandling", "", "No", "false", 0 },
+
+  { "BasicRuntimeChecks", "RTCs", "Stack Frames", "StackFrameRuntimeCheck",
+    0 },
+  { "BasicRuntimeChecks", "RTCu", "Uninitialized variables",
+    "UninitializedLocalUsageCheck", 0 },
+  { "BasicRuntimeChecks", "RTC1", "Both (/RTC1, equiv. to /RTCsu)",
+    "EnableFastChecks", 0 },
+  { "BasicRuntimeChecks", "", "Default", "Default", 0 },
+
+  { "RuntimeLibrary", "MT", "Multi-threaded", "MultiThreaded", 0 },
+  { "RuntimeLibrary", "MTd", "Multi-threaded Debug", "MultiThreadedDebug", 0 },
+  { "RuntimeLibrary", "MD", "Multi-threaded DLL", "MultiThreadedDLL", 0 },
+  { "RuntimeLibrary", "MDd", "Multi-threaded Debug DLL",
+    "MultiThreadedDebugDLL", 0 },
+
+  { "StructMemberAlignment", "Zp1", "1 Byte", "1Byte", 0 },
+  { "StructMemberAlignment", "Zp2", "2 Bytes", "2Bytes", 0 },
+  { "StructMemberAlignment", "Zp4", "4 Byte", "4Bytes", 0 },
+  { "StructMemberAlignment", "Zp8", "8 Bytes", "8Bytes", 0 },
+  { "StructMemberAlignment", "Zp16", "16 Bytes", "16Bytes", 0 },
+  { "StructMemberAlignment", "", "Default", "Default", 0 },
+
+  { "BufferSecurityCheck", "GS-", "Disable Security Check", "false", 0 },
+  { "BufferSecurityCheck", "GS", "Enable Security Check", "true", 0 },
+
+  { "ControlFlowGuard", "guard:cf", "Yes", "Guard", 0 },
+  { "ControlFlowGuard", "", "No", "false", 0 },
+
+  { "EnableEnhancedInstructionSet", "arch:SSE", "Streaming SIMD Extensions",
+    "StreamingSIMDExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "arch:SSE2", "Streaming SIMD Extensions 2",
+    "StreamingSIMDExtensions2", 0 },
+  { "EnableEnhancedInstructionSet", "arch:AVX", "Advanced Vector Extensions",
+    "AdvancedVectorExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "arch:AVX2",
+    "Advanced Vector Extensions 2", "AdvancedVectorExtensions2", 0 },
+  { "EnableEnhancedInstructionSet", "arch:IA32", "No Enhanced Instructions",
+    "NoExtensions", 0 },
+  { "EnableEnhancedInstructionSet", "", "Not Set", "NotSet", 0 },
+
+  { "FloatingPointModel", "fp:precise", "Precise", "Precise", 0 },
+  { "FloatingPointModel", "fp:strict", "Strict", "Strict", 0 },
+  { "FloatingPointModel", "fp:fast", "Fast", "Fast", 0 },
+
+  { "LanguageStandard", "std:c++14", "ISO C++14 Standard", "stdcpp14", 0 },
+  { "LanguageStandard", "std:c++latest", "ISO C++ Latest Draft Standard",
+    "stdcpplatest", 0 },
+
+  { "PrecompiledHeader", "Yc", "Create", "Create",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "PrecompiledHeader", "Yu", "Use", "Use",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+
+  { "AssemblerOutput", "", "No Listing", "NoListing", 0 },
+  { "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
+  { "AssemblerOutput", "FAc", "Assembly With Machine Code",
+    "AssemblyAndMachineCode", 0 },
+  { "AssemblerOutput", "FAs", "Assembly With Source Code",
+    "AssemblyAndSourceCode", 0 },
+  { "AssemblerOutput", "FAcs", "Assembly, Machine Code and Source", "All", 0 },
+
+  { "CallingConvention", "Gd", "__cdecl", "Cdecl", 0 },
+  { "CallingConvention", "Gr", "__fastcall", "FastCall", 0 },
+  { "CallingConvention", "Gz", "__stdcall", "StdCall", 0 },
+  { "CallingConvention", "Gv", "__vectorcall", "VectorCall", 0 },
+
+  { "CompileAs", "", "Default", "Default", 0 },
+  { "CompileAs", "TC", "Compile as C Code", "CompileAsC", 0 },
+  { "CompileAs", "TP", "Compile as C++ Code", "CompileAsCpp", 0 },
+
+  { "ErrorReporting", "errorReport:none", "Do Not Send Report", "None", 0 },
+  { "ErrorReporting", "errorReport:prompt", "Prompt Immediately", "Prompt",
+    0 },
+  { "ErrorReporting", "errorReport:queue", "Queue For Next Login", "Queue",
+    0 },
+  { "ErrorReporting", "errorReport:send", "Send Automatically", "Send", 0 },
+
+  { "CompileAsManaged", "", "No Common Language RunTime Support", "false", 0 },
+  { "CompileAsManaged", "clr", "Common Language RunTime Support", "true", 0 },
+  { "CompileAsManaged", "clr:pure",
+    "Pure MSIL Common Language RunTime Support", "Pure", 0 },
+  { "CompileAsManaged", "clr:safe",
+    "Safe MSIL Common Language RunTime Support", "Safe", 0 },
+  { "CompileAsManaged", "clr:oldSyntax",
+    "Common Language RunTime Support, Old Syntax", "OldSyntax", 0 },
+
+  { "CppLanguageStandard", "", "Default", "Default", 0 },
+  { "CppLanguageStandard", "std=c++98", "C++03", "c++98", 0 },
+  { "CppLanguageStandard", "std=c++11", "C++11", "c++11", 0 },
+  { "CppLanguageStandard", "std=c++1y", "C++14", "c++1y", 0 },
+  { "CppLanguageStandard", "std=c++14", "C++14", "c++1y", 0 },
+  { "CppLanguageStandard", "std=gnu++98", "C++03 (GNU Dialect)", "gnu++98",
+    0 },
+  { "CppLanguageStandard", "std=gnu++11", "C++11 (GNU Dialect)", "gnu++11",
+    0 },
+  { "CppLanguageStandard", "std=gnu++1y", "C++14 (GNU Dialect)", "gnu++1y",
+    0 },
+  { "CppLanguageStandard", "std=gnu++14", "C++14 (GNU Dialect)", "gnu++1y",
+    0 },
+
+  // Bool Properties
+  { "CompileAsWinRT", "ZW", "", "true", 0 },
+  { "WinRTNoStdLib", "ZW:nostdlib", "", "true", 0 },
+  { "SuppressStartupBanner", "nologo", "", "true", 0 },
+  { "TreatWarningAsError", "WX-", "", "false", 0 },
+  { "TreatWarningAsError", "WX", "", "true", 0 },
+  { "SDLCheck", "sdl-", "", "false", 0 },
+  { "SDLCheck", "sdl", "", "true", 0 },
+  { "IntrinsicFunctions", "Oi", "", "true", 0 },
+  { "OmitFramePointers", "Oy-", "", "false", 0 },
+  { "OmitFramePointers", "Oy", "", "true", 0 },
+  { "EnableFiberSafeOptimizations", "GT", "", "true", 0 },
+  { "WholeProgramOptimization", "GL", "", "true", 0 },
+  { "UndefineAllPreprocessorDefinitions", "u", "", "true", 0 },
+  { "IgnoreStandardIncludePath", "X", "", "true", 0 },
+  { "PreprocessToFile", "P", "", "true", 0 },
+  { "PreprocessSuppressLineNumbers", "EP", "", "true", 0 },
+  { "PreprocessKeepComments", "C", "", "true", 0 },
+  { "StringPooling", "GF-", "", "false", 0 },
+  { "StringPooling", "GF", "", "true", 0 },
+  { "MinimalRebuild", "Gm-", "", "false", 0 },
+  { "MinimalRebuild", "Gm", "", "true", 0 },
+  { "SmallerTypeCheck", "RTCc", "", "true", 0 },
+  { "FunctionLevelLinking", "Gy-", "", "false", 0 },
+  { "FunctionLevelLinking", "Gy", "", "true", 0 },
+  { "EnableParallelCodeGeneration", "Qpar-", "", "false", 0 },
+  { "EnableParallelCodeGeneration", "Qpar", "", "true", 0 },
+  { "FloatingPointExceptions", "fp:except-", "", "false", 0 },
+  { "FloatingPointExceptions", "fp:except", "", "true", 0 },
+  { "CreateHotpatchableImage", "hotpatch", "", "true", 0 },
+  { "DisableLanguageExtensions", "Za", "", "true", 0 },
+  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t-", "", "false", 0 },
+  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0 },
+  { "ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0 },
+  { "ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0 },
+  { "RemoveUnreferencedCodeData", "Zc:inline", "", "true", 0 },
+  { "EnforceTypeConversionRules", "Zc:rvalueCast-", "", "false", 0 },
+  { "EnforceTypeConversionRules", "Zc:rvalueCast", "", "true", 0 },
+  { "RuntimeTypeInfo", "GR-", "", "false", 0 },
+  { "RuntimeTypeInfo", "GR", "", "true", 0 },
+  { "OpenMPSupport", "openmp-", "", "false", 0 },
+  { "OpenMPSupport", "openmp", "", "true", 0 },
+  { "ExpandAttributedSource", "Fx", "", "true", 0 },
+  { "UseUnicodeForAssemblerListing", "FAu", "", "true", 0 },
+  { "ShowIncludes", "showIncludes", "", "true", 0 },
+  { "EnablePREfast", "analyze-", "", "false", 0 },
+  { "EnablePREfast", "analyze", "", "true", 0 },
+  { "UseFullPaths", "FC", "", "true", 0 },
+  { "OmitDefaultLibName", "Zl", "", "true", 0 },
+
+  // Bool Properties With Argument
+  { "MultiProcessorCompilation", "MP", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "ProcessorNumber", "MP", "Multi-processor Compilation", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "GenerateXMLDocumentationFiles", "doc", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "XMLDocumentationFileName", "doc", "Generate XML Documentation Files", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "BrowseInformation", "FR", "", "true",
+    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
+  { "BrowseInformationFile", "FR", "Enable Browse Information", "",
+    cmVS7FlagTable::UserValueRequired },
+
+  // String List Properties
+  { "AdditionalIncludeDirectories", "I", "Additional Include Directories", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "AdditionalUsingDirectories", "AI", "Additional #using Directories", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "PreprocessorDefinitions", "D ", "Preprocessor Definitions", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "UndefinePreprocessorDefinitions", "U",
+    "Undefine Preprocessor Definitions", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "DisableSpecificWarnings", "wd", "Disable Specific Warnings", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "ForcedIncludeFiles", "FI", "Forced Include File", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "ForcedUsingFiles", "FU", "Forced #using File", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "PREfastLog", "analyze:log", "Code Analysis Log", "",
+    cmVS7FlagTable::UserFollowing },
+  { "PREfastAdditionalPlugins", "analyze:plugin",
+    "Additional Code Analysis Native plugins", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "TreatSpecificWarningsAsErrors", "we", "Treat Specific Warnings As Errors",
+    "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+
+  // String Properties
+  { "WarningVersion", "Wv:", "Warning Version", "",
+    cmVS7FlagTable::UserValue },
+  // Skip [TrackerLogDirectory] - no command line Switch.
+  { "PreprocessOutputPath", "Fi", "Preprocess Output Path", "",
+    cmVS7FlagTable::UserValue },
+  { "PrecompiledHeaderFile", "Yc", "Precompiled Header Name", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "PrecompiledHeaderFile", "Yu", "Precompiled Header Name", "",
+    cmVS7FlagTable::UserValueRequired },
+  { "PrecompiledHeaderOutputFile", "Fp", "Precompiled Header Output File", "",
+    cmVS7FlagTable::UserValue },
+  { "AssemblerListingLocation", "Fa", "ASM List Location", "",
+    cmVS7FlagTable::UserValue },
+  { "ObjectFileName", "Fo", "Object File Name", "",
+    cmVS7FlagTable::UserValue },
+  { "ProgramDataBaseFileName", "Fd", "Program Database File Name", "",
+    cmVS7FlagTable::UserValue },
+  // Skip [XMLDocumentationFileName] - no command line Switch.
+  // Skip [BrowseInformationFile] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  { 0, 0, 0, 0, 0 }
+};
diff --git a/Source/cmVS14CLFlagTable.h b/Source/cmVS14CLFlagTable.h
deleted file mode 100644
index 5812e79..0000000
--- a/Source/cmVS14CLFlagTable.h
+++ /dev/null
@@ -1,237 +0,0 @@
-static cmVS7FlagTable cmVS14CLFlagTable[] = {
-
-  // Enum Properties
-  { "DebugInformationFormat", "", "None", "None", 0 },
-  { "DebugInformationFormat", "Z7", "C7 compatible", "OldStyle", 0 },
-  { "DebugInformationFormat", "Zi", "Program Database", "ProgramDatabase", 0 },
-  { "DebugInformationFormat", "ZI", "Program Database for Edit And Continue",
-    "EditAndContinue", 0 },
-
-  { "WarningLevel", "W0", "Turn Off All Warnings", "TurnOffAllWarnings", 0 },
-  { "WarningLevel", "W1", "Level1", "Level1", 0 },
-  { "WarningLevel", "W2", "Level2", "Level2", 0 },
-  { "WarningLevel", "W3", "Level3", "Level3", 0 },
-  { "WarningLevel", "W4", "Level4", "Level4", 0 },
-  { "WarningLevel", "Wall", "EnableAllWarnings", "EnableAllWarnings", 0 },
-
-  { "Optimization", "", "Custom", "Custom", 0 },
-  { "Optimization", "Od", "Disabled", "Disabled", 0 },
-  { "Optimization", "O1", "Minimize Size", "MinSpace", 0 },
-  { "Optimization", "O2", "Maximize Speed", "MaxSpeed", 0 },
-  { "Optimization", "Ox", "Full Optimization", "Full", 0 },
-
-  { "InlineFunctionExpansion", "", "Default", "Default", 0 },
-  { "InlineFunctionExpansion", "Ob0", "Disabled", "Disabled", 0 },
-  { "InlineFunctionExpansion", "Ob1", "Only __inline", "OnlyExplicitInline",
-    0 },
-  { "InlineFunctionExpansion", "Ob2", "Any Suitable", "AnySuitable", 0 },
-
-  { "FavorSizeOrSpeed", "Os", "Favor small code", "Size", 0 },
-  { "FavorSizeOrSpeed", "Ot", "Favor fast code", "Speed", 0 },
-  { "FavorSizeOrSpeed", "", "Neither", "Neither", 0 },
-
-  { "ExceptionHandling", "EHa", "Yes with SEH Exceptions", "Async", 0 },
-  { "ExceptionHandling", "EHsc", "Yes", "Sync", 0 },
-  { "ExceptionHandling", "EHs", "Yes with Extern C functions", "SyncCThrow",
-    0 },
-  { "ExceptionHandling", "", "No", "false", 0 },
-
-  { "BasicRuntimeChecks", "RTCs", "Stack Frames", "StackFrameRuntimeCheck",
-    0 },
-  { "BasicRuntimeChecks", "RTCu", "Uninitialized variables",
-    "UninitializedLocalUsageCheck", 0 },
-  { "BasicRuntimeChecks", "RTC1", "Both (/RTC1, equiv. to /RTCsu)",
-    "EnableFastChecks", 0 },
-  { "BasicRuntimeChecks", "", "Default", "Default", 0 },
-
-  { "RuntimeLibrary", "MT", "Multi-threaded", "MultiThreaded", 0 },
-  { "RuntimeLibrary", "MTd", "Multi-threaded Debug", "MultiThreadedDebug", 0 },
-  { "RuntimeLibrary", "MD", "Multi-threaded DLL", "MultiThreadedDLL", 0 },
-  { "RuntimeLibrary", "MDd", "Multi-threaded Debug DLL",
-    "MultiThreadedDebugDLL", 0 },
-
-  { "StructMemberAlignment", "Zp1", "1 Byte", "1Byte", 0 },
-  { "StructMemberAlignment", "Zp2", "2 Bytes", "2Bytes", 0 },
-  { "StructMemberAlignment", "Zp4", "4 Byte", "4Bytes", 0 },
-  { "StructMemberAlignment", "Zp8", "8 Bytes", "8Bytes", 0 },
-  { "StructMemberAlignment", "Zp16", "16 Bytes", "16Bytes", 0 },
-  { "StructMemberAlignment", "", "Default", "Default", 0 },
-
-  { "BufferSecurityCheck", "GS-", "Disable Security Check", "false", 0 },
-  { "BufferSecurityCheck", "GS", "Enable Security Check", "true", 0 },
-
-  { "EnableEnhancedInstructionSet", "arch:SSE", "Streaming SIMD Extensions",
-    "StreamingSIMDExtensions", 0 },
-  { "EnableEnhancedInstructionSet", "arch:SSE2", "Streaming SIMD Extensions 2",
-    "StreamingSIMDExtensions2", 0 },
-  { "EnableEnhancedInstructionSet", "arch:AVX", "Advanced Vector Extensions",
-    "AdvancedVectorExtensions", 0 },
-  { "EnableEnhancedInstructionSet", "arch:AVX2",
-    "Advanced Vector Extensions 2", "AdvancedVectorExtensions2", 0 },
-  { "EnableEnhancedInstructionSet", "arch:IA32", "No Enhanced Instructions",
-    "NoExtensions", 0 },
-  { "EnableEnhancedInstructionSet", "", "Not Set", "NotSet", 0 },
-
-  { "FloatingPointModel", "fp:precise", "Precise", "Precise", 0 },
-  { "FloatingPointModel", "fp:strict", "Strict", "Strict", 0 },
-  { "FloatingPointModel", "fp:fast", "Fast", "Fast", 0 },
-
-  { "PrecompiledHeader", "Yc", "Create", "Create",
-    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
-  { "PrecompiledHeader", "Yu", "Use", "Use",
-    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
-  { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
-
-  { "AssemblerOutput", "", "No Listing", "NoListing", 0 },
-  { "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
-  { "AssemblerOutput", "FAc", "Assembly With Machine Code",
-    "AssemblyAndMachineCode", 0 },
-  { "AssemblerOutput", "FAs", "Assembly With Source Code",
-    "AssemblyAndSourceCode", 0 },
-  { "AssemblerOutput", "FAcs", "Assembly, Machine Code and Source", "All", 0 },
-
-  { "CallingConvention", "Gd", "__cdecl", "Cdecl", 0 },
-  { "CallingConvention", "Gr", "__fastcall", "FastCall", 0 },
-  { "CallingConvention", "Gz", "__stdcall", "StdCall", 0 },
-  { "CallingConvention", "Gv", "__vectorcall", "VectorCall", 0 },
-
-  { "CompileAs", "", "Default", "Default", 0 },
-  { "CompileAs", "TC", "Compile as C Code", "CompileAsC", 0 },
-  { "CompileAs", "TP", "Compile as C++ Code", "CompileAsCpp", 0 },
-
-  { "ErrorReporting", "errorReport:none", "Do Not Send Report", "None", 0 },
-  { "ErrorReporting", "errorReport:prompt", "Prompt Immediately", "Prompt",
-    0 },
-  { "ErrorReporting", "errorReport:queue", "Queue For Next Login", "Queue",
-    0 },
-  { "ErrorReporting", "errorReport:send", "Send Automatically", "Send", 0 },
-
-  { "CompileAsManaged", "", "No Common Language RunTime Support", "false", 0 },
-  { "CompileAsManaged", "clr", "Common Language RunTime Support", "true", 0 },
-  { "CompileAsManaged", "clr:pure",
-    "Pure MSIL Common Language RunTime Support", "Pure", 0 },
-  { "CompileAsManaged", "clr:safe",
-    "Safe MSIL Common Language RunTime Support", "Safe", 0 },
-  { "CompileAsManaged", "clr:oldSyntax",
-    "Common Language RunTime Support, Old Syntax", "OldSyntax", 0 },
-
-  { "CppLanguageStandard", "", "Default", "Default", 0 },
-  { "CppLanguageStandard", "std=c++98", "C++03", "c++98", 0 },
-  { "CppLanguageStandard", "std=c++11", "C++11", "c++11", 0 },
-  { "CppLanguageStandard", "std=c++1y", "C++14", "c++1y", 0 },
-  { "CppLanguageStandard", "std=c++14", "C++14", "c++1y", 0 },
-  { "CppLanguageStandard", "std=gnu++98", "C++03 (GNU Dialect)", "gnu++98",
-    0 },
-  { "CppLanguageStandard", "std=gnu++11", "C++11 (GNU Dialect)", "gnu++11",
-    0 },
-  { "CppLanguageStandard", "std=gnu++1y", "C++14 (GNU Dialect)", "gnu++1y",
-    0 },
-  { "CppLanguageStandard", "std=gnu++14", "C++14 (GNU Dialect)", "gnu++1y",
-    0 },
-
-  // Bool Properties
-  { "CompileAsWinRT", "ZW", "", "true", 0 },
-  { "WinRTNoStdLib", "ZW:nostdlib", "", "true", 0 },
-  { "SuppressStartupBanner", "nologo", "", "true", 0 },
-  { "TreatWarningAsError", "WX-", "", "false", 0 },
-  { "TreatWarningAsError", "WX", "", "true", 0 },
-  { "SDLCheck", "sdl-", "", "false", 0 },
-  { "SDLCheck", "sdl", "", "true", 0 },
-  { "IntrinsicFunctions", "Oi", "", "true", 0 },
-  { "OmitFramePointers", "Oy-", "", "false", 0 },
-  { "OmitFramePointers", "Oy", "", "true", 0 },
-  { "EnableFiberSafeOptimizations", "GT", "", "true", 0 },
-  { "WholeProgramOptimization", "GL", "", "true", 0 },
-  { "UndefineAllPreprocessorDefinitions", "u", "", "true", 0 },
-  { "IgnoreStandardIncludePath", "X", "", "true", 0 },
-  { "PreprocessToFile", "P", "", "true", 0 },
-  { "PreprocessSuppressLineNumbers", "EP", "", "true", 0 },
-  { "PreprocessKeepComments", "C", "", "true", 0 },
-  { "StringPooling", "GF-", "", "false", 0 },
-  { "StringPooling", "GF", "", "true", 0 },
-  { "MinimalRebuild", "Gm-", "", "false", 0 },
-  { "MinimalRebuild", "Gm", "", "true", 0 },
-  { "SmallerTypeCheck", "RTCc", "", "true", 0 },
-  { "FunctionLevelLinking", "Gy-", "", "false", 0 },
-  { "FunctionLevelLinking", "Gy", "", "true", 0 },
-  { "EnableParallelCodeGeneration", "Qpar-", "", "false", 0 },
-  { "EnableParallelCodeGeneration", "Qpar", "", "true", 0 },
-  { "FloatingPointExceptions", "fp:except-", "", "false", 0 },
-  { "FloatingPointExceptions", "fp:except", "", "true", 0 },
-  { "CreateHotpatchableImage", "hotpatch", "", "true", 0 },
-  { "DisableLanguageExtensions", "Za", "", "true", 0 },
-  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t-", "", "false", 0 },
-  { "TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0 },
-  { "ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0 },
-  { "ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0 },
-  { "RuntimeTypeInfo", "GR-", "", "false", 0 },
-  { "RuntimeTypeInfo", "GR", "", "true", 0 },
-  { "OpenMPSupport", "openmp-", "", "false", 0 },
-  { "OpenMPSupport", "openmp", "", "true", 0 },
-  { "ExpandAttributedSource", "Fx", "", "true", 0 },
-  { "UseUnicodeForAssemblerListing", "FAu", "", "true", 0 },
-  { "ShowIncludes", "showIncludes", "", "true", 0 },
-  { "EnablePREfast", "analyze-", "", "false", 0 },
-  { "EnablePREfast", "analyze", "", "true", 0 },
-  { "UseFullPaths", "FC", "", "true", 0 },
-  { "OmitDefaultLibName", "Zl", "", "true", 0 },
-
-  // Bool Properties With Argument
-  { "MultiProcessorCompilation", "MP", "", "true",
-    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
-  { "ProcessorNumber", "MP", "Multi-processor Compilation", "",
-    cmVS7FlagTable::UserValueRequired },
-  { "GenerateXMLDocumentationFiles", "doc", "", "true",
-    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
-  { "XMLDocumentationFileName", "doc", "Generate XML Documentation Files", "",
-    cmVS7FlagTable::UserValueRequired },
-  { "BrowseInformation", "FR", "", "true",
-    cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
-  { "BrowseInformationFile", "FR", "Enable Browse Information", "",
-    cmVS7FlagTable::UserValueRequired },
-
-  // String List Properties
-  { "AdditionalIncludeDirectories", "I", "Additional Include Directories", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "AdditionalUsingDirectories", "AI", "Additional #using Directories", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "PreprocessorDefinitions", "D ", "Preprocessor Definitions", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "UndefinePreprocessorDefinitions", "U",
-    "Undefine Preprocessor Definitions", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "DisableSpecificWarnings", "wd", "Disable Specific Warnings", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "ForcedIncludeFiles", "FI", "Forced Include File", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "ForcedUsingFiles", "FU", "Forced #using File", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "PREfastLog", "analyze:log", "Code Analysis Log", "",
-    cmVS7FlagTable::UserFollowing },
-  { "PREfastAdditionalPlugins", "analyze:plugin",
-    "Additional Code Analysis Native plugins", "",
-    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-  { "TreatSpecificWarningsAsErrors", "we", "Treat Specific Warnings As Errors",
-    "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
-
-  // String Properties
-  // Skip [TrackerLogDirectory] - no command line Switch.
-  { "PreprocessOutputPath", "Fi", "Preprocess Output Path", "",
-    cmVS7FlagTable::UserValue },
-  { "PrecompiledHeaderFile", "Yc", "Precompiled Header Name", "",
-    cmVS7FlagTable::UserValueRequired },
-  { "PrecompiledHeaderFile", "Yu", "Precompiled Header Name", "",
-    cmVS7FlagTable::UserValueRequired },
-  { "PrecompiledHeaderOutputFile", "Fp", "Precompiled Header Output File", "",
-    cmVS7FlagTable::UserValue },
-  { "AssemblerListingLocation", "Fa", "ASM List Location", "",
-    cmVS7FlagTable::UserValue },
-  { "ObjectFileName", "Fo", "Object File Name", "",
-    cmVS7FlagTable::UserValue },
-  { "ProgramDataBaseFileName", "Fd", "Program Database File Name", "",
-    cmVS7FlagTable::UserValue },
-  // Skip [XMLDocumentationFileName] - no command line Switch.
-  // Skip [BrowseInformationFile] - no command line Switch.
-  // Skip [AdditionalOptions] - no command line Switch.
-  { 0, 0, 0, 0, 0 }
-};
diff --git a/Source/cmVS14LinkFlagTable.h b/Source/cmVS14LinkFlagTable.h
index 6e56422..596f880 100644
--- a/Source/cmVS14LinkFlagTable.h
+++ b/Source/cmVS14LinkFlagTable.h
@@ -35,6 +35,12 @@ static cmVS7FlagTable cmVS14LinkFlagTable[] = {
   { "UACExecutionLevel", "level='requireAdministrator'",
     "requireAdministrator", "RequireAdministrator", 0 },
 
+  { "GenerateDebugInformation", "DEBUG:FASTLINK",
+    "Optimize for faster linking", "DebugFastLink",
+    cmVS7FlagTable::CaseInsensitive },
+  { "GenerateDebugInformation", "DEBUG", "Optimize for debugging", "Debug",
+    cmVS7FlagTable::CaseInsensitive },
+
   { "SubSystem", "", "Not Set", "NotSet", 0 },
   { "SubSystem", "SUBSYSTEM:CONSOLE", "Console", "Console", 0 },
   { "SubSystem", "SUBSYSTEM:WINDOWS", "Windows", "Windows", 0 },
@@ -54,6 +60,8 @@ static cmVS7FlagTable cmVS14LinkFlagTable[] = {
   { "Driver", "DRIVER:WDM", "WDM", "WDM", 0 },
 
   { "LinkTimeCodeGeneration", "", "Default", "Default", 0 },
+  { "LinkTimeCodeGeneration", "LTCG:incremental",
+    "Use Fast Link Time Code Generation", "UseFastLinkTimeCodeGeneration", 0 },
   { "LinkTimeCodeGeneration", "LTCG", "Use Link Time Code Generation",
     "UseLinkTimeCodeGeneration", 0 },
   { "LinkTimeCodeGeneration", "LTCG:PGInstrument",
@@ -121,6 +129,9 @@ static cmVS7FlagTable cmVS14LinkFlagTable[] = {
   { "CLRSupportLastError", "CLRSupportLastError:SYSTEMDLL", "System Dlls Only",
     "SystemDlls", 0 },
 
+  { "LinkControlFlowGuard", "guard:cf", "Enable Security Check with Guard",
+    "Guard", 0 },
+
   // Bool Properties
   { "LinkIncremental", "INCREMENTAL:NO", "", "false", 0 },
   { "LinkIncremental", "INCREMENTAL", "", "true", 0 },
@@ -138,10 +149,6 @@ static cmVS7FlagTable cmVS14LinkFlagTable[] = {
   { "UACUIAccess", "uiAccess='false'", "", "false", 0 },
   { "UACUIAccess", "uiAccess='true'", "", "true", 0 },
   { "ManifestEmbed", "manifest:embed", "", "true", 0 },
-  { "GenerateDebugInformation", "DEBUG:FASTLINK", "", "DebugFastLink",
-    cmVS7FlagTable::CaseInsensitive },
-  { "GenerateDebugInformation", "DEBUG", "", "Debug",
-    cmVS7FlagTable::CaseInsensitive },
   { "MapExports", "MAPINFO:EXPORTS", "", "true", 0 },
   { "AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0 },
   { "AssemblyDebug", "ASSEMBLYDEBUG", "", "true", 0 },
@@ -195,6 +202,8 @@ static cmVS7FlagTable cmVS14LinkFlagTable[] = {
   { "AdditionalLibraryDirectories", "LIBPATH:",
     "Additional Library Directories", "",
     cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
+  { "Natvis", "NATVIS:", "Natvis files", "",
+    cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable },
   // Skip [AdditionalDependencies] - no command line Switch.
   { "IgnoreSpecificDefaultLibraries", "NODEFAULTLIB:",
     "Ignore Specific Default Libraries", "",
diff --git a/Source/cmVariableRequiresCommand.cxx b/Source/cmVariableRequiresCommand.cxx
index 8d55b0e..7599551 100644
--- a/Source/cmVariableRequiresCommand.cxx
+++ b/Source/cmVariableRequiresCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVariableRequiresCommand.h"
 
 #include "cmState.h"
diff --git a/Source/cmVariableRequiresCommand.h b/Source/cmVariableRequiresCommand.h
index b83f615..e40151b 100644
--- a/Source/cmVariableRequiresCommand.h
+++ b/Source/cmVariableRequiresCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVariableRequiresCommand_h
 #define cmVariableRequiresCommand_h
 
@@ -18,10 +9,10 @@ class cmVariableRequiresCommand : public cmCommand
 {
 public:
   cmTypeMacro(cmVariableRequiresCommand, cmCommand);
-  virtual cmCommand* Clone() { return new cmVariableRequiresCommand; }
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
-  virtual std::string GetName() const { return "variable_requires"; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmVariableRequiresCommand; }
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+  std::string GetName() const CM_OVERRIDE { return "variable_requires"; }
 };
 
 #endif
diff --git a/Source/cmVariableWatch.cxx b/Source/cmVariableWatch.cxx
index 11eaa93..c94ce17 100644
--- a/Source/cmVariableWatch.cxx
+++ b/Source/cmVariableWatch.cxx
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVariableWatch.h"
 
 #include "cmAlgorithms.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <algorithm>
+#include <cm_auto_ptr.hxx>
+#include <utility>
 
 static const char* const cmVariableWatchAccessStrings[] = {
   "READ_ACCESS",     "UNKNOWN_READ_ACCESS", "UNKNOWN_DEFINED_ACCESS",
@@ -48,7 +41,7 @@ bool cmVariableWatch::AddWatch(const std::string& variable, WatchMethod method,
                                void* client_data /*=0*/,
                                DeleteData delete_data /*=0*/)
 {
-  cmsys::auto_ptr<cmVariableWatch::Pair> p(new cmVariableWatch::Pair);
+  CM_AUTO_PTR<cmVariableWatch::Pair> p(new cmVariableWatch::Pair);
   p->Method = method;
   p->ClientData = client_data;
   p->DeleteDataCall = delete_data;
diff --git a/Source/cmVariableWatch.h b/Source/cmVariableWatch.h
index be8f72f..0b8b433 100644
--- a/Source/cmVariableWatch.h
+++ b/Source/cmVariableWatch.h
@@ -1,18 +1,13 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVariableWatch_h
 #define cmVariableWatch_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
+#include <vector>
 
 class cmMakefile;
 
@@ -36,9 +31,10 @@ public:
    * Add watch to the variable
    */
   bool AddWatch(const std::string& variable, WatchMethod method,
-                void* client_data = 0, DeleteData delete_data = 0);
+                void* client_data = CM_NULLPTR,
+                DeleteData delete_data = CM_NULLPTR);
   void RemoveWatch(const std::string& variable, WatchMethod method,
-                   void* client_data = 0);
+                   void* client_data = CM_NULLPTR);
 
   /**
    * This method is called when variable is accessed
@@ -71,9 +67,9 @@ protected:
     void* ClientData;
     DeleteData DeleteDataCall;
     Pair()
-      : Method(0)
-      , ClientData(0)
-      , DeleteDataCall(0)
+      : Method(CM_NULLPTR)
+      , ClientData(CM_NULLPTR)
+      , DeleteDataCall(CM_NULLPTR)
     {
     }
     ~Pair()
diff --git a/Source/cmVariableWatchCommand.cxx b/Source/cmVariableWatchCommand.cxx
index f30ffe8..5c1e00a 100644
--- a/Source/cmVariableWatchCommand.cxx
+++ b/Source/cmVariableWatchCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVariableWatchCommand.h"
 
 #include "cmVariableWatch.h"
@@ -104,7 +95,7 @@ cmVariableWatchCommand::~cmVariableWatchCommand()
 bool cmVariableWatchCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("must be called with at least one argument.");
     return false;
   }
diff --git a/Source/cmVariableWatchCommand.h b/Source/cmVariableWatchCommand.h
index aad53cb..b1862f0 100644
--- a/Source/cmVariableWatchCommand.h
+++ b/Source/cmVariableWatchCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVariableWatchCommand_h
 #define cmVariableWatchCommand_h
 
@@ -24,34 +15,34 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmVariableWatchCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmVariableWatchCommand; }
 
   //! Default constructor
   cmVariableWatchCommand();
 
   //! Destructor.
-  ~cmVariableWatchCommand();
+  ~cmVariableWatchCommand() CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /** This command does not really have a final pass but it needs to
       stay alive since it owns variable watch callback information. */
-  virtual bool HasFinalPass() const { return true; }
+  bool HasFinalPass() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "variable_watch"; }
+  std::string GetName() const CM_OVERRIDE { return "variable_watch"; }
 
   cmTypeMacro(cmVariableWatchCommand, cmCommand);
 
diff --git a/Source/cmVersion.cxx b/Source/cmVersion.cxx
index 4c2e4ce..a091b91 100644
--- a/Source/cmVersion.cxx
+++ b/Source/cmVersion.cxx
@@ -1,17 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVersion.h"
 
-#include "cmVersionMacros.h"
+#include "cmVersionConfig.h"
 
 unsigned int cmVersion::GetMajorVersion()
 {
diff --git a/Source/cmVersion.h b/Source/cmVersion.h
index 46fd5a6..e77ec99 100644
--- a/Source/cmVersion.h
+++ b/Source/cmVersion.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVersion_h
 #define cmVersion_h
 
-#include "cmStandardIncludes.h"
+#include <cm_kwiml.h>
 
 /** \class cmVersion
  * \brief Helper class for providing CMake and CTest version information.
diff --git a/Source/cmVersionConfig.h.in b/Source/cmVersionConfig.h.in
index 16aeabe..06251f3 100644
--- a/Source/cmVersionConfig.h.in
+++ b/Source/cmVersionConfig.h.in
@@ -1,15 +1,8 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #define CMake_VERSION_MAJOR @CMake_VERSION_MAJOR@
 #define CMake_VERSION_MINOR @CMake_VERSION_MINOR@
 #define CMake_VERSION_PATCH @CMake_VERSION_PATCH@
+#define CMake_VERSION_SUFFIX "@CMake_VERSION_SUFFIX@"
+#define CMake_VERSION_IS_DIRTY @CMake_VERSION_IS_DIRTY@
 #define CMake_VERSION "@CMake_VERSION@"
diff --git a/Source/cmVersionMacros.h b/Source/cmVersionMacros.h
index a2dcce4..1b617bd 100644
--- a/Source/cmVersionMacros.h
+++ b/Source/cmVersionMacros.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVersionMacros_h
 #define cmVersionMacros_h
 
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index 1999397..82f4b99 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVisualStudio10TargetGenerator.h"
 
 #include "cmComputeLinkInformation.h"
@@ -34,7 +25,8 @@
 #include "cmVS12LinkFlagTable.h"
 #include "cmVS12MASMFlagTable.h"
 #include "cmVS12RCFlagTable.h"
-#include "cmVS14CLFlagTable.h"
+#include "cmVS140CLFlagTable.h"
+#include "cmVS141CLFlagTable.h"
 #include "cmVS14LibFlagTable.h"
 #include "cmVS14LinkFlagTable.h"
 #include "cmVS14MASMFlagTable.h"
@@ -42,7 +34,7 @@
 #include "cmVisualStudioGeneratorOptions.h"
 #include "windows.h"
 
-#include <cmsys/auto_ptr.hxx>
+#include <cm_auto_ptr.hxx>
 
 static std::string const kWINDOWS_7_1_SDK = "Windows7.1SDK";
 
@@ -52,7 +44,13 @@ cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetClFlagTable() const
     cmGlobalVisualStudioGenerator::VSVersion v =
       this->LocalGenerator->GetVersion();
     if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      return cmVS14CLFlagTable;
+      // FIXME: All flag table selection should be based on the toolset name.
+      // See issue #16153.  For now, treat VS 15's toolset as a special case.
+      const char* toolset = this->GlobalGenerator->GetPlatformToolset();
+      if (toolset && cmHasLiteralPrefix(toolset, "v141")) {
+        return cmVS141CLFlagTable;
+      }
+      return cmVS140CLFlagTable;
     } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
       return cmVS12CLFlagTable;
     } else if (v == cmGlobalVisualStudioGenerator::VS11) {
@@ -532,7 +530,9 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
              this->Configurations.begin();
            i != this->Configurations.end(); ++i) {
         this->WritePlatformConfigTag("LogicalName", i->c_str(), 3);
-        if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE")) {
+        if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
+            // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
+            this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
           (*this->BuildFileStream) << "$(RootNamespace).";
         }
         (*this->BuildFileStream) << "%(Filename)";
@@ -1188,6 +1188,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
     tool = "PRIResource";
   } else if (ext == "xml") {
     tool = "XML";
+  } else if (ext == "natvis") {
+    tool = "Natvis";
   }
 
   if (this->NsightTegra) {
@@ -1204,6 +1206,11 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
     }
   }
 
+  const char* toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
+  if (toolOverride && *toolOverride) {
+    tool = toolOverride;
+  }
+
   std::string deployContent;
   std::string deployLocation;
   if (this->GlobalGenerator->TargetsWindowsPhone() ||
@@ -1225,8 +1232,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
 
     if (!deployContent.empty()) {
       cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-        ge.Parse(deployContent);
+      CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(deployContent);
       // Deployment location cannot be set on a configuration basis
       if (!deployLocation.empty()) {
         this->WriteString("<Link>", 3);
@@ -1680,7 +1686,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
   // copied from cmLocalVisualStudio7Generator.cxx 805
   // TODO: Integrate code below with cmLocalVisualStudio7Generator.
 
-  cmsys::auto_ptr<Options> pOptions(new Options(
+  CM_AUTO_PTR<Options> pOptions(new Options(
     this->LocalGenerator, Options::Compiler, this->GetClFlagTable()));
   Options& clOptions = *pOptions;
 
@@ -1796,7 +1802,8 @@ void cmVisualStudio10TargetGenerator::WriteClOptions(
   }
 
   if (this->MSTools) {
-    cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
+    cmsys::RegularExpression clangToolset(
+      "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)");
     const char* toolset = this->GlobalGenerator->GetPlatformToolset();
     if (toolset && clangToolset.find(toolset)) {
       this->WriteString("<ObjectFileName>"
@@ -1844,7 +1851,7 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
 bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
   std::string const& configName)
 {
-  cmsys::auto_ptr<Options> pOptions(new Options(
+  CM_AUTO_PTR<Options> pOptions(new Options(
     this->LocalGenerator, Options::ResourceCompiler, this->GetRcFlagTable()));
   Options& rcOptions = *pOptions;
 
@@ -1901,7 +1908,7 @@ bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
   std::string const& configName)
 {
-  cmsys::auto_ptr<Options> pOptions(new Options(
+  CM_AUTO_PTR<Options> pOptions(new Options(
     this->LocalGenerator, Options::MasmCompiler, this->GetMasmFlagTable()));
   Options& masmOptions = *pOptions;
 
@@ -2054,7 +2061,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
   if (const char* nativeLibDirectoriesExpression =
         this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
       ge.Parse(nativeLibDirectoriesExpression);
     std::string nativeLibDirs =
       cge->Evaluate(this->LocalGenerator, configName);
@@ -2067,7 +2074,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
         this->GeneratorTarget->GetProperty(
           "ANDROID_NATIVE_LIB_DEPENDENCIES")) {
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
       ge.Parse(nativeLibDependenciesExpression);
     std::string nativeLibDeps =
       cge->Evaluate(this->LocalGenerator, configName);
@@ -2086,7 +2093,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
   if (const char* jarDirectoriesExpression =
         this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
     cmGeneratorExpression ge;
-    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
       ge.Parse(jarDirectoriesExpression);
     std::string jarDirectories =
       cge->Evaluate(this->LocalGenerator, configName);
@@ -2146,7 +2153,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   std::string const& config)
 {
-  cmsys::auto_ptr<Options> pOptions(new Options(
+  CM_AUTO_PTR<Options> pOptions(new Options(
     this->LocalGenerator, Options::Linker, this->GetLinkFlagTable(), 0, this));
   Options& linkOptions = *pOptions;
 
@@ -2340,7 +2347,8 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
                            "%(IgnoreSpecificDefaultLibraries)");
   }
 
-  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY &&
+  if ((this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
+       this->GeneratorTarget->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (this->GeneratorTarget->GetPropertyAsBool(
           "WINDOWS_EXPORT_ALL_SYMBOLS")) {
@@ -2406,11 +2414,12 @@ void cmVisualStudio10TargetGenerator::AddLibraries(
 {
   typedef cmComputeLinkInformation::ItemVector ItemVector;
   ItemVector libs = cli.GetItems();
+  std::string currentBinDir =
+    this->LocalGenerator->GetCurrentBinaryDirectory();
   for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
     if (l->IsPath) {
-      std::string path = this->LocalGenerator->Convert(
-        l->Value.c_str(), cmOutputConverter::START_OUTPUT,
-        cmOutputConverter::UNCHANGED);
+      std::string path = this->LocalGenerator->ConvertToRelativePath(
+        currentBinDir, l->Value.c_str());
       this->ConvertToWindowsSlash(path);
       libVec.push_back(path);
     } else if (!l->Target ||
@@ -2507,7 +2516,8 @@ void cmVisualStudio10TargetGenerator::WriteEvents(
   std::string const& configName)
 {
   bool addedPrelink = false;
-  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY &&
+  if ((this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
+       this->GeneratorTarget->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (this->GeneratorTarget->GetPropertyAsBool(
           "WINDOWS_EXPORT_ALL_SYMBOLS")) {
@@ -2648,6 +2658,20 @@ void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
 
 void cmVisualStudio10TargetGenerator::WriteSDKReferences()
 {
+  std::vector<std::string> sdkReferences;
+  bool hasWrittenItemGroup = false;
+  if (const char* vsSDKReferences =
+        this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
+    cmSystemTools::ExpandListArgument(vsSDKReferences, sdkReferences);
+    this->WriteString("<ItemGroup>\n", 1);
+    hasWrittenItemGroup = true;
+    for (std::vector<std::string>::iterator ri = sdkReferences.begin();
+         ri != sdkReferences.end(); ++ri) {
+      this->WriteString("<SDKReference Include=\"", 2);
+      (*this->BuildFileStream) << cmVS10EscapeXML(*ri) << "\"/>\n";
+    }
+  }
+
   // This only applies to Windows 10 apps
   if (this->GlobalGenerator->TargetsWindowsStore() &&
       cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
@@ -2660,7 +2684,10 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences()
 
     if (desktopExtensionsVersion || mobileExtensionsVersion ||
         iotExtensionsVersion) {
-      this->WriteString("<ItemGroup>\n", 1);
+      if (!hasWrittenItemGroup) {
+        this->WriteString("<ItemGroup>\n", 1);
+        hasWrittenItemGroup = true;
+      }
       if (desktopExtensionsVersion) {
         this->WriteSingleSDKReference("WindowsDesktop",
                                       desktopExtensionsVersion);
@@ -2672,6 +2699,9 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences()
       if (iotExtensionsVersion) {
         this->WriteSingleSDKReference("WindowsIoT", iotExtensionsVersion);
       }
+    }
+
+    if (hasWrittenItemGroup) {
       this->WriteString("</ItemGroup>\n", 1);
     }
   }
@@ -2712,9 +2742,11 @@ void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile()
       this->WriteString("<AppxPackageArtifactsDir>", 2);
       (*this->BuildFileStream) << cmVS10EscapeXML(artifactDir)
                                << "\\</AppxPackageArtifactsDir>\n";
-      this->WriteString("<ProjectPriFullPath>"
-                        "$(TargetDir)resources.pri</ProjectPriFullPath>\n",
-                        2);
+      this->WriteString("<ProjectPriFullPath>", 2);
+      std::string resourcePriFile =
+        this->DefaultArtifactDir + "/resources.pri";
+      this->ConvertToWindowsSlash(resourcePriFile);
+      (*this->BuildFileStream) << resourcePriFile << "</ProjectPriFullPath>\n";
 
       // If we are missing files and we don't have a certificate and
       // aren't targeting WP8.0, add a default certificate
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index 109a100..c62be7e 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVisualStudioTargetGenerator_h
 #define cmVisualStudioTargetGenerator_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmMakefile;
diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx
index 3b31d7b..9badda6 100644
--- a/Source/cmVisualStudioGeneratorOptions.cxx
+++ b/Source/cmVisualStudioGeneratorOptions.cxx
@@ -96,6 +96,7 @@ void cmVisualStudioGeneratorOptions::FixExceptionHandlingDefault()
     case cmGlobalVisualStudioGenerator::VS11:
     case cmGlobalVisualStudioGenerator::VS12:
     case cmGlobalVisualStudioGenerator::VS14:
+    case cmGlobalVisualStudioGenerator::VS15:
       // by default VS puts <ExceptionHandling></ExceptionHandling> empty
       // for a project, to make our projects look the same put a new line
       // and space over for the closing </ExceptionHandling> as the default
diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h
index 219b009..4eeae3d 100644
--- a/Source/cmVisualStudioGeneratorOptions.h
+++ b/Source/cmVisualStudioGeneratorOptions.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVisualStudioGeneratorOptions_h
 #define cmVisualStudioGeneratorOptions_h
 
diff --git a/Source/cmVisualStudioSlnData.cxx b/Source/cmVisualStudioSlnData.cxx
index 7ffa0b5..48112dd 100644
--- a/Source/cmVisualStudioSlnData.cxx
+++ b/Source/cmVisualStudioSlnData.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVisualStudioSlnData.h"
 
 const cmSlnProjectEntry* cmSlnData::GetProjectByGUID(
diff --git a/Source/cmVisualStudioSlnData.h b/Source/cmVisualStudioSlnData.h
index 4508370..9f5ccb7 100644
--- a/Source/cmVisualStudioSlnData.h
+++ b/Source/cmVisualStudioSlnData.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVisualStudioSlnData_h
 #define cmVisualStudioSlnData_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmSlnProjectEntry
diff --git a/Source/cmVisualStudioSlnParser.cxx b/Source/cmVisualStudioSlnParser.cxx
index 7d7bb5b..939120a 100644
--- a/Source/cmVisualStudioSlnParser.cxx
+++ b/Source/cmVisualStudioSlnParser.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVisualStudioSlnParser.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmVisualStudioSlnParser.h b/Source/cmVisualStudioSlnParser.h
index b9f8a92..8939ab5 100644
--- a/Source/cmVisualStudioSlnParser.h
+++ b/Source/cmVisualStudioSlnParser.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVisualStudioSlnParser_h
 #define cmVisualStudioSlnParser_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include <bitset>
diff --git a/Source/cmVisualStudioWCEPlatformParser.cxx b/Source/cmVisualStudioWCEPlatformParser.cxx
index bc6b0bf..fc64d0f 100644
--- a/Source/cmVisualStudioWCEPlatformParser.cxx
+++ b/Source/cmVisualStudioWCEPlatformParser.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVisualStudioWCEPlatformParser.h"
 
 #include "cmGlobalVisualStudioGenerator.h"
diff --git a/Source/cmVisualStudioWCEPlatformParser.h b/Source/cmVisualStudioWCEPlatformParser.h
index 2b20eba..25f1a18 100644
--- a/Source/cmVisualStudioWCEPlatformParser.h
+++ b/Source/cmVisualStudioWCEPlatformParser.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmVisualStudioWCEPlatformParser_h
 #define cmVisualStudioWCEPlatformParser_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 #include "cmXMLParser.h"
diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx
index bec2861..c52ea40 100644
--- a/Source/cmWhileCommand.cxx
+++ b/Source/cmWhileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWhileCommand.h"
 
 #include "cmConditionEvaluator.h"
@@ -37,8 +28,7 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
     // if this is the endwhile for this while loop then execute
     if (!this->Depth) {
       // Remove the function blocker for this scope or bail.
-      cmsys::auto_ptr<cmFunctionBlocker> fb(
-        mf.RemoveFunctionBlocker(this, lff));
+      CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
       if (!fb.get()) {
         return false;
       }
@@ -105,10 +95,9 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
                                            messageType);
       }
       return true;
-    } else {
-      // decrement for each nested while that ends
-      this->Depth--;
     }
+    // decrement for each nested while that ends
+    this->Depth--;
   }
 
   // record the command
@@ -134,7 +123,7 @@ bool cmWhileFunctionBlocker::ShouldRemove(const cmListFileFunction& lff,
 bool cmWhileCommand::InvokeInitialPass(
   const std::vector<cmListFileArgument>& args, cmExecutionStatus&)
 {
-  if (args.size() < 1) {
+  if (args.empty()) {
     this->SetError("called with incorrect number of arguments");
     return false;
   }
diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h
index 0f35be8..9c70ca2 100644
--- a/Source/cmWhileCommand.h
+++ b/Source/cmWhileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWhileCommand_h
 #define cmWhileCommand_h
 
@@ -21,10 +12,10 @@ class cmWhileFunctionBlocker : public cmFunctionBlocker
 {
 public:
   cmWhileFunctionBlocker(cmMakefile* mf);
-  ~cmWhileFunctionBlocker();
-  virtual bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
-                                 cmExecutionStatus&);
-  virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf);
+  ~cmWhileFunctionBlocker() CM_OVERRIDE;
+  bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
+                         cmExecutionStatus&) CM_OVERRIDE;
+  bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
 
   std::vector<cmListFileArgument> Args;
   std::vector<cmListFileFunction> Functions;
@@ -41,20 +32,21 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmWhileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmWhileCommand; }
 
   /**
    * This overrides the default InvokeInitialPass implementation.
    * It records the arguments before expansion.
    */
-  virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
-                                 cmExecutionStatus&);
+  bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
+                         cmExecutionStatus&) CM_OVERRIDE;
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const&, cmExecutionStatus&)
+  bool InitialPass(std::vector<std::string> const&,
+                   cmExecutionStatus&) CM_OVERRIDE
   {
     return false;
   }
@@ -62,12 +54,12 @@ public:
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "while"; }
+  std::string GetName() const CM_OVERRIDE { return "while"; }
 
   cmTypeMacro(cmWhileCommand, cmCommand);
 };
diff --git a/Source/cmWriteFileCommand.cxx b/Source/cmWriteFileCommand.cxx
index 3966d38..0bdef0f 100644
--- a/Source/cmWriteFileCommand.cxx
+++ b/Source/cmWriteFileCommand.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmWriteFileCommand.h"
 
 #include <cmsys/FStream.hxx>
diff --git a/Source/cmWriteFileCommand.h b/Source/cmWriteFileCommand.h
index b0eef9c..dbadf84 100644
--- a/Source/cmWriteFileCommand.h
+++ b/Source/cmWriteFileCommand.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmWriteFileCommand_h
 #define cmWriteFileCommand_h
 
@@ -24,24 +15,24 @@ public:
   /**
    * This is a virtual constructor for the command.
    */
-  virtual cmCommand* Clone() { return new cmWriteFileCommand; }
+  cmCommand* Clone() CM_OVERRIDE { return new cmWriteFileCommand; }
 
   /**
    * This is called when the command is first encountered in
    * the CMakeLists.txt file.
    */
-  virtual bool InitialPass(std::vector<std::string> const& args,
-                           cmExecutionStatus& status);
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
 
   /**
    * This determines if the command is invoked when in script mode.
    */
-  virtual bool IsScriptable() const { return true; }
+  bool IsScriptable() const CM_OVERRIDE { return true; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
    */
-  virtual std::string GetName() const { return "write_file"; }
+  std::string GetName() const CM_OVERRIDE { return "write_file"; }
 
   cmTypeMacro(cmWriteFileCommand, cmCommand);
 };
diff --git a/Source/cmXCode21Object.cxx b/Source/cmXCode21Object.cxx
index 1abdf66..a783c70 100644
--- a/Source/cmXCode21Object.cxx
+++ b/Source/cmXCode21Object.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXCode21Object.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmXCode21Object.h b/Source/cmXCode21Object.h
index 9e51e0d..0db20e6 100644
--- a/Source/cmXCode21Object.h
+++ b/Source/cmXCode21Object.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmXCode21Object_h
 #define cmXCode21Object_h
 
diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx
index 3d31343..b1dc7ea 100644
--- a/Source/cmXCodeObject.cxx
+++ b/Source/cmXCodeObject.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXCodeObject.h"
 
 #include "cmSystemTools.h"
@@ -83,6 +74,22 @@ cmXCodeObject::cmXCodeObject(PBXType ptype, Type type)
   }
 }
 
+bool cmXCodeObject::IsEmpty() const
+{
+  switch (this->TypeValue) {
+    case OBJECT_LIST:
+      return this->List.empty();
+    case STRING:
+      return this->String.empty();
+    case ATTRIBUTE_GROUP:
+      return this->ObjectAttributes.empty();
+    case OBJECT_REF:
+    case OBJECT:
+      return this->Object == 0;
+  }
+  return true; // unreachable, but quiets warnings
+}
+
 void cmXCodeObject::Indent(int level, std::ostream& out)
 {
   while (level) {
diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h
index d2f7cb7..d495130 100644
--- a/Source/cmXCodeObject.h
+++ b/Source/cmXCodeObject.h
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmXCodeObject_h
 #define cmXCodeObject_h
 
+#include <cmConfigure.h>
+
 #include "cmStandardIncludes.h"
 
 class cmGeneratorTarget;
@@ -59,21 +52,30 @@ public:
   static const char* PBXTypeNames[];
   virtual ~cmXCodeObject();
   cmXCodeObject(PBXType ptype, Type type);
-  Type GetType() { return this->TypeValue; }
-  PBXType GetIsA() { return this->IsA; }
+  Type GetType() const { return this->TypeValue; }
+  PBXType GetIsA() const { return this->IsA; }
+
+  bool IsEmpty() const;
 
   void SetString(const std::string& s);
-  const std::string& GetString() { return this->String; }
+  const std::string& GetString() const { return this->String; }
 
   void AddAttribute(const std::string& name, cmXCodeObject* value)
   {
     this->ObjectAttributes[name] = value;
   }
 
+  void AddAttributeIfNotEmpty(const std::string& name, cmXCodeObject* value)
+  {
+    if (value && !value->IsEmpty()) {
+      AddAttribute(name, value);
+    }
+  }
+
   void SetObject(cmXCodeObject* value) { this->Object = value; }
   cmXCodeObject* GetObject() { return this->Object; }
   void AddObject(cmXCodeObject* value) { this->List.push_back(value); }
-  bool HasObject(cmXCodeObject* o)
+  bool HasObject(cmXCodeObject* o) const
   {
     return !(std::find(this->List.begin(), this->List.end(), o) ==
              this->List.end());
@@ -94,23 +96,25 @@ public:
   virtual void PrintComment(std::ostream&) {}
 
   static void PrintList(std::vector<cmXCodeObject*> const&, std::ostream& out);
-  const std::string& GetId() { return this->Id; }
+  const std::string& GetId() const { return this->Id; }
   void SetId(const std::string& id) { this->Id = id; }
-  cmGeneratorTarget* GetTarget() { return this->Target; }
+  cmGeneratorTarget* GetTarget() const { return this->Target; }
   void SetTarget(cmGeneratorTarget* t) { this->Target = t; }
-  const std::string& GetComment() { return this->Comment; }
-  bool HasComment() { return (!this->Comment.empty()); }
-  cmXCodeObject* GetObject(const char* name)
+  const std::string& GetComment() const { return this->Comment; }
+  bool HasComment() const { return (!this->Comment.empty()); }
+  cmXCodeObject* GetObject(const char* name) const
   {
-    if (this->ObjectAttributes.count(name)) {
-      return this->ObjectAttributes[name];
+    std::map<std::string, cmXCodeObject*>::const_iterator i =
+      this->ObjectAttributes.find(name);
+    if (i != this->ObjectAttributes.end()) {
+      return i->second;
     }
     return 0;
   }
   // search the attribute list for an object of the specified type
-  cmXCodeObject* GetObject(cmXCodeObject::PBXType t)
+  cmXCodeObject* GetObject(cmXCodeObject::PBXType t) const
   {
-    for (std::vector<cmXCodeObject*>::iterator i = this->List.begin();
+    for (std::vector<cmXCodeObject*>::const_iterator i = this->List.begin();
          i != this->List.end(); ++i) {
       cmXCodeObject* o = *i;
       if (o->IsA == t) {
@@ -126,7 +130,7 @@ public:
   {
     this->DependLibraries[configName].push_back(l);
   }
-  std::map<std::string, StringVec> const& GetDependLibraries()
+  std::map<std::string, StringVec> const& GetDependLibraries() const
   {
     return this->DependLibraries;
   }
@@ -134,11 +138,14 @@ public:
   {
     this->DependTargets[configName].push_back(tName);
   }
-  std::map<std::string, StringVec> const& GetDependTargets()
+  std::map<std::string, StringVec> const& GetDependTargets() const
   {
     return this->DependTargets;
   }
-  std::vector<cmXCodeObject*> const& GetObjectList() { return this->List; }
+  std::vector<cmXCodeObject*> const& GetObjectList() const
+  {
+    return this->List;
+  }
   void SetComment(const std::string& c) { this->Comment = c; }
   static void PrintString(std::ostream& os, std::string String);
 
diff --git a/Source/cmXMLParser.cxx b/Source/cmXMLParser.cxx
index 5e06d36..231e95e 100644
--- a/Source/cmXMLParser.cxx
+++ b/Source/cmXMLParser.cxx
@@ -1,27 +1,20 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXMLParser.h"
 
-#include <cmsys/FStream.hxx>
-
 #include <cm_expat.h>
+#include <cmsys/FStream.hxx>
 #include <ctype.h>
+#include <iostream>
+#include <sstream>
+#include <string.h>
 
 cmXMLParser::cmXMLParser()
 {
-  this->Parser = 0;
+  this->Parser = CM_NULLPTR;
   this->ParseError = 0;
-  this->ReportCallback = 0;
-  this->ReportCallbackData = 0;
+  this->ReportCallback = CM_NULLPTR;
+  this->ReportCallbackData = CM_NULLPTR;
 }
 
 cmXMLParser::~cmXMLParser()
@@ -62,7 +55,7 @@ int cmXMLParser::InitializeParser()
   }
 
   // Create the expat XML parser.
-  this->Parser = XML_ParserCreate(0);
+  this->Parser = XML_ParserCreate(CM_NULLPTR);
   XML_SetElementHandler(static_cast<XML_Parser>(this->Parser),
                         &cmXMLParserStartElement, &cmXMLParserEndElement);
   XML_SetCharacterDataHandler(static_cast<XML_Parser>(this->Parser),
@@ -106,7 +99,7 @@ int cmXMLParser::CleanupParser()
 
   // Clean up the parser.
   XML_ParserFree(static_cast<XML_Parser>(this->Parser));
-  this->Parser = 0;
+  this->Parser = CM_NULLPTR;
 
   return result;
 }
@@ -163,7 +156,7 @@ const char* cmXMLParser::FindAttribute(const char** atts,
       }
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 void cmXMLParserStartElement(void* parser, const char* name, const char** atts)
@@ -198,7 +191,7 @@ void cmXMLParser::ReportXmlParseError()
                     XML_ErrorString(XML_GetErrorCode(parser)));
 }
 
-void cmXMLParser::ReportError(int line, int, const char* msg)
+void cmXMLParser::ReportError(int line, int /*unused*/, const char* msg)
 {
   if (this->ReportCallback) {
     this->ReportCallback(line, msg, this->ReportCallbackData);
diff --git a/Source/cmXMLParser.h b/Source/cmXMLParser.h
index 6aae81d..60da51e 100644
--- a/Source/cmXMLParser.h
+++ b/Source/cmXMLParser.h
@@ -1,18 +1,11 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmXMLParser_h
 #define cmXMLParser_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
 
 extern "C" {
 void cmXMLParserStartElement(void*, const char*, const char**);
diff --git a/Source/cmXMLSafe.cxx b/Source/cmXMLSafe.cxx
index f899f57..d9bdc02 100644
--- a/Source/cmXMLSafe.cxx
+++ b/Source/cmXMLSafe.cxx
@@ -1,21 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXMLSafe.h"
 
 #include "cm_utf8.h"
 
-#include <iostream>
 #include <sstream>
-
 #include <stdio.h>
 #include <string.h>
 
diff --git a/Source/cmXMLSafe.h b/Source/cmXMLSafe.h
index 11ced13..c41554d 100644
--- a/Source/cmXMLSafe.h
+++ b/Source/cmXMLSafe.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmXMLSafe_h
 #define cmXMLSafe_h
 
-#include <cmsys/Configure.hxx>
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <iosfwd>
 #include <string>
diff --git a/Source/cmXMLWriter.cxx b/Source/cmXMLWriter.cxx
index 98c2680..2f50fe9 100644
--- a/Source/cmXMLWriter.cxx
+++ b/Source/cmXMLWriter.cxx
@@ -1,20 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Daniel Pfeifer <daniel at pfeifer-mail.de>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXMLWriter.h"
 
-#include "cmXMLSafe.h"
-
 #include <cassert>
-#include <fstream>
+#include <cmsys/FStream.hxx>
 
 cmXMLWriter::cmXMLWriter(std::ostream& output, std::size_t level)
   : Output(output)
@@ -107,7 +96,7 @@ void cmXMLWriter::ProcessingInstruction(const char* target, const char* data)
 void cmXMLWriter::FragmentFile(const char* fname)
 {
   this->CloseStartElement();
-  std::ifstream fin(fname, std::ios::in | std::ios::binary);
+  cmsys::ifstream fin(fname, std::ios::in | std::ios::binary);
   this->Output << fin.rdbuf();
 }
 
diff --git a/Source/cmXMLWriter.h b/Source/cmXMLWriter.h
index 8a88dd4..904f73b 100644
--- a/Source/cmXMLWriter.h
+++ b/Source/cmXMLWriter.h
@@ -1,18 +1,9 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2015 Daniel Pfeifer <daniel at pfeifer-mail.de>
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmXMLWiter_h
 #define cmXMLWiter_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmXMLSafe.h"
 
diff --git a/Source/cm_auto_ptr.hxx b/Source/cm_auto_ptr.hxx
new file mode 100644
index 0000000..5382018
--- /dev/null
+++ b/Source/cm_auto_ptr.hxx
@@ -0,0 +1,220 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef CM_AUTO_PTR_HXX
+#define CM_AUTO_PTR_HXX
+
+#include <cmConfigure.h>
+
+#ifdef CMake_HAVE_CXX_AUTO_PTR
+
+#include <memory>
+#define CM_AUTO_PTR std::auto_ptr
+
+#else
+
+#define CM_AUTO_PTR cm::auto_ptr
+
+// The HP compiler cannot handle the conversions necessary to use
+// auto_ptr_ref to pass an auto_ptr returned from one function
+// directly to another function as in use_auto_ptr(get_auto_ptr()).
+// We instead use const_cast to achieve the syntax on those platforms.
+// We do not use const_cast on other platforms to maintain the C++
+// standard design and guarantee that if an auto_ptr is bound
+// to a reference-to-const then ownership will be maintained.
+#if defined(__HP_aCC)
+#define cm_AUTO_PTR_REF 0
+#define cm_AUTO_PTR_CONST const
+#define cm_AUTO_PTR_CAST(a) cast(a)
+#else
+#define cm_AUTO_PTR_REF 1
+#define cm_AUTO_PTR_CONST
+#define cm_AUTO_PTR_CAST(a) a
+#endif
+
+// In C++11, clang will warn about using dynamic exception specifications
+// as they are deprecated.  But as this class is trying to faithfully
+// mimic std::auto_ptr, we want to keep the 'throw()' decorations below.
+// So we suppress the warning.
+#if defined(__clang__) && defined(__has_warning)
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated"
+#endif
+#endif
+
+namespace cm {
+
+template <class X>
+class auto_ptr;
+
+#if cm_AUTO_PTR_REF
+namespace detail {
+// The auto_ptr_ref template is supposed to be a private member of
+// auto_ptr but Borland 5.8 cannot handle it.  Instead put it in
+// a private namespace.
+template <class Y>
+struct auto_ptr_ref
+{
+  Y* p_;
+
+  // The extra constructor argument prevents implicit conversion to
+  // auto_ptr_ref from auto_ptr through the constructor.  Normally
+  // this should be done with the explicit keyword but Borland 5.x
+  // generates code in the conversion operator to call itself
+  // infinately.
+  auto_ptr_ref(Y* p, int)
+    : p_(p)
+  {
+  }
+};
+}
+#endif
+
+/** C++98 Standard Section 20.4.5 - Template class auto_ptr.  */
+template <class X>
+class auto_ptr
+{
+#if !cm_AUTO_PTR_REF
+  template <typename Y>
+  static inline auto_ptr<Y>& cast(auto_ptr<Y> const& a)
+  {
+    return const_cast<auto_ptr<Y>&>(a);
+  }
+#endif
+
+  /** The pointer to the object held.  */
+  X* x_;
+
+public:
+  /** The type of object held by the auto_ptr.  */
+  typedef X element_type;
+
+  /** Construct from an auto_ptr holding a compatible object.  This
+      transfers ownership to the newly constructed auto_ptr.  */
+  template <class Y>
+  auto_ptr(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw()
+    : x_(cm_AUTO_PTR_CAST(a).release())
+  {
+  }
+
+  /** Assign from an auto_ptr holding a compatible object.  This
+      transfers ownership to the left-hand-side of the assignment.  */
+  template <class Y>
+  auto_ptr& operator=(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw()
+  {
+    this->reset(cm_AUTO_PTR_CAST(a).release());
+    return *this;
+  }
+
+  /**
+   * Explicitly construct from a raw pointer.  This is typically
+   * called with the result of operator new.  For example:
+   *
+   *   auto_ptr<X> ptr(new X());
+   */
+  explicit auto_ptr(X* p = CM_NULLPTR) throw()
+    : x_(p)
+  {
+  }
+
+  /** Construct from another auto_ptr holding an object of the same
+      type.  This transfers ownership to the newly constructed
+      auto_ptr.  */
+  auto_ptr(auto_ptr cm_AUTO_PTR_CONST& a) throw()
+    : x_(cm_AUTO_PTR_CAST(a).release())
+  {
+  }
+
+  /** Assign from another auto_ptr holding an object of the same type.
+      This transfers ownership to the newly constructed auto_ptr.  */
+  auto_ptr& operator=(auto_ptr cm_AUTO_PTR_CONST& a) throw()
+  {
+    this->reset(cm_AUTO_PTR_CAST(a).release());
+    return *this;
+  }
+
+  /** Destruct and delete the object held.  */
+  ~auto_ptr() throw()
+  {
+    // Assume object destructor is nothrow.
+    delete this->x_;
+  }
+
+  /** Dereference and return a reference to the object held.  */
+  X& operator*() const throw() { return *this->x_; }
+
+  /** Return a pointer to the object held.  */
+  X* operator->() const throw() { return this->x_; }
+
+  /** Return a pointer to the object held.  */
+  X* get() const throw() { return this->x_; }
+
+  /** Return a pointer to the object held and reset to hold no object.
+      This transfers ownership to the caller.  */
+  X* release() throw()
+  {
+    X* x = this->x_;
+    this->x_ = CM_NULLPTR;
+    return x;
+  }
+
+  /** Assume ownership of the given object.  The object previously
+      held is deleted.  */
+  void reset(X* p = 0) throw()
+  {
+    if (this->x_ != p) {
+      // Assume object destructor is nothrow.
+      delete this->x_;
+      this->x_ = p;
+    }
+  }
+
+  /** Convert to an auto_ptr holding an object of a compatible type.
+      This transfers ownership to the returned auto_ptr.  */
+  template <class Y>
+  operator auto_ptr<Y>() throw()
+  {
+    return auto_ptr<Y>(this->release());
+  }
+
+#if cm_AUTO_PTR_REF
+  /** Construct from an auto_ptr_ref.  This is used when the
+      constructor argument is a call to a function returning an
+      auto_ptr.  */
+  auto_ptr(detail::auto_ptr_ref<X> r) throw()
+    : x_(r.p_)
+  {
+  }
+
+  /** Assign from an auto_ptr_ref.  This is used when a function
+      returning an auto_ptr is passed on the right-hand-side of an
+      assignment.  */
+  auto_ptr& operator=(detail::auto_ptr_ref<X> r) throw()
+  {
+    this->reset(r.p_);
+    return *this;
+  }
+
+  /** Convert to an auto_ptr_ref.  This is used when a function
+      returning an auto_ptr is the argument to the constructor of
+      another auto_ptr.  */
+  template <class Y>
+  operator detail::auto_ptr_ref<Y>() throw()
+  {
+    return detail::auto_ptr_ref<Y>(this->release(), 1);
+  }
+#endif
+};
+
+} // namespace cm
+
+// Undo warning suppression.
+#if defined(__clang__) && defined(__has_warning)
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic pop
+#endif
+#endif
+
+#endif
+
+#endif
diff --git a/Source/cm_get_date.c b/Source/cm_get_date.c
index 2e0d4bd..4bef803 100644
--- a/Source/cm_get_date.c
+++ b/Source/cm_get_date.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cm_get_date.h"
 
 #define __archive_get_date cm_get_date
diff --git a/Source/cm_get_date.h b/Source/cm_get_date.h
index 3045775..6acf8de 100644
--- a/Source/cm_get_date.h
+++ b/Source/cm_get_date.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc.
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_get_date_h
 #define cm_get_date_h
 
diff --git a/Source/cm_sha2_mangle.h b/Source/cm_sha2_mangle.h
index e73d131..3dce819 100644
--- a/Source/cm_sha2_mangle.h
+++ b/Source/cm_sha2_mangle.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_sha2_mangle_h
 #define cm_sha2_mangle_h
 
diff --git a/Source/cm_utf8.c b/Source/cm_utf8.c
index 2352507..6c49b52 100644
--- a/Source/cm_utf8.c
+++ b/Source/cm_utf8.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cm_utf8.h"
 
 /*
diff --git a/Source/cm_utf8.h b/Source/cm_utf8.h
index 06e2868..fcb43e0 100644
--- a/Source/cm_utf8.h
+++ b/Source/cm_utf8.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_utf8_h
 #define cm_utf8_h
 
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index 89ea955..c8cf465 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -1,37 +1,34 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmake.h"
 
 #include "cmAlgorithms.h"
-#include "cmCommand.h"
 #include "cmCommands.h"
+#include "cmDocumentation.h"
+#include "cmDocumentationEntry.h"
 #include "cmDocumentationFormatter.h"
 #include "cmExternalMakefileProjectGenerator.h"
 #include "cmFileTimeComparison.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmGlobalGeneratorFactory.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
+#include "cmMessenger.h"
 #include "cmState.h"
-#include "cmTest.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetLinkLibraryType.h"
+#include "cmUtils.hxx"
+#include "cmVersionConfig.h"
+#include "cm_auto_ptr.hxx"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmGraphVizWriter.h"
 #include "cmVariableWatch.h"
-#include <cmsys/SystemInformation.hxx>
-#endif
 
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
+#include <cm_jsoncpp_writer.h>
+#endif
 
 // only build kdevelop generator on non-windows platforms
 // when not bootstrapping cmake
@@ -60,9 +57,11 @@
 #include "cmGlobalVisualStudio11Generator.h"
 #include "cmGlobalVisualStudio12Generator.h"
 #include "cmGlobalVisualStudio14Generator.h"
+#include "cmGlobalVisualStudio15Generator.h"
 #include "cmGlobalVisualStudio71Generator.h"
 #include "cmGlobalVisualStudio8Generator.h"
 #include "cmGlobalVisualStudio9Generator.h"
+
 #define CMAKE_HAVE_VS_GENERATORS
 #endif
 #include "cmGlobalMSYSMakefileGenerator.h"
@@ -92,11 +91,10 @@
 #include "cmExtraEclipseCDT4Generator.h"
 #endif
 
-#include <stdlib.h> // required for atoi
-
 #if defined(__APPLE__)
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmGlobalXCodeGenerator.h"
+
 #define CMAKE_USE_XCODE 1
 #endif
 #include <sys/resource.h>
@@ -107,13 +105,37 @@
 // include sys/stat.h after sys/types.h
 #include <sys/stat.h> // struct stat
 
-#include <list>
+#include <algorithm>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <iostream>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
+class cmCommand;
+
+namespace {
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#ifdef CMake_HAVE_CXX_UNORDERED_MAP
+typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
+#else
+typedef cmsys::hash_map<std::string, Json::Value> JsonValueMapType;
+#endif
+#endif
+
+} // namespace
 
 static bool cmakeCheckStampFile(const char* stampName);
 static bool cmakeCheckStampList(const char* stampName);
 
-void cmWarnUnusedCliWarning(const std::string& variable, int, void* ctx,
-                            const char*, const cmMakefile*)
+void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
+                            void* ctx, const char* /*unused*/,
+                            const cmMakefile* /*unused*/)
 {
   cmake* cm = reinterpret_cast<cmake*>(ctx);
   cm->MarkCliAsUsed(variable);
@@ -134,6 +156,7 @@ cmake::cmake()
 
   this->State = new cmState;
   this->CurrentSnapshot = this->State->CreateBaseSnapshot();
+  this->Messenger = new cmMessenger(this->State);
 
 #ifdef __APPLE__
   struct rlimit rlp;
@@ -145,10 +168,9 @@ cmake::cmake()
   }
 #endif
 
-  this->Verbose = false;
-  this->GlobalGenerator = 0;
-  this->ProgressCallback = 0;
-  this->ProgressCallbackClientData = 0;
+  this->GlobalGenerator = CM_NULLPTR;
+  this->ProgressCallback = CM_NULLPTR;
+  this->ProgressCallbackClientData = CM_NULLPTR;
   this->CurrentWorkingMode = NORMAL_MODE;
 
 #ifdef CMAKE_BUILD_WITH_CMAKE
@@ -190,9 +212,10 @@ cmake::cmake()
 cmake::~cmake()
 {
   delete this->State;
+  delete this->Messenger;
   if (this->GlobalGenerator) {
     delete this->GlobalGenerator;
-    this->GlobalGenerator = 0;
+    this->GlobalGenerator = CM_NULLPTR;
   }
   cmDeleteAll(this->Generators);
 #ifdef CMAKE_BUILD_WITH_CMAKE
@@ -201,6 +224,71 @@ cmake::~cmake()
   delete this->FileComparison;
 }
 
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
+{
+  Json::Value obj = Json::objectValue;
+  // Version information:
+  Json::Value version = Json::objectValue;
+  version["string"] = CMake_VERSION;
+  version["major"] = CMake_VERSION_MAJOR;
+  version["minor"] = CMake_VERSION_MINOR;
+  version["suffix"] = CMake_VERSION_SUFFIX;
+  version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
+  version["patch"] = CMake_VERSION_PATCH;
+
+  obj["version"] = version;
+
+  // Generators:
+  std::vector<cmake::GeneratorInfo> generatorInfoList;
+  this->GetRegisteredGenerators(generatorInfoList);
+
+  JsonValueMapType generatorMap;
+  for (std::vector<cmake::GeneratorInfo>::const_iterator i =
+         generatorInfoList.begin();
+       i != generatorInfoList.end(); ++i) {
+    if (i->isAlias) { // skip aliases, they are there for compatibility reasons
+                      // only
+      continue;
+    }
+
+    if (i->extraName.empty()) {
+      Json::Value gen = Json::objectValue;
+      gen["name"] = i->name;
+      gen["toolsetSupport"] = i->supportsToolset;
+      gen["platformSupport"] = i->supportsPlatform;
+      gen["extraGenerators"] = Json::arrayValue;
+      generatorMap[i->name] = gen;
+    } else {
+      Json::Value& gen = generatorMap[i->baseName];
+      gen["extraGenerators"].append(i->extraName);
+    }
+  }
+
+  Json::Value generators = Json::arrayValue;
+  for (JsonValueMapType::const_iterator i = generatorMap.begin();
+       i != generatorMap.end(); ++i) {
+    generators.append(i->second);
+  }
+  obj["generators"] = generators;
+  obj["serverMode"] = haveServerMode;
+
+  return obj;
+}
+#endif
+
+std::string cmake::ReportCapabilities(bool haveServerMode) const
+{
+  std::string result;
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  Json::FastWriter writer;
+  result = writer.write(this->ReportCapabilitiesJson(haveServerMode));
+#else
+  result = "Not supported";
+#endif
+  return result;
+}
+
 void cmake::CleanupCommandsAndMacros()
 {
   this->CurrentSnapshot = this->State->Reset();
@@ -398,7 +486,7 @@ void cmake::ReadListFile(const std::vector<std::string>& args,
     snapshot.GetDirectory().SetCurrentSource(
       cmSystemTools::GetCurrentWorkingDirectory());
     snapshot.SetDefaultDefinitions();
-    cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(gg, snapshot));
+    CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(gg, snapshot));
     if (this->GetWorkingMode() != NORMAL_MODE) {
       std::string file(cmSystemTools::CollapseFullPath(path));
       cmSystemTools::ConvertToUnixSlashes(file);
@@ -464,7 +552,8 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
 
     gg->CreateGenerationObjects();
     cmLocalGenerator* lg = gg->LocalGenerators[0];
-    std::string includeFlags = lg->GetIncludeFlags(includeDirs, 0, language);
+    std::string includeFlags =
+      lg->GetIncludeFlags(includeDirs, CM_NULLPTR, language);
 
     std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
     printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
@@ -482,6 +571,9 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
       mf->AddLinkLibraryForTarget(targetName, *libIt, GENERAL_LibraryType);
     }
 
+    std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
+    buildType = cmSystemTools::UpperCase(buildType);
+
     std::string linkLibs;
     std::string frameworkPath;
     std::string linkPath;
@@ -490,8 +582,8 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
     gg->CreateGenerationObjects();
     cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
     cmLocalGenerator* lg = gtgt->GetLocalGenerator();
-    lg->GetTargetFlags(linkLibs, frameworkPath, linkPath, flags, linkFlags,
-                       gtgt, false);
+    lg->GetTargetFlags(buildType, linkLibs, flags, linkFlags, frameworkPath,
+                       linkPath, gtgt, false);
     linkLibs = frameworkPath + linkPath + linkLibs;
 
     printf("%s\n", linkLibs.c_str());
@@ -555,9 +647,7 @@ void cmake::SetArgs(const std::vector<std::string>& args,
       this->VSSolutionFile = args[++i];
     }
 #endif
-    else if (arg.find("-V", 0) == 0) {
-      this->Verbose = true;
-    } else if (arg.find("-D", 0) == 0) {
+    else if (arg.find("-D", 0) == 0) {
       // skip for now
     } else if (arg.find("-U", 0) == 0) {
       // skip for now
@@ -589,6 +679,11 @@ void cmake::SetArgs(const std::vector<std::string>& args,
       std::cout << "Running with expanded trace output on.\n";
       this->SetTrace(true);
       this->SetTraceExpand(true);
+    } else if (arg.find("--trace-source=", 0) == 0) {
+      std::string file = arg.substr(strlen("--trace-source="));
+      cmSystemTools::ConvertToUnixSlashes(file);
+      this->AddTraceSource(file);
+      this->SetTrace(true);
     } else if (arg.find("--trace", 0) == 0) {
       std::cout << "Running with trace output on.\n";
       this->SetTrace(true);
@@ -786,57 +881,26 @@ int cmake::AddCMakePaths()
   return 1;
 }
 
-void cmake::AddExtraGenerator(const std::string& name,
-                              CreateExtraGeneratorFunctionType newFunction)
-{
-  cmExternalMakefileProjectGenerator* extraGenerator = newFunction();
-  const std::vector<std::string>& supportedGlobalGenerators =
-    extraGenerator->GetSupportedGlobalGenerators();
-
-  for (std::vector<std::string>::const_iterator it =
-         supportedGlobalGenerators.begin();
-       it != supportedGlobalGenerators.end(); ++it) {
-    std::string fullName =
-      cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*it, name);
-    this->ExtraGenerators[fullName] = newFunction;
-  }
-  delete extraGenerator;
-}
-
 void cmake::AddDefaultExtraGenerators()
 {
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#if defined(_WIN32) && !defined(__CYGWIN__)
-// e.g. kdevelop4 ?
-#endif
-
-  this->AddExtraGenerator(cmExtraCodeBlocksGenerator::GetActualName(),
-                          &cmExtraCodeBlocksGenerator::New);
-  this->AddExtraGenerator(cmExtraCodeLiteGenerator::GetActualName(),
-                          &cmExtraCodeLiteGenerator::New);
-  this->AddExtraGenerator(cmExtraSublimeTextGenerator::GetActualName(),
-                          &cmExtraSublimeTextGenerator::New);
-  this->AddExtraGenerator(cmExtraKateGenerator::GetActualName(),
-                          &cmExtraKateGenerator::New);
+  this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
+  this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
+  this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
+  this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
 
 #ifdef CMAKE_USE_ECLIPSE
-  this->AddExtraGenerator(cmExtraEclipseCDT4Generator::GetActualName(),
-                          &cmExtraEclipseCDT4Generator::New);
+  this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
 #endif
 
 #ifdef CMAKE_USE_KDEVELOP
-  this->AddExtraGenerator(cmGlobalKdevelopGenerator::GetActualName(),
-                          &cmGlobalKdevelopGenerator::New);
-  // for kdevelop also add the generator with just the name of the
-  // extra generator, since it was this way since cmake 2.2
-  this->ExtraGenerators[cmGlobalKdevelopGenerator::GetActualName()] =
-    &cmGlobalKdevelopGenerator::New;
+  this->ExtraGenerators.push_back(cmGlobalKdevelopGenerator::GetFactory());
 #endif
-
 #endif
 }
 
-void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators)
+void cmake::GetRegisteredGenerators(
+  std::vector<GeneratorInfo>& generators) const
 {
   for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(),
                                                   e = this->Generators.end();
@@ -847,34 +911,85 @@ void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators)
     for (size_t j = 0; j < names.size(); ++j) {
       GeneratorInfo info;
       info.supportsToolset = (*i)->SupportsToolset();
+      info.supportsPlatform = (*i)->SupportsPlatform();
       info.name = names[j];
+      info.baseName = names[j];
+      info.isAlias = false;
       generators.push_back(info);
     }
   }
 
-  for (RegisteredExtraGeneratorsMap::const_iterator
+  for (RegisteredExtraGeneratorsVector::const_iterator
          i = this->ExtraGenerators.begin(),
          e = this->ExtraGenerators.end();
        i != e; ++i) {
-    GeneratorInfo info;
-    info.name = i->first;
-    info.supportsToolset = false;
-    generators.push_back(info);
+    const std::vector<std::string> genList =
+      (*i)->GetSupportedGlobalGenerators();
+    for (std::vector<std::string>::const_iterator gen = genList.begin();
+         gen != genList.end(); ++gen) {
+      GeneratorInfo info;
+      info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
+        *gen, (*i)->GetName());
+      info.baseName = *gen;
+      info.extraName = (*i)->GetName();
+      info.supportsPlatform = false;
+      info.supportsToolset = false;
+      info.isAlias = false;
+      generators.push_back(info);
+    }
+    for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
+         a != (*i)->Aliases.end(); ++a) {
+      GeneratorInfo info;
+      info.name = *a;
+      if (!genList.empty()) {
+        info.baseName = genList.at(0);
+      }
+      info.extraName = (*i)->GetName();
+      info.supportsPlatform = false;
+      info.supportsToolset = false;
+      info.isAlias = true;
+      generators.push_back(info);
+    }
   }
 }
 
-cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
+static std::pair<cmExternalMakefileProjectGenerator*, std::string>
+createExtraGenerator(
+  const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
+  const std::string& name)
 {
-  cmExternalMakefileProjectGenerator* extraGenerator = 0;
-  std::string name = gname;
-  RegisteredExtraGeneratorsMap::const_iterator extraGenIt =
-    this->ExtraGenerators.find(name);
-  if (extraGenIt != this->ExtraGenerators.end()) {
-    extraGenerator = (extraGenIt->second)();
-    name = extraGenerator->GetGlobalGeneratorName(name);
+  for (std::vector<cmExternalMakefileProjectGeneratorFactory*>::const_iterator
+         i = in.begin();
+       i != in.end(); ++i) {
+    const std::vector<std::string> generators =
+      (*i)->GetSupportedGlobalGenerators();
+    if ((*i)->GetName() == name) { // Match aliases
+      return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
+                            generators.at(0));
+    }
+    for (std::vector<std::string>::const_iterator g = generators.begin();
+         g != generators.end(); ++g) {
+      const std::string fullName =
+        cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
+          *g, (*i)->GetName());
+      if (fullName == name) {
+        return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
+                              *g);
+      }
+    }
   }
+  return std::make_pair(
+    static_cast<cmExternalMakefileProjectGenerator*>(CM_NULLPTR), name);
+}
 
-  cmGlobalGenerator* generator = 0;
+cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
+{
+  std::pair<cmExternalMakefileProjectGenerator*, std::string> extra =
+    createExtraGenerator(this->ExtraGenerators, gname);
+  cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
+  const std::string name = extra.second;
+
+  cmGlobalGenerator* generator = CM_NULLPTR;
   for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
        i != this->Generators.end(); ++i) {
     generator = (*i)->CreateGlobalGenerator(name, this);
@@ -918,6 +1033,28 @@ const char* cmake::GetHomeOutputDirectory() const
   return this->State->GetBinaryDirectory();
 }
 
+std::string cmake::FindCacheFile(const std::string& binaryDir)
+{
+  std::string cachePath = binaryDir;
+  cmSystemTools::ConvertToUnixSlashes(cachePath);
+  std::string cacheFile = cachePath;
+  cacheFile += "/CMakeCache.txt";
+  if (!cmSystemTools::FileExists(cacheFile.c_str())) {
+    // search in parent directories for cache
+    std::string cmakeFiles = cachePath;
+    cmakeFiles += "/CMakeFiles";
+    if (cmSystemTools::FileExists(cmakeFiles.c_str())) {
+      std::string cachePathFound =
+        cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
+                                                     cachePath.c_str(), "/");
+      if (!cachePathFound.empty()) {
+        cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
+      }
+    }
+  }
+  return cachePath;
+}
+
 void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
 {
   if (!gg) {
@@ -949,16 +1086,10 @@ void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
   cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
 
   // Save the environment variables CXX and CC
-  const char* cxx = getenv("CXX");
-  const char* cc = getenv("CC");
-  if (cxx) {
-    this->CXXEnvironment = cxx;
-  } else {
+  if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
     this->CXXEnvironment = "";
   }
-  if (cc) {
-    this->CCEnvironment = cc;
-  } else {
+  if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
     this->CCEnvironment = "";
   }
 }
@@ -1203,6 +1334,7 @@ int cmake::ActualConfigure()
         { "11.0", "Visual Studio 11 2012" },
         { "12.0", "Visual Studio 12 2013" },
         { "14.0", "Visual Studio 14 2015" },
+        { "15.0", "Visual Studio 15" },
         { 0, 0 }
       };
       for (int i = 0; version[i].MSVersion != 0; i++) {
@@ -1413,9 +1545,8 @@ int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
   if (this->GetWorkingMode() != NORMAL_MODE) {
     if (cmSystemTools::GetErrorOccuredFlag()) {
       return -1;
-    } else {
-      return 0;
     }
+    return 0;
   }
 
   // If MAKEFLAGS are given in the environment, remove the environment
@@ -1423,7 +1554,7 @@ int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
   // should fail (if "-i" is an option).  We cannot simply test
   // whether "-i" is given and remove it because some make programs
   // encode the MAKEFLAGS variable in a strange way.
-  if (getenv("MAKEFLAGS")) {
+  if (cmSystemTools::HasEnv("MAKEFLAGS")) {
     cmSystemTools::PutEnv("MAKEFLAGS=");
   }
 
@@ -1521,6 +1652,7 @@ void cmake::AddDefaultGenerators()
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #if !defined(CMAKE_BOOT_MINGW)
+  this->Generators.push_back(cmGlobalVisualStudio15Generator::NewFactory());
   this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
   this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
   this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
@@ -1648,15 +1780,32 @@ void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
     (*i)->GetDocumentation(e);
     v.push_back(e);
   }
-  for (RegisteredExtraGeneratorsMap::const_iterator i =
+  for (RegisteredExtraGeneratorsVector::const_iterator i =
          this->ExtraGenerators.begin();
        i != this->ExtraGenerators.end(); ++i) {
-    cmDocumentationEntry e;
-    cmExternalMakefileProjectGenerator* generator = (i->second)();
-    generator->GetDocumentation(e, i->first);
-    e.Name = i->first;
-    delete generator;
-    v.push_back(e);
+    const std::string doc = (*i)->GetDocumentation();
+    const std::string name = (*i)->GetName();
+
+    // Aliases:
+    for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
+         a != (*i)->Aliases.end(); ++a) {
+      cmDocumentationEntry e;
+      e.Name = *a;
+      e.Brief = doc;
+      v.push_back(e);
+    }
+
+    // Full names:
+    const std::vector<std::string> generators =
+      (*i)->GetSupportedGlobalGenerators();
+    for (std::vector<std::string>::const_iterator g = generators.begin();
+         g != generators.end(); ++g) {
+      cmDocumentationEntry e;
+      e.Name =
+        cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name);
+      e.Brief = doc;
+      v.push_back(e);
+    }
   }
 }
 
@@ -1698,12 +1847,8 @@ void cmake::UpdateConversionPathTable()
 
 int cmake::CheckBuildSystem()
 {
-  // We do not need to rerun CMake.  Check dependency integrity.  Use
-  // the make system's VERBOSE environment variable to enable verbose
-  // output. This can be skipped by setting CMAKE_NO_VERBOSE (which is set
-  // by the Eclipse and KDevelop generators).
-  bool verbose = ((cmSystemTools::GetEnv("VERBOSE") != 0) &&
-                  (cmSystemTools::GetEnv("CMAKE_NO_VERBOSE") == 0));
+  // We do not need to rerun CMake.  Check dependency integrity.
+  const bool verbose = isCMakeVerbose();
 
   // This method will check the integrity of the build system if the
   // option was given on the command line.  It reads the given file to
@@ -1737,7 +1882,7 @@ int cmake::CheckBuildSystem()
   cm.SetHomeOutputDirectory("");
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator gg(&cm);
-  cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+  CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
   if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
       cmSystemTools::GetErrorOccuredFlag()) {
     if (verbose) {
@@ -1758,14 +1903,12 @@ int cmake::CheckBuildSystem()
     }
 
     // Create the generator and use it to clear the dependencies.
-    cmsys::auto_ptr<cmGlobalGenerator> ggd(
-      this->CreateGlobalGenerator(genName));
+    CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName));
     if (ggd.get()) {
       cm.GetCurrentSnapshot().SetDefaultDefinitions();
-      cmsys::auto_ptr<cmMakefile> mfd(
+      CM_AUTO_PTR<cmMakefile> mfd(
         new cmMakefile(ggd.get(), cm.GetCurrentSnapshot()));
-      cmsys::auto_ptr<cmLocalGenerator> lgd(
-        ggd->CreateLocalGenerator(mfd.get()));
+      CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get()));
       lgd->ClearDependencies(mfd.get(), verbose);
     }
   }
@@ -1905,7 +2048,7 @@ void cmake::MarkCliAsUsed(const std::string& variable)
 void cmake::GenerateGraphViz(const char* fileName) const
 {
 #ifdef CMAKE_BUILD_WITH_CMAKE
-  cmsys::auto_ptr<cmGraphVizWriter> gvWriter(
+  CM_AUTO_PTR<cmGraphVizWriter> gvWriter(
     new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators()));
 
   std::string settingsFile = this->GetHomeOutputDirectory();
@@ -1952,11 +2095,10 @@ cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
   if (i != this->InstalledFiles.end()) {
     cmInstalledFile& file = i->second;
     return &file;
-  } else {
-    cmInstalledFile& file = this->InstalledFiles[name];
-    file.SetName(mf, name);
-    return &file;
   }
+  cmInstalledFile& file = this->InstalledFiles[name];
+  file.SetName(mf, name);
+  return &file;
 }
 
 cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
@@ -1967,9 +2109,8 @@ cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
   if (i != this->InstalledFiles.end()) {
     cmInstalledFile const& file = i->second;
     return &file;
-  } else {
-    return 0;
   }
+  return CM_NULLPTR;
 }
 
 int cmake::GetSystemInformation(std::vector<std::string>& args)
@@ -1989,9 +2130,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args)
   bool writeToStdout = true;
   for (unsigned int i = 1; i < args.size(); ++i) {
     std::string arg = args[i];
-    if (arg.find("-V", 0) == 0) {
-      this->Verbose = true;
-    } else if (arg.find("-G", 0) == 0) {
+    if (arg.find("-G", 0) == 0) {
       std::string value = arg.substr(2);
       if (value.empty()) {
         ++i;
@@ -2096,7 +2235,7 @@ static bool cmakeCheckStampFile(const char* stampName)
 #if defined(_WIN32) || defined(__CYGWIN__)
   cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
 #else
-  cmsys::ifstream fin(stampDepends.c_str(), std::ios::in);
+  cmsys::ifstream fin(stampDepends.c_str());
 #endif
   if (!fin) {
     // The stamp dependencies file cannot be read.  Just assume the
@@ -2144,11 +2283,10 @@ static bool cmakeCheckStampFile(const char* stampName)
     std::cout << "CMake does not need to re-run because " << stampName
               << " is up-to-date.\n";
     return true;
-  } else {
-    cmSystemTools::RemoveFile(stampTemp);
-    cmSystemTools::Error("Cannot restore timestamp ", stampName);
-    return false;
   }
+  cmSystemTools::RemoveFile(stampTemp);
+  cmSystemTools::Error("Cannot restore timestamp ", stampName);
+  return false;
 }
 
 static bool cmakeCheckStampList(const char* stampList)
@@ -2176,155 +2314,10 @@ static bool cmakeCheckStampList(const char* stampList)
   return true;
 }
 
-cmake::MessageType cmake::ConvertMessageType(cmake::MessageType t)
-{
-  bool warningsAsErrors;
-
-  if (t == cmake::AUTHOR_WARNING || t == cmake::AUTHOR_ERROR) {
-    warningsAsErrors = this->GetDevWarningsAsErrors();
-    if (warningsAsErrors && t == cmake::AUTHOR_WARNING) {
-      t = cmake::AUTHOR_ERROR;
-    } else if (!warningsAsErrors && t == cmake::AUTHOR_ERROR) {
-      t = cmake::AUTHOR_WARNING;
-    }
-  } else if (t == cmake::DEPRECATION_WARNING ||
-             t == cmake::DEPRECATION_ERROR) {
-    warningsAsErrors = this->GetDeprecatedWarningsAsErrors();
-    if (warningsAsErrors && t == cmake::DEPRECATION_WARNING) {
-      t = cmake::DEPRECATION_ERROR;
-    } else if (!warningsAsErrors && t == cmake::DEPRECATION_ERROR) {
-      t = cmake::DEPRECATION_WARNING;
-    }
-  }
-
-  return t;
-}
-
-bool cmake::IsMessageTypeVisible(cmake::MessageType t)
-{
-  bool isVisible = true;
-
-  if (t == cmake::DEPRECATION_ERROR) {
-    if (!this->GetDeprecatedWarningsAsErrors()) {
-      isVisible = false;
-    }
-  } else if (t == cmake::DEPRECATION_WARNING) {
-    if (this->GetSuppressDeprecatedWarnings()) {
-      isVisible = false;
-    }
-  } else if (t == cmake::AUTHOR_ERROR) {
-    if (!this->GetDevWarningsAsErrors()) {
-      isVisible = false;
-    }
-  } else if (t == cmake::AUTHOR_WARNING) {
-    if (this->GetSuppressDevWarnings()) {
-      isVisible = false;
-    }
-  }
-
-  return isVisible;
-}
-
-bool cmake::PrintMessagePreamble(cmake::MessageType t, std::ostream& msg)
-{
-  // Construct the message header.
-  if (t == cmake::FATAL_ERROR) {
-    msg << "CMake Error";
-  } else if (t == cmake::INTERNAL_ERROR) {
-    msg << "CMake Internal Error (please report a bug)";
-  } else if (t == cmake::LOG) {
-    msg << "CMake Debug Log";
-  } else if (t == cmake::DEPRECATION_ERROR) {
-    msg << "CMake Deprecation Error";
-  } else if (t == cmake::DEPRECATION_WARNING) {
-    msg << "CMake Deprecation Warning";
-  } else if (t == cmake::AUTHOR_WARNING) {
-    msg << "CMake Warning (dev)";
-  } else if (t == cmake::AUTHOR_ERROR) {
-    msg << "CMake Error (dev)";
-  } else {
-    msg << "CMake Warning";
-  }
-  return true;
-}
-
-void printMessageText(std::ostream& msg, std::string const& text)
-{
-  msg << ":\n";
-  cmDocumentationFormatter formatter;
-  formatter.SetIndent("  ");
-  formatter.PrintFormatted(msg, text.c_str());
-}
-
-void displayMessage(cmake::MessageType t, std::ostringstream& msg)
-{
-
-  // Add a note about warning suppression.
-  if (t == cmake::AUTHOR_WARNING) {
-    msg << "This warning is for project developers.  Use -Wno-dev to suppress "
-           "it.";
-  } else if (t == cmake::AUTHOR_ERROR) {
-    msg << "This error is for project developers. Use -Wno-error=dev to "
-           "suppress "
-           "it.";
-  }
-
-  // Add a terminating blank line.
-  msg << "\n";
-
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-  // Add a C++ stack trace to internal errors.
-  if (t == cmake::INTERNAL_ERROR) {
-    std::string stack = cmsys::SystemInformation::GetProgramStack(0, 0);
-    if (!stack.empty()) {
-      if (cmHasLiteralPrefix(stack, "WARNING:")) {
-        stack = "Note:" + stack.substr(8);
-      }
-      msg << stack << "\n";
-    }
-  }
-#endif
-
-  // Output the message.
-  if (t == cmake::FATAL_ERROR || t == cmake::INTERNAL_ERROR ||
-      t == cmake::DEPRECATION_ERROR || t == cmake::AUTHOR_ERROR) {
-    cmSystemTools::SetErrorOccured();
-    cmSystemTools::Message(msg.str().c_str(), "Error");
-  } else {
-    cmSystemTools::Message(msg.str().c_str(), "Warning");
-  }
-}
-
 void cmake::IssueMessage(cmake::MessageType t, std::string const& text,
-                         cmListFileBacktrace const& backtrace, bool force)
+                         cmListFileBacktrace const& backtrace) const
 {
-  if (!force) {
-    // override the message type, if needed, for warnings and errors
-    cmake::MessageType override = this->ConvertMessageType(t);
-    if (override != t) {
-      t = override;
-      force = true;
-    }
-  }
-
-  if (!force && !this->IsMessageTypeVisible(t)) {
-    return;
-  }
-
-  std::ostringstream msg;
-  if (!this->PrintMessagePreamble(t, msg)) {
-    return;
-  }
-
-  // Add the immediate context.
-  backtrace.PrintTitle(msg);
-
-  printMessageText(msg, text);
-
-  // Add the rest of the context.
-  backtrace.PrintCallStack(msg);
-
-  displayMessage(t, msg);
+  this->Messenger->IssueMessage(t, text, backtrace);
 }
 
 std::vector<std::string> cmake::GetDebugConfigs()
@@ -2344,6 +2337,11 @@ std::vector<std::string> cmake::GetDebugConfigs()
   return configs;
 }
 
+cmMessenger* cmake::GetMessenger() const
+{
+  return this->Messenger;
+}
+
 int cmake::Build(const std::string& dir, const std::string& target,
                  const std::string& config,
                  const std::vector<std::string>& nativeOptions, bool clean)
@@ -2355,24 +2353,8 @@ int cmake::Build(const std::string& dir, const std::string& target,
     std::cerr << "Error: " << dir << " is not a directory\n";
     return 1;
   }
-  std::string cachePath = dir;
-  cmSystemTools::ConvertToUnixSlashes(cachePath);
-  std::string cacheFile = cachePath;
-  cacheFile += "/CMakeCache.txt";
-  if (!cmSystemTools::FileExists(cacheFile.c_str())) {
-    // search in parent directories for cache
-    std::string cmakeFiles = cachePath;
-    cmakeFiles += "/CMakeFiles";
-    if (cmSystemTools::FileExists(cmakeFiles.c_str())) {
-      std::string cachePathFound =
-        cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
-                                                     cachePath.c_str(), "/");
-      if (!cachePathFound.empty()) {
-        cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
-      }
-    }
-  }
 
+  std::string cachePath = FindCacheFile(dir);
   if (!this->LoadCache(cachePath)) {
     std::cerr << "Error: could not load cache\n";
     return 1;
@@ -2383,7 +2365,7 @@ int cmake::Build(const std::string& dir, const std::string& target,
     std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
     return 1;
   }
-  cmsys::auto_ptr<cmGlobalGenerator> gen(
+  CM_AUTO_PTR<cmGlobalGenerator> gen(
     this->CreateGlobalGenerator(cachedGenerator));
   if (!gen.get()) {
     std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
@@ -2448,19 +2430,9 @@ void cmake::RunCheckForUnusedVariables()
 #endif
 }
 
-bool cmake::GetSuppressDevWarnings(cmMakefile const* mf)
+bool cmake::GetSuppressDevWarnings() const
 {
-  /*
-   * The suppression CMake variable may be set in the CMake configuration file
-   * itself, so we have to check what its set to in the makefile if we can.
-   */
-  if (mf) {
-    return mf->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
-  } else {
-    const char* cacheEntryValue =
-      this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
-    return cmSystemTools::IsOn(cacheEntryValue);
-  }
+  return this->Messenger->GetSuppressDevWarnings();
 }
 
 void cmake::SetSuppressDevWarnings(bool b)
@@ -2482,20 +2454,9 @@ void cmake::SetSuppressDevWarnings(bool b)
                       cmState::INTERNAL);
 }
 
-bool cmake::GetSuppressDeprecatedWarnings(cmMakefile const* mf)
+bool cmake::GetSuppressDeprecatedWarnings() const
 {
-  /*
-   * The suppression CMake variable may be set in the CMake configuration file
-   * itself, so we have to check what its set to in the makefile if we can.
-   */
-  if (mf) {
-    return (mf->IsSet("CMAKE_WARN_DEPRECATED") &&
-            !mf->IsOn("CMAKE_WARN_DEPRECATED"));
-  } else {
-    const char* cacheEntryValue =
-      this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
-    return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue);
-  }
+  return this->Messenger->GetSuppressDeprecatedWarnings();
 }
 
 void cmake::SetSuppressDeprecatedWarnings(bool b)
@@ -2517,16 +2478,9 @@ void cmake::SetSuppressDeprecatedWarnings(bool b)
                       cmState::INTERNAL);
 }
 
-bool cmake::GetDevWarningsAsErrors(cmMakefile const* mf)
+bool cmake::GetDevWarningsAsErrors() const
 {
-  if (mf) {
-    return (mf->IsSet("CMAKE_SUPPRESS_DEVELOPER_ERRORS") &&
-            !mf->IsOn("CMAKE_SUPPRESS_DEVELOPER_ERRORS"));
-  } else {
-    const char* cacheEntryValue =
-      this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
-    return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue);
-  }
+  return this->Messenger->GetDevWarningsAsErrors();
 }
 
 void cmake::SetDevWarningsAsErrors(bool b)
@@ -2548,15 +2502,9 @@ void cmake::SetDevWarningsAsErrors(bool b)
                       cmState::INTERNAL);
 }
 
-bool cmake::GetDeprecatedWarningsAsErrors(cmMakefile const* mf)
+bool cmake::GetDeprecatedWarningsAsErrors() const
 {
-  if (mf) {
-    return mf->IsOn("CMAKE_ERROR_DEPRECATED");
-  } else {
-    const char* cacheEntryValue =
-      this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
-    return cmSystemTools::IsOn(cacheEntryValue);
-  }
+  return this->Messenger->GetDeprecatedWarningsAsErrors();
 }
 
 void cmake::SetDeprecatedWarningsAsErrors(bool b)
diff --git a/Source/cmake.h b/Source/cmake.h
index 266c33d..ae1a502 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -1,36 +1,31 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmake_h
 #define cmake_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
 
-#include "cmCacheManager.h"
 #include "cmInstalledFile.h"
 #include "cmListFileCache.h"
 #include "cmState.h"
-#include "cmSystemTools.h"
 
-class cmGlobalGeneratorFactory;
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_jsoncpp_value.h"
+#endif
+
+class cmExternalMakefileProjectGeneratorFactory;
+class cmFileTimeComparison;
 class cmGlobalGenerator;
-class cmLocalGenerator;
+class cmGlobalGeneratorFactory;
 class cmMakefile;
+class cmMessenger;
 class cmVariableWatch;
-class cmFileTimeComparison;
-class cmExternalMakefileProjectGenerator;
-class cmDocumentationSection;
-class cmTarget;
-class cmGeneratedFileStream;
+struct cmDocumentationEntry;
 
 /** \brief Represents a cmake invocation.
  *
@@ -103,7 +98,11 @@ public:
   struct GeneratorInfo
   {
     std::string name;
+    std::string baseName;
+    std::string extraName;
     bool supportsToolset;
+    bool supportsPlatform;
+    bool isAlias;
   };
 
   typedef std::map<std::string, cmInstalledFile> InstalledFilesMap;
@@ -113,6 +112,11 @@ public:
   /// Destructor
   ~cmake();
 
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  Json::Value ReportCapabilitiesJson(bool haveServerMode) const;
+#endif
+  std::string ReportCapabilities(bool haveServerMode) const;
+
   static const char* GetCMakeFilesDirectory() { return "/CMakeFiles"; }
   static const char* GetCMakeFilesDirectoryPostSlash()
   {
@@ -179,11 +183,14 @@ public:
     return this->GlobalGenerator;
   }
 
+  ///! Return the full path to where the CMakeCache.txt file should be.
+  static std::string FindCacheFile(const std::string& binaryDir);
+
   ///! Return the global generator assigned to this instance of cmake
   void SetGlobalGenerator(cmGlobalGenerator*);
 
   ///! Get the names of the current registered generators
-  void GetRegisteredGenerators(std::vector<GeneratorInfo>& generators);
+  void GetRegisteredGenerators(std::vector<GeneratorInfo>& generators) const;
 
   ///! Set the name of the selected generator-specific platform.
   void SetGeneratorPlatform(std::string const& ts)
@@ -209,9 +216,6 @@ public:
     return this->GeneratorToolset;
   }
 
-  ///! get the cmCachemManager used by this invocation of cmake
-  cmCacheManager* GetCacheManager() { return this->CacheManager; }
-
   const std::vector<std::string>& GetSourceExtensions() const
   {
     return this->SourceFileExtensions;
@@ -253,7 +257,8 @@ public:
    *  number provided may be negative in cases where a message is
    *  to be displayed without any progress percentage.
    */
-  void SetProgressCallback(ProgressCallbackType f, void* clientData = 0);
+  void SetProgressCallback(ProgressCallbackType f,
+                           void* clientData = CM_NULLPTR);
 
   ///! this is called by generators to update the progress
   void UpdateProgress(const char* msg, float prog);
@@ -310,6 +315,14 @@ public:
   void SetTrace(bool b) { this->Trace = b; }
   bool GetTraceExpand() { return this->TraceExpand; }
   void SetTraceExpand(bool b) { this->TraceExpand = b; }
+  void AddTraceSource(std::string const& file)
+  {
+    this->TraceOnlyThisSources.push_back(file);
+  }
+  std::vector<std::string> const& GetTraceSources() const
+  {
+    return this->TraceOnlyThisSources;
+  }
   bool GetWarnUninitialized() { return this->WarnUninitialized; }
   void SetWarnUninitialized(bool b) { this->WarnUninitialized = b; }
   bool GetWarnUnused() { return this->WarnUnused; }
@@ -334,12 +347,14 @@ public:
     return this->CMakeEditCommand;
   }
 
+  cmMessenger* GetMessenger() const;
+
   /*
    * Get the state of the suppression of developer (author) warnings.
    * Returns false, by default, if developer warnings should be shown, true
    * otherwise.
    */
-  bool GetSuppressDevWarnings(cmMakefile const* mf = NULL);
+  bool GetSuppressDevWarnings() const;
   /*
    * Set the state of the suppression of developer (author) warnings.
    */
@@ -350,7 +365,7 @@ public:
    * Returns false, by default, if deprecated warnings should be shown, true
    * otherwise.
    */
-  bool GetSuppressDeprecatedWarnings(cmMakefile const* mf = NULL);
+  bool GetSuppressDeprecatedWarnings() const;
   /*
    * Set the state of the suppression of deprecated warnings.
    */
@@ -361,7 +376,7 @@ public:
    * Returns false, by default, if warnings should not be treated as errors,
    * true otherwise.
    */
-  bool GetDevWarningsAsErrors(cmMakefile const* mf = NULL);
+  bool GetDevWarningsAsErrors() const;
   /**
    * Set the state of treating developer (author) warnings as errors.
    */
@@ -372,7 +387,7 @@ public:
    * Returns false, by default, if warnings should not be treated as errors,
    * true otherwise.
    */
-  bool GetDeprecatedWarningsAsErrors(cmMakefile const* mf = NULL);
+  bool GetDeprecatedWarningsAsErrors() const;
   /**
    * Set the state of treating developer (author) warnings as errors.
    */
@@ -381,8 +396,7 @@ public:
   /** Display a message to the user.  */
   void IssueMessage(
     cmake::MessageType t, std::string const& text,
-    cmListFileBacktrace const& backtrace = cmListFileBacktrace(),
-    bool force = false);
+    cmListFileBacktrace const& backtrace = cmListFileBacktrace()) const;
 
   ///! run the --build option
   int Build(const std::string& dir, const std::string& target,
@@ -407,21 +421,16 @@ protected:
   void InitializeProperties();
   int HandleDeleteCacheVariables(const std::string& var);
 
-  typedef cmExternalMakefileProjectGenerator* (
-    *CreateExtraGeneratorFunctionType)();
-  typedef std::map<std::string, CreateExtraGeneratorFunctionType>
-    RegisteredExtraGeneratorsMap;
   typedef std::vector<cmGlobalGeneratorFactory*> RegisteredGeneratorsVector;
   RegisteredGeneratorsVector Generators;
-  RegisteredExtraGeneratorsMap ExtraGenerators;
+  typedef std::vector<cmExternalMakefileProjectGeneratorFactory*>
+    RegisteredExtraGeneratorsVector;
+  RegisteredExtraGeneratorsVector ExtraGenerators;
   void AddDefaultCommands();
   void AddDefaultGenerators();
   void AddDefaultExtraGenerators();
-  void AddExtraGenerator(const std::string& name,
-                         CreateExtraGeneratorFunctionType newFunction);
 
   cmGlobalGenerator* GlobalGenerator;
-  cmCacheManager* CacheManager;
   std::map<std::string, DiagLevel> DiagLevels;
   std::string GeneratorPlatform;
   std::string GeneratorToolset;
@@ -455,7 +464,6 @@ private:
   void operator=(const cmake&); // Not implemented.
   ProgressCallbackType ProgressCallback;
   void* ProgressCallbackClientData;
-  bool Verbose;
   bool InTryCompile;
   WorkingMode CurrentWorkingMode;
   bool DebugOutput;
@@ -483,6 +491,9 @@ private:
 
   cmState* State;
   cmState::Snapshot CurrentSnapshot;
+  cmMessenger* Messenger;
+
+  std::vector<std::string> TraceOnlyThisSources;
 
   void UpdateConversionPathTable();
 
@@ -493,15 +504,13 @@ private:
    * Convert a message type between a warning and an error, based on the state
    * of the error output CMake variables, in the cache.
    */
-  cmake::MessageType ConvertMessageType(cmake::MessageType t);
+  cmake::MessageType ConvertMessageType(cmake::MessageType t) const;
 
   /*
    * Check if messages of this type should be output, based on the state of the
    * warning and error output CMake variables, in the cache.
    */
-  bool IsMessageTypeVisible(cmake::MessageType t);
-
-  bool PrintMessagePreamble(cmake::MessageType t, std::ostream& msg);
+  bool IsMessageTypeVisible(cmake::MessageType t) const;
 };
 
 #define CMAKE_STANDARD_OPTIONS_TABLE                                          \
diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx
index 056671a..0d1f1ce 100644
--- a/Source/cmakemain.cxx
+++ b/Source/cmakemain.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 // include these first, otherwise there will be problems on Windows
 // with GetCurrentDirectory() being redefined
 #ifdef CMAKE_BUILD_WITH_CMAKE
@@ -17,34 +8,44 @@
 #endif
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmGlobalGenerator.h"
-#include "cmListFileCache.h"
-#include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 #include "cmcmd.h"
+
+#include <cmConfigure.h>
 #include <cmsys/Encoding.hxx>
+#include <iostream>
+#include <string.h>
+#include <string>
+#include <vector>
+
+#ifdef CMAKE_USE_LIBUV
+#include <cm_uv.h>
+#endif
 
 #ifdef CMAKE_BUILD_WITH_CMAKE
 static const char* cmDocumentationName[][2] = {
-  { 0, "  cmake - Cross-Platform Makefile Generator." },
-  { 0, 0 }
+  { CM_NULLPTR, "  cmake - Cross-Platform Makefile Generator." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationUsage[][2] = {
-  { 0, "  cmake [options] <path-to-source>\n"
-       "  cmake [options] <path-to-existing-build>" },
-  { 0, "Specify a source directory to (re-)generate a build system for "
-       "it in the current working directory.  Specify an existing build "
-       "directory to re-generate its build system." },
-  { 0, 0 }
+  { CM_NULLPTR, "  cmake [options] <path-to-source>\n"
+                "  cmake [options] <path-to-existing-build>" },
+  { CM_NULLPTR,
+    "Specify a source directory to (re-)generate a build system for "
+    "it in the current working directory.  Specify an existing build "
+    "directory to re-generate its build system." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 static const char* cmDocumentationUsageNote[][2] = {
-  { 0, "Run 'cmake --help' for more information." },
-  { 0, 0 }
+  { CM_NULLPTR, "Run 'cmake --help' for more information." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 #define CMAKE_BUILD_OPTIONS                                                   \
@@ -73,12 +74,14 @@ static const char* cmDocumentationOptions[][2] = {
   { "--debug-output", "Put cmake in a debug mode." },
   { "--trace", "Put cmake in trace mode." },
   { "--trace-expand", "Put cmake in trace mode with variable expansion." },
+  { "--trace-source=<file>",
+    "Trace only this CMake file/module. Multiple options allowed." },
   { "--warn-uninitialized", "Warn about uninitialized values." },
   { "--warn-unused-vars", "Warn about unused variables." },
   { "--no-warn-unused-cli", "Don't warn about command line options." },
   { "--check-system-vars", "Find problems with variable usage in system "
                            "files." },
-  { 0, 0 }
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 #endif
@@ -104,7 +107,7 @@ static cmMakefile* cmakemainGetMakefile(void* clientdata)
       return gg->GetCurrentMakefile();
     }
   }
-  return 0;
+  return CM_NULLPTR;
 }
 
 static std::string cmakemainGetStack(void* clientdata)
@@ -121,8 +124,8 @@ static std::string cmakemainGetStack(void* clientdata)
   return msg;
 }
 
-static void cmakemainMessageCallback(const char* m, const char*, bool&,
-                                     void* clientdata)
+static void cmakemainMessageCallback(const char* m, const char* /*unused*/,
+                                     bool& /*unused*/, void* clientdata)
 {
   std::cerr << m << cmakemainGetStack(clientdata) << std::endl << std::flush;
 }
@@ -160,7 +163,8 @@ int main(int ac, char const* const* av)
   if (ac > 1) {
     if (strcmp(av[1], "--build") == 0) {
       return do_build(ac, av);
-    } else if (strcmp(av[1], "-E") == 0) {
+    }
+    if (strcmp(av[1], "-E") == 0) {
       return do_command(ac, av);
     }
   }
@@ -168,6 +172,9 @@ int main(int ac, char const* const* av)
 #ifdef CMAKE_BUILD_WITH_CMAKE
   cmDynamicLoader::FlushCache();
 #endif
+#ifdef CMAKE_USE_LIBUV
+  uv_loop_close(uv_default_loop());
+#endif
   return ret;
 }
 
@@ -234,7 +241,8 @@ int do_cmake(int ac, char const* const* av)
         "Use cmake-gui or ccmake for an interactive dialog.\n";
       /* clang-format on */
       return 1;
-    } else if (strcmp(av[i], "--system-information") == 0) {
+    }
+    if (strcmp(av[i], "--system-information") == 0) {
       sysinfo = true;
     } else if (strcmp(av[i], "-N") == 0) {
       view_only = true;
@@ -310,9 +318,8 @@ int do_cmake(int ac, char const* const* av)
   // interpret negative return values as errors.
   if (res != 0) {
     return 1;
-  } else {
-    return 0;
   }
+  return 0;
 }
 
 static int do_build(int ac, char const* const* av)
diff --git a/Source/cmakexbuild.cxx b/Source/cmakexbuild.cxx
index bdbc4da..82db012 100644
--- a/Source/cmakexbuild.cxx
+++ b/Source/cmakexbuild.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmStandardIncludes.h"
 
 #include "cmSystemTools.h"
diff --git a/Source/cmcldeps.cxx b/Source/cmcldeps.cxx
index 8b0cede..167d60a 100644
--- a/Source/cmcldeps.cxx
+++ b/Source/cmcldeps.cxx
@@ -21,6 +21,7 @@
 #include <cmSystemTools.h>
 #include <cmsys/Encoding.hxx>
 
+#include <algorithm>
 #include <sstream>
 #include <windows.h>
 
@@ -213,7 +214,7 @@ static int process(const std::string& srcfilename, const std::string& dfile,
                                     dir.c_str(), cmSystemTools::OUTPUT_NONE);
 
   // process the include directives and output everything else
-  std::stringstream ss(output);
+  std::istringstream ss(output);
   std::string line;
   std::vector<std::string> includes;
   bool isFirstLine = true; // cl prints always first the source filename
diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx
index 471028a..4387bf6 100644
--- a/Source/cmcmd.cxx
+++ b/Source/cmcmd.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmcmd.h"
 
 #include "cmAlgorithms.h"
@@ -16,28 +7,46 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmQtAutoGenerators.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmUtils.hxx"
 #include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
+#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
+#include "cmServer.h"
+#include "cmServerConnection.h"
+#endif
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
 #endif
 
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Process.h>
-#include <cmsys/Terminal.h>
+#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
+#include "bindexplib.h"
+#endif
 
-#if defined(CMAKE_HAVE_VS_GENERATORS)
-#include "cmCallVisualStudioMacro.h"
+#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__)
 #include "cmVisualStudioWCEPlatformParser.h"
 #endif
 
+#include <algorithm>
+#include <cmConfigure.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Process.h>
+#include <cmsys/Terminal.h>
+#include <iostream>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
 #include <time.h>
 
-#include <stdlib.h> // required for atoi
-#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
-#include "bindexplib.h"
-#endif
+int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
+                              std::vector<std::string>::const_iterator argEnd);
+int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
+                             std::vector<std::string>::const_iterator argEnd);
 
 void CMakeCommandUsage(const char* program)
 {
@@ -60,6 +69,8 @@ void CMakeCommandUsage(const char* program)
   errorStream
     << "Usage: " << program << " -E <command> [arguments...]\n"
     << "Available commands: \n"
+    << "  capabilities              - Report capabilities built into cmake "
+       "in JSON format\n"
     << "  chdir dir cmd [args...]   - run command in a given directory\n"
     << "  compare_files file1 file2 - check if file1 is same as file2\n"
     << "  copy <file>... destination  - copy files to destination "
@@ -81,9 +92,10 @@ void CMakeCommandUsage(const char* program)
     << "  remove_directory dir      - remove a directory and its contents\n"
     << "  rename oldname newname    - rename a file or directory "
        "(on one volume)\n"
+    << "  server                    - start cmake in server mode\n"
+    << "  sleep <number>...         - sleep for given number of seconds\n"
     << "  tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
     << "                            - create or extract a tar or zip archive\n"
-    << "  sleep <number>...         - sleep for given number of seconds\n"
     << "  time command [args...]    - run command and return elapsed time\n"
     << "  touch file                - touch a file.\n"
     << "  touch_nocreate file       - touch a file but do not create it.\n"
@@ -260,7 +272,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     // run include what you use command and then run the compile
     // command. This is an internal undocumented option and should
     // only be used by CMake itself when running iwyu.
-    else if (args[1] == "__run_iwyu") {
+    if (args[1] == "__run_iwyu") {
       if (args.size() < 3) {
         std::cerr << "__run_iwyu Usage: -E __run_iwyu [--iwyu=/path/iwyu]"
                      " [--tidy=/path/tidy] -- compile command\n";
@@ -271,6 +283,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       std::string iwyu;
       std::string tidy;
       std::string sourceFile;
+      std::string lwyu;
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         std::string const& arg = args[cc];
         if (arg == "--") {
@@ -281,6 +294,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
           tidy = arg.substr(7);
         } else if (doing_options && cmHasLiteralPrefix(arg, "--source=")) {
           sourceFile = arg.substr(9);
+        } else if (doing_options && cmHasLiteralPrefix(arg, "--lwyu=")) {
+          lwyu = arg.substr(7);
         } else if (doing_options) {
           std::cerr << "__run_iwyu given unknown argument: " << arg << "\n";
           return 1;
@@ -288,7 +303,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
           orig_cmd.push_back(arg);
         }
       }
-      if (tidy.empty() && iwyu.empty()) {
+      if (tidy.empty() && iwyu.empty() && lwyu.empty()) {
         std::cerr << "__run_iwyu missing --tidy= or --iwyu=\n";
         return 1;
       }
@@ -296,7 +311,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         std::cerr << "__run_iwyu --tidy= requires --source=\n";
         return 1;
       }
-      if (orig_cmd.empty()) {
+      if (orig_cmd.empty() && lwyu.empty()) {
         std::cerr << "__run_iwyu missing compile command after --\n";
         return 1;
       }
@@ -312,7 +327,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 
         // Run the iwyu command line.  Capture its stderr and hide its stdout.
         std::string stdErr;
-        if (!cmSystemTools::RunSingleCommand(iwyu_cmd, 0, &stdErr, &ret, 0,
+        if (!cmSystemTools::RunSingleCommand(iwyu_cmd, CM_NULLPTR, &stdErr,
+                                             &ret, CM_NULLPTR,
                                              cmSystemTools::OUTPUT_NONE)) {
           std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr
                     << "\n";
@@ -340,19 +356,46 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 
         // Run the tidy command line.  Capture its stdout and hide its stderr.
         std::string stdOut;
-        if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, 0, &ret, 0,
+        if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, CM_NULLPTR,
+                                             &ret, CM_NULLPTR,
                                              cmSystemTools::OUTPUT_NONE)) {
           std::cerr << "Error running '" << tidy_cmd[0] << "'\n";
           return 1;
         }
-
         // Output the stdout from clang-tidy to stderr
         std::cerr << stdOut;
       }
+      if (!lwyu.empty()) {
+        // Construct the ldd -r -u (link what you use lwyu) command line
+        // ldd -u -r lwuy target
+        std::vector<std::string> lwyu_cmd;
+        lwyu_cmd.push_back("ldd");
+        lwyu_cmd.push_back("-u");
+        lwyu_cmd.push_back("-r");
+        lwyu_cmd.push_back(lwyu);
+
+        // Run the ldd -u -r command line.
+        // Capture its stdout and hide its stderr.
+        std::string stdOut;
+        if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, CM_NULLPTR,
+                                             &ret, CM_NULLPTR,
+                                             cmSystemTools::OUTPUT_NONE)) {
+          std::cerr << "Error running '" << lwyu_cmd[0] << "'\n";
+          return 1;
+        }
 
+        // Output the stdout from ldd -r -u to stderr
+        // Warn if lwyu reported anything.
+        if (stdOut.find("Unused direct dependencies:") != stdOut.npos) {
+          std::cerr << "Warning: " << stdOut;
+        }
+      }
+      ret = 0;
       // Now run the real compiler command and return its result value.
-      if (!cmSystemTools::RunSingleCommand(
-            orig_cmd, 0, 0, &ret, 0, cmSystemTools::OUTPUT_PASSTHROUGH)) {
+      if (lwyu.empty() &&
+          !cmSystemTools::RunSingleCommand(
+            orig_cmd, CM_NULLPTR, CM_NULLPTR, &ret, CM_NULLPTR,
+            cmSystemTools::OUTPUT_PASSTHROUGH)) {
         std::cerr << "Error running '" << orig_cmd[0] << "'\n";
         return 1;
       }
@@ -360,13 +403,13 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Echo string
-    else if (args[1] == "echo") {
+    if (args[1] == "echo") {
       std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
       return 0;
     }
 
     // Echo string no new line
-    else if (args[1] == "echo_append") {
+    if (args[1] == "echo_append") {
       std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
       return 0;
     }
@@ -402,7 +445,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       // Execute command from remaining arguments.
       std::vector<std::string> cmd(ai, ae);
       int retval;
-      if (cmSystemTools::RunSingleCommand(cmd, 0, 0, &retval, NULL,
+      if (cmSystemTools::RunSingleCommand(cmd, CM_NULLPTR, CM_NULLPTR, &retval,
+                                          CM_NULLPTR,
                                           cmSystemTools::OUTPUT_PASSTHROUGH)) {
         return retval;
       }
@@ -478,6 +522,20 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       }
       return 0;
     }
+    // capabilities
+    else if (args[1] == "capabilities") {
+      if (args.size() > 2) {
+        std::cerr << "-E capabilities accepts no additional arguments\n";
+        return 1;
+      }
+      cmake cm;
+#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
+      std::cout << cm.ReportCapabilities(true);
+#else
+      std::cout << cm.ReportCapabilities(false);
+#endif
+      return 0;
+    }
 
     // Sleep command
     else if (args[1] == "sleep" && args.size() > 2) {
@@ -510,7 +568,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       time(&time_start);
       clock_start = clock();
       int ret = 0;
-      cmSystemTools::RunSingleCommand(command, 0, 0, &ret);
+      cmSystemTools::RunSingleCommand(command, CM_NULLPTR, CM_NULLPTR, &ret);
 
       clock_finish = clock();
       time(&time_finish);
@@ -561,8 +619,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       int retval = 0;
       int timeout = 0;
       if (cmSystemTools::RunSingleCommand(
-            command.c_str(), 0, 0, &retval, directory.c_str(),
-            cmSystemTools::OUTPUT_PASSTHROUGH, timeout)) {
+            command.c_str(), CM_NULLPTR, CM_NULLPTR, &retval,
+            directory.c_str(), cmSystemTools::OUTPUT_PASSTHROUGH, timeout)) {
         return retval;
       }
 
@@ -640,36 +698,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       return cmcmd::SymlinkExecutable(args);
     }
 
-#if defined(CMAKE_HAVE_VS_GENERATORS)
-    // Internal CMake support for calling Visual Studio macros.
-    else if (args[1] == "cmake_call_visual_studio_macro" && args.size() >= 4) {
-      // args[2] = full path to .sln file or "ALL"
-      // args[3] = name of Visual Studio macro to call
-      // args[4..args.size()-1] = [optional] args for Visual Studio macro
-
-      std::string macroArgs;
-
-      if (args.size() > 4) {
-        macroArgs = args[4];
-
-        for (size_t i = 5; i < args.size(); ++i) {
-          macroArgs += " ";
-          macroArgs += args[i];
-        }
-      }
-
-      return cmCallVisualStudioMacro::CallMacro(args[2], args[3], macroArgs,
-                                                true);
-    }
-#endif
-
     // Internal CMake dependency scanning support.
     else if (args[1] == "cmake_depends" && args.size() >= 6) {
-      // Use the make system's VERBOSE environment variable to enable
-      // verbose output. This can be skipped by also setting CMAKE_NO_VERBOSE
-      // (which is set by the Eclipse and KDevelop generators).
-      bool verbose = ((cmSystemTools::GetEnv("VERBOSE") != 0) &&
-                      (cmSystemTools::GetEnv("CMAKE_NO_VERBOSE") == 0));
+      const bool verbose = isCMakeVerbose();
 
       // Create a cmake object instance to process dependencies.
       cmake cm;
@@ -732,9 +763,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         cmState::Snapshot snapshot = cm.GetCurrentSnapshot();
         snapshot.GetDirectory().SetCurrentBinary(startOutDir);
         snapshot.GetDirectory().SetCurrentSource(startDir);
-        cmsys::auto_ptr<cmMakefile> mf(new cmMakefile(ggd, snapshot));
-        cmsys::auto_ptr<cmLocalGenerator> lgd(
-          ggd->CreateLocalGenerator(mf.get()));
+        CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(ggd, snapshot));
+        CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mf.get()));
 
         // Actually scan dependencies.
         return lgd->UpdateDependencies(depInfo.c_str(), verbose, color) ? 0
@@ -748,6 +778,18 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       return cmcmd::ExecuteLinkScript(args);
     }
 
+#ifdef CMAKE_BUILD_WITH_CMAKE
+    // Internal CMake ninja dependency scanning support.
+    else if (args[1] == "cmake_ninja_depends") {
+      return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
+    }
+
+    // Internal CMake ninja dyndep support.
+    else if (args[1] == "cmake_ninja_dyndep") {
+      return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
+    }
+#endif
+
     // Internal CMake unimplemented feature notification.
     else if (args[1] == "cmake_unimplemented_variable") {
       std::cerr << "Feature not implemented for this platform.";
@@ -835,7 +877,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         cmSystemTools::Error("Can not use compression flags with format: ",
                              format.c_str());
         return 1;
-      } else if (nCompress > 1) {
+      }
+      if (nCompress > 1) {
         cmSystemTools::Error("Can only compress a tar file one way; "
                              "at most one flag of z, j, or J may be used");
         return 1;
@@ -868,9 +911,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         // 1/10th of a second after the untar.  If CMAKE_UNTAR_DELAY
         // is set in the env, its value will be used instead of 100.
         int delay = 100;
-        const char* delayVar = cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY");
-        if (delayVar) {
-          delay = atoi(delayVar);
+        std::string delayVar;
+        if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
+          delay = atoi(delayVar.c_str());
         }
         if (delay) {
           cmSystemTools::Delay(delay);
@@ -878,6 +921,53 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 #endif
       }
       return 0;
+    } else if (args[1] == "server") {
+      const std::string pipePrefix = "--pipe=";
+      bool supportExperimental = false;
+      bool isDebug = false;
+      std::string pipe;
+
+      for (size_t i = 2; i < args.size(); ++i) {
+        const std::string& a = args[i];
+
+        if (a == "--experimental") {
+          supportExperimental = true;
+        } else if (a == "--debug") {
+          pipe.clear();
+          isDebug = true;
+        } else if (a.substr(0, pipePrefix.size()) == pipePrefix) {
+          isDebug = false;
+          pipe = a.substr(pipePrefix.size());
+          if (pipe.empty()) {
+            cmSystemTools::Error("No pipe given after --pipe=");
+            return 2;
+          }
+        } else {
+          cmSystemTools::Error("Unknown argument for server mode");
+          return 1;
+        }
+      }
+#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
+      cmServerConnection* conn;
+      if (isDebug) {
+        conn = new cmServerStdIoConnection;
+      } else {
+        conn = new cmServerPipeConnection(pipe);
+      }
+      cmServer server(conn, supportExperimental);
+      std::string errorMessage;
+      if (server.Serve(&errorMessage)) {
+        return 0;
+      } else {
+        cmSystemTools::Error(errorMessage.c_str());
+        return 1;
+      }
+#else
+      static_cast<void>(supportExperimental);
+      static_cast<void>(isDebug);
+      cmSystemTools::Error("CMake was not built with server mode enabled");
+      return 1;
+#endif
     }
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -979,12 +1069,12 @@ static void cmcmdProgressReport(std::string const& dir, std::string const& num)
   int count = 0;
   if (!progFile) {
     return;
-  } else {
-    if (1 != fscanf(progFile, "%i", &count)) {
-      cmSystemTools::Message("Could not read from progress file.");
-    }
-    fclose(progFile);
   }
+  if (1 != fscanf(progFile, "%i", &count)) {
+    cmSystemTools::Message("Could not read from progress file.");
+  }
+  fclose(progFile);
+
   const char* last = num.c_str();
   for (const char* c = last;; ++c) {
     if (*c == ',' || *c == '\0') {
@@ -1027,11 +1117,7 @@ int cmcmd::ExecuteEchoColor(std::vector<std::string>& args)
       // Enable or disable color based on the switch value.
       std::string value = args[i].substr(9);
       if (!value.empty()) {
-        if (cmSystemTools::IsOn(value.c_str())) {
-          enabled = true;
-        } else {
-          enabled = false;
-        }
+        enabled = cmSystemTools::IsOn(value.c_str());
       }
     } else if (cmHasLiteralPrefix(args[i], "--progress-dir=")) {
       progressDir = args[i].substr(15);
@@ -1123,7 +1209,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
     }
 
     // Setup this command line.
-    const char* cmd[2] = { command.c_str(), 0 };
+    const char* cmd[2] = { command.c_str(), CM_NULLPTR };
     cmsysProcess_SetCommand(cp, cmd);
 
     // Report the command if verbose output is enabled.
@@ -1133,7 +1219,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
 
     // Run the command and wait for it to exit.
     cmsysProcess_Execute(cp);
-    cmsysProcess_WaitForExit(cp, 0);
+    cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 
     // Report failure if any.
     switch (cmsysProcess_GetState(cp)) {
@@ -1167,7 +1253,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
 
 int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
 {
-#if defined(CMAKE_HAVE_VS_GENERATORS)
+#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__)
   cmVisualStudioWCEPlatformParser parser(name.c_str());
   parser.ParseVersion(version);
   if (parser.Found()) {
@@ -1226,7 +1312,7 @@ int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type)
   if (args.size() < 2) {
     return -1;
   }
-  bool verbose = cmSystemTools::GetEnv("VERBOSE") ? true : false;
+  const bool verbose = cmSystemTools::HasEnv("VERBOSE");
   std::vector<std::string> expandedArgs;
   for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
        ++i) {
@@ -1250,7 +1336,7 @@ int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type)
 }
 
 static bool RunCommand(const char* comment, std::vector<std::string>& command,
-                       bool verbose, int* retCodeOut = 0)
+                       bool verbose, int* retCodeOut = CM_NULLPTR)
 {
   if (verbose) {
     std::cout << comment << ":\n";
@@ -1259,8 +1345,9 @@ static bool RunCommand(const char* comment, std::vector<std::string>& command,
   std::string output;
   int retCode = 0;
   // use rc command to create .res file
-  bool res = cmSystemTools::RunSingleCommand(
-    command, &output, &output, &retCode, 0, cmSystemTools::OUTPUT_NONE);
+  bool res =
+    cmSystemTools::RunSingleCommand(command, &output, &output, &retCode,
+                                    CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
   // always print the output of the command, unless
   // it is the dumb rc command banner, but if the command
   // returned an error code then print the output anyway as
diff --git a/Source/cmcmd.h b/Source/cmcmd.h
index 8da2103..139d2a8 100644
--- a/Source/cmcmd.h
+++ b/Source/cmcmd.h
@@ -1,19 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmcmd_h
 #define cmcmd_h
 
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
 
 class cmcmd
 {
diff --git a/Source/cmparseMSBuildXML.py b/Source/cmparseMSBuildXML.py
index 056a0db..1b38d15 100755
--- a/Source/cmparseMSBuildXML.py
+++ b/Source/cmparseMSBuildXML.py
@@ -15,6 +15,9 @@
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/cl.xml"
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/lib.xml"
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/link.xml"
+#  "${PROGRAMFILES}/Microsoft Visual Studio/VS15Preview/Common7/IDE/VC/VCTargets/1033/cl.xml"
+#  "${PROGRAMFILES}/Microsoft Visual Studio/VS15Preview/Common7/IDE/VC/VCTargets/1033/lib.xml"
+#  "${PROGRAMFILES}/Microsoft Visual Studio/VS15Preview/Common7/IDE/VC/VCTargets/1033/link.xml"
 #
 #  BoolProperty  <Name>true|false</Name>
 #   simple example:
diff --git a/Source/ctest.cxx b/Source/ctest.cxx
index 4edd62e..1fb39ff 100644
--- a/Source/ctest.cxx
+++ b/Source/ctest.cxx
@@ -1,32 +1,28 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include <cmConfigure.h>
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+#include "CTest/cmCTestLaunch.h"
+#include "CTest/cmCTestScriptHandler.h"
 #include "cmCTest.h"
-#include "cmSystemTools.h"
-
-// Need these for documentation support.
 #include "cmDocumentation.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
-#include "CTest/cmCTestLaunch.h"
-#include "CTest/cmCTestScriptHandler.h"
-#include "cmsys/Encoding.hxx"
+#include <cmsys/Encoding.hxx>
+#include <iostream>
+#include <string.h>
+#include <string>
+#include <vector>
 
 static const char* cmDocumentationName[][2] = {
-  { 0, "  ctest - Testing driver provided by CMake." },
-  { 0, 0 }
+  { CM_NULLPTR, "  ctest - Testing driver provided by CMake." },
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
-static const char* cmDocumentationUsage[][2] = { { 0, "  ctest [options]" },
-                                                 { 0, 0 } };
+static const char* cmDocumentationUsage[][2] = { { CM_NULLPTR,
+                                                   "  ctest [options]" },
+                                                 { CM_NULLPTR, CM_NULLPTR } };
 
 static const char* cmDocumentationOptions[][2] = {
   { "-C <cfg>, --build-config <cfg>", "Choose configuration to test." },
@@ -108,7 +104,7 @@ static const char* cmDocumentationOptions[][2] = {
   { "--http1.0", "Submit using HTTP 1.0." },
   { "--no-compress-output", "Do not compress test output when submitting." },
   { "--print-labels", "Print all available test labels." },
-  { 0, 0 }
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
 // this is a test driver program for cmCTest.
diff --git a/Source/dir.dox b/Source/dir.dox
new file mode 100644
index 0000000..66e3de7
--- /dev/null
+++ b/Source/dir.dox
@@ -0,0 +1,7 @@
+/*!
+
+\dir
+
+\brief Root \c ${CMake_SOURCE_DIR}/Source directory
+
+*/
diff --git a/Source/dir.dox.in b/Source/dir.dox.in
new file mode 100644
index 0000000..78cf58d
--- /dev/null
+++ b/Source/dir.dox.in
@@ -0,0 +1,7 @@
+/*!
+
+\dir
+
+\brief Generated \c ${CMake_BINARY_DIR}/Source directory
+
+*/
diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt
index 8b15394..c4fe5e8 100644
--- a/Source/kwsys/CMakeLists.txt
+++ b/Source/kwsys/CMakeLists.txt
@@ -123,6 +123,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
   SET(KWSYS_USE_FStream 1)
   SET(KWSYS_USE_String 1)
   SET(KWSYS_USE_SystemInformation 1)
+  SET(KWSYS_USE_ConsoleBuf 1)
 ENDIF()
 
 # Enforce component dependencies.
@@ -154,6 +155,9 @@ ENDIF()
 IF(KWSYS_USE_FStream)
   SET(KWSYS_USE_Encoding 1)
 ENDIF()
+IF(KWSYS_USE_ConsoleBuf)
+  SET(KWSYS_USE_Encoding 1)
+ENDIF()
 
 # Setup the large file support default.
 IF(KWSYS_LFS_DISABLE)
@@ -632,6 +636,11 @@ IF(KWSYS_USE_SystemInformation)
   ENDIF()
 ENDIF()
 
+IF(KWSYS_USE_FStream)
+  KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H
+    "Checking whether <ext/stdio_filebuf.h> is available" DIRECT)
+ENDIF()
+
 #-----------------------------------------------------------------------------
 # Choose a directory for the generated headers.
 IF(NOT KWSYS_HEADER_ROOT)
@@ -663,13 +672,12 @@ SET(KWSYS_CLASSES)
 SET(KWSYS_H_FILES Configure SharedForward)
 SET(KWSYS_HXX_FILES Configure String
   hashtable hash_fun hash_map hash_set
-  auto_ptr
   )
 
 # Add selected C++ classes.
 SET(cppclasses
   Directory DynamicLoader Encoding Glob RegularExpression SystemTools
-  CommandLineArguments IOStream FStream SystemInformation
+  CommandLineArguments IOStream FStream SystemInformation ConsoleBuf
   )
 FOREACH(cpp ${cppclasses})
   IF(KWSYS_USE_${cpp})
@@ -903,7 +911,6 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
     # C++ tests
     IF(NOT WATCOM)
       SET(KWSYS_CXX_TESTS
-        testAutoPtr
         testHashSTL
         )
     ENDIF()
@@ -923,6 +930,20 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
         testFStream
         )
     ENDIF()
+    IF(KWSYS_USE_ConsoleBuf)
+      ADD_EXECUTABLE(testConsoleBufChild testConsoleBufChild.cxx)
+      SET_PROPERTY(TARGET testConsoleBufChild PROPERTY LABELS ${KWSYS_LABELS_EXE})
+      TARGET_LINK_LIBRARIES(testConsoleBufChild ${KWSYS_NAMESPACE})
+      SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS}
+        testConsoleBuf
+        )
+      IF("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC" AND
+         NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "19.0")
+        set_property(SOURCE testConsoleBuf.cxx testConsoleBufChild.cxx PROPERTY COMPILE_FLAGS /utf-8)
+      ENDIF()
+      SET_PROPERTY(SOURCE testConsoleBuf.cxx APPEND PROPERTY COMPILE_DEFINITIONS
+        KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE})
+    ENDIF()
     IF(KWSYS_USE_SystemInformation)
       SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testSystemInformation)
     ENDIF()
diff --git a/Source/kwsys/Configure.hxx.in b/Source/kwsys/Configure.hxx.in
index ff8e49d..4ce680d 100644
--- a/Source/kwsys/Configure.hxx.in
+++ b/Source/kwsys/Configure.hxx.in
@@ -17,6 +17,8 @@
 
 /* Whether wstring is available.  */
 #define @KWSYS_NAMESPACE at _STL_HAS_WSTRING @KWSYS_STL_HAS_WSTRING@
+/* Whether <ext/stdio_filebuf.h> is available. */
+#define @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@
 
 /* If building a C++ file in kwsys itself, give the source file
    access to the macros without a configured namespace.  */
@@ -24,8 +26,9 @@
 # if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
 #  define kwsys     @KWSYS_NAMESPACE@
 # endif
-# define KWSYS_NAME_IS_KWSYS            @KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define KWSYS_STL_HAS_WSTRING          @KWSYS_NAMESPACE at _STL_HAS_WSTRING
+# define KWSYS_NAME_IS_KWSYS               @KWSYS_NAMESPACE at _NAME_IS_KWSYS
+# define KWSYS_STL_HAS_WSTRING             @KWSYS_NAMESPACE at _STL_HAS_WSTRING
+# define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
 #endif
 
 #endif
diff --git a/Source/kwsys/ConsoleBuf.hxx.in b/Source/kwsys/ConsoleBuf.hxx.in
new file mode 100644
index 0000000..8aeeda1
--- /dev/null
+++ b/Source/kwsys/ConsoleBuf.hxx.in
@@ -0,0 +1,348 @@
+/*============================================================================
+  KWSys - Kitware System Library
+  Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef @KWSYS_NAMESPACE at _ConsoleBuf_hxx
+#define @KWSYS_NAMESPACE at _ConsoleBuf_hxx
+
+#include <@KWSYS_NAMESPACE@/Configure.hxx>
+#include <@KWSYS_NAMESPACE@/Encoding.hxx>
+#include <string>
+#include <cstring>
+#include <sstream>
+#include <streambuf>
+#include <iostream>
+#include <stdexcept>
+
+#if defined(_WIN32)
+#  include <windows.h>
+#  if __cplusplus >= 201103L
+#    include <system_error>
+#  endif
+#endif
+
+namespace @KWSYS_NAMESPACE@
+{
+#if defined(_WIN32)
+
+  template<class CharT, class Traits = std::char_traits<CharT> >
+  class @KWSYS_NAMESPACE at _EXPORT BasicConsoleBuf :
+      public std::basic_streambuf<CharT, Traits> {
+    public:
+      typedef typename Traits::int_type int_type;
+      typedef typename Traits::char_type char_type;
+
+      class Manager {
+        public:
+          Manager(std::basic_ios<CharT, Traits> &ios, const bool err = false)
+            : m_consolebuf(0)
+          {
+            m_ios = &ios;
+            try {
+              m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
+              m_streambuf = m_ios->rdbuf(m_consolebuf);
+            } catch (const std::runtime_error& ex) {
+              std::cerr << "Failed to create ConsoleBuf!" << std::endl
+                        << ex.what() << std::endl;
+            };
+          }
+
+          ~Manager()
+          {
+            if (m_consolebuf) {
+              delete m_consolebuf;
+              m_ios->rdbuf(m_streambuf);
+            }
+          }
+
+        private:
+          std::basic_ios<CharT, Traits> *m_ios;
+          std::basic_streambuf<CharT, Traits> *m_streambuf;
+          BasicConsoleBuf<CharT, Traits> *m_consolebuf;
+      };
+
+      BasicConsoleBuf(const bool err = false) :
+        flush_on_newline(true),
+        input_pipe_codepage(0),
+        output_pipe_codepage(0),
+        input_file_codepage(CP_UTF8),
+        output_file_codepage(CP_UTF8),
+        m_consolesCodepage(0)
+      {
+        m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
+        checkHandle(true, "STD_INPUT_HANDLE");
+        if (!setActiveInputCodepage()) {
+          throw std::runtime_error("setActiveInputCodepage failed!");
+        }
+        m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE) :
+                          ::GetStdHandle(STD_OUTPUT_HANDLE);
+        checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
+        if (!setActiveOutputCodepage()) {
+          throw std::runtime_error("setActiveOutputCodepage failed!");
+        }
+        _setg();
+        _setp();
+      }
+
+      ~BasicConsoleBuf() throw()
+      {
+        sync();
+      }
+
+      bool activateCodepageChange()
+      {
+        return setActiveInputCodepage() && setActiveOutputCodepage();
+      }
+
+    protected:
+      virtual int sync() {
+        bool success = true;
+        if (m_hInput && m_isConsoleInput &&
+            ::FlushConsoleInputBuffer(m_hInput) == 0) {
+          success = false;
+        }
+        if (m_hOutput && !m_obuffer.empty()) {
+          const std::wstring wbuffer = getBuffer(m_obuffer);
+          if (m_isConsoleOutput) {
+            DWORD charsWritten;
+            success = ::WriteConsoleW(m_hOutput, wbuffer.c_str(),
+                                      (DWORD)wbuffer.size(), &charsWritten,
+                                      NULL) == 0 ? false : true;
+          } else {
+            DWORD bytesWritten;
+            std::string buffer;
+            success = encodeOutputBuffer(wbuffer, buffer);
+            if (success) {
+              success = ::WriteFile(m_hOutput, buffer.c_str(),
+                                    (DWORD)buffer.size(), &bytesWritten,
+                                     NULL) == 0 ? false : true;
+            }
+          }
+        }
+        m_ibuffer.clear();
+        m_obuffer.clear();
+        _setg();
+        _setp();
+        return success ? 0 : -1;
+      }
+
+      virtual int_type underflow() {
+        if (this->gptr() >= this->egptr()) {
+          if (!m_hInput) {
+            _setg(true);
+            return Traits::eof();
+          }
+          if (m_isConsoleInput) {
+            wchar_t wbuffer[128];
+            DWORD charsRead;
+            if (::ReadConsoleW(m_hInput, wbuffer, (sizeof(wbuffer) / sizeof(wbuffer[0])) - 1,
+                               &charsRead, NULL) == 0 || charsRead == 0) {
+              _setg(true);
+              return Traits::eof();
+            }
+            wbuffer[charsRead] = L'\0';
+            setBuffer(wbuffer, m_ibuffer);
+          } else {
+            std::wstring totalBuffer;
+            std::wstring wbuffer;
+            char buffer[128];
+            DWORD bytesRead;
+            while (::ReadFile(m_hInput, buffer, (sizeof(buffer) / sizeof(buffer[0])) - 1,
+                              &bytesRead, NULL) == 0) {
+              if (::GetLastError() == ERROR_MORE_DATA) {
+                buffer[bytesRead] = '\0';
+                if (decodeInputBuffer(buffer, wbuffer)) {
+                  totalBuffer += wbuffer;
+                  continue;
+                }
+              }
+              _setg(true);
+              return Traits::eof();
+            }
+            buffer[bytesRead] = '\0';
+            if (!decodeInputBuffer(buffer, wbuffer)) {
+              _setg(true);
+              return Traits::eof();
+            }
+            totalBuffer += wbuffer;
+            setBuffer(totalBuffer, m_ibuffer);
+          }
+          _setg();
+        }
+        return Traits::to_int_type(*this->gptr());
+      }
+
+      virtual int_type overflow(int_type ch = Traits::eof()) {
+        if (!Traits::eq_int_type(ch, Traits::eof())) {
+          char_type chr = Traits::to_char_type(ch);
+          m_obuffer += chr;
+          if ((flush_on_newline && Traits::eq(chr, '\n')) ||
+              Traits::eq_int_type(ch, 0x00)) {
+            sync();
+          }
+          return ch;
+        }
+        sync();
+        return Traits::eof();
+      }
+
+    public:
+      bool flush_on_newline;
+      UINT input_pipe_codepage;
+      UINT output_pipe_codepage;
+      UINT input_file_codepage;
+      UINT output_file_codepage;
+
+    private:
+      HANDLE m_hInput;
+      HANDLE m_hOutput;
+      std::basic_string<char_type> m_ibuffer;
+      std::basic_string<char_type> m_obuffer;
+      bool m_isConsoleInput;
+      bool m_isConsoleOutput;
+      UINT m_activeInputCodepage;
+      UINT m_activeOutputCodepage;
+      UINT m_consolesCodepage;
+      void checkHandle(bool input, std::string handleName) {
+        if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
+            (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
+          std::string errmsg = "GetStdHandle(" + handleName +
+                               ") returned INVALID_HANDLE_VALUE";
+#if __cplusplus >= 201103L
+          throw std::system_error(::GetLastError(),
+                                  std::system_category(), errmsg);
+#else
+          throw std::runtime_error(errmsg);
+#endif
+        }
+      }
+      UINT getConsolesCodepage() {
+        if (!m_consolesCodepage) {
+          m_consolesCodepage = GetConsoleCP();
+          if (!m_consolesCodepage) {
+            m_consolesCodepage = GetACP();
+          }
+        }
+        return m_consolesCodepage;
+      }
+      bool setActiveInputCodepage() {
+        m_isConsoleInput = false;
+        switch (GetFileType(m_hInput)) {
+          case FILE_TYPE_DISK:
+            m_activeInputCodepage = input_file_codepage;
+            break;
+          case FILE_TYPE_CHAR:
+            m_isConsoleInput = true;
+            break;
+          case FILE_TYPE_PIPE:
+            m_activeInputCodepage = input_pipe_codepage;
+            break;
+          default:
+            return false;
+        }
+        if (!m_isConsoleInput && m_activeInputCodepage == 0) {
+          m_activeInputCodepage = getConsolesCodepage();
+        }
+        return true;
+      }
+      bool setActiveOutputCodepage() {
+        m_isConsoleOutput = false;
+        switch (GetFileType(m_hOutput)) {
+          case FILE_TYPE_DISK:
+            m_activeOutputCodepage = output_file_codepage;
+            break;
+          case FILE_TYPE_CHAR:
+            m_isConsoleOutput = true;
+            break;
+          case FILE_TYPE_PIPE:
+            m_activeOutputCodepage = output_pipe_codepage;
+            break;
+          default:
+            return false;
+        }
+        if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
+           m_activeOutputCodepage = getConsolesCodepage();
+        }
+        return true;
+      }
+      void _setg(bool empty = false) {
+        if (!empty) {
+          this->setg((char_type *)m_ibuffer.data(),
+                     (char_type *)m_ibuffer.data(),
+                     (char_type *)m_ibuffer.data() + m_ibuffer.size());
+        } else {
+          this->setg((char_type *)m_ibuffer.data(),
+                     (char_type *)m_ibuffer.data() + m_ibuffer.size(),
+                     (char_type *)m_ibuffer.data() + m_ibuffer.size());
+        }
+      }
+      void _setp() {
+        this->setp((char_type *)m_obuffer.data(),
+                   (char_type *)m_obuffer.data() + m_obuffer.size());
+      }
+      bool encodeOutputBuffer(const std::wstring wbuffer,
+                              std::string &buffer) {
+        const int length = WideCharToMultiByte(m_activeOutputCodepage, 0,
+                                               wbuffer.c_str(),
+                                               (int)wbuffer.size(), NULL, 0,
+                                               NULL, NULL);
+        char *buf = new char[length + 1];
+        const bool success = WideCharToMultiByte(m_activeOutputCodepage, 0,
+                                                 wbuffer.c_str(),
+                                                 (int)wbuffer.size(), buf,
+                                                 length, NULL, NULL) > 0
+                             ? true : false;
+        buf[length] = '\0';
+        buffer = buf;
+        delete[] buf;
+        return success;
+      }
+      bool decodeInputBuffer(const char *buffer, std::wstring &wbuffer) {
+        int actualCodepage = m_activeInputCodepage;
+        const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
+        if (std::memcmp(buffer, BOM_UTF8, sizeof(BOM_UTF8)) == 0) {
+          // PowerShell uses UTF-8 with BOM for pipes
+          actualCodepage = CP_UTF8;
+          buffer += sizeof(BOM_UTF8);
+        }
+        const int wlength = MultiByteToWideChar(actualCodepage, 0, buffer,
+                                                -1, NULL, 0);
+        wchar_t *wbuf = new wchar_t[wlength];
+        const bool success = MultiByteToWideChar(actualCodepage, 0, buffer,
+                                                 -1, wbuf, wlength) > 0
+                             ? true : false;
+        wbuffer = wbuf;
+        delete[] wbuf;
+        return success;
+      }
+      std::wstring getBuffer(const std::basic_string<char> buffer) {
+        return Encoding::ToWide(buffer);
+      }
+      std::wstring getBuffer(const std::basic_string<wchar_t> buffer) {
+        return buffer;
+      }
+      void setBuffer(const std::wstring wbuffer,
+                     std::basic_string<char> &target) {
+        target = Encoding::ToNarrow(wbuffer);
+      }
+      void setBuffer(const std::wstring wbuffer,
+                     std::basic_string<wchar_t> &target) {
+        target = wbuffer;
+      }
+
+  }; // BasicConsoleBuf class
+
+  typedef BasicConsoleBuf<char>    ConsoleBuf;
+  typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
+
+#endif
+} // KWSYS_NAMESPACE
+
+#endif
diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx
index c549792..15480e1 100644
--- a/Source/kwsys/Directory.cxx
+++ b/Source/kwsys/Directory.cxx
@@ -84,9 +84,9 @@ void Directory::Clear()
 
 } // namespace KWSYS_NAMESPACE
 
-// First microsoft compilers
+// First Windows platforms
 
-#if defined(_MSC_VER) || defined(__WATCOMC__)
+#if defined(_WIN32) && !defined(__CYGWIN__)
 #include <windows.h>
 #include <io.h>
 #include <ctype.h>
@@ -97,15 +97,25 @@ void Directory::Clear()
 #include <sys/stat.h>
 #include <sys/types.h>
 
+// Wide function names can vary depending on compiler:
+#ifdef __BORLANDC__
+# define _wfindfirst_func __wfindfirst
+# define _wfindnext_func __wfindnext
+#else
+# define _wfindfirst_func _wfindfirst
+# define _wfindnext_func _wfindnext
+#endif
+
 namespace KWSYS_NAMESPACE
 {
 
 bool Directory::Load(const std::string& name)
 {
   this->Clear();
-#if _MSC_VER < 1300
+#if (defined(_MSC_VER) && _MSC_VER < 1300) || defined(__BORLANDC__)
+  // Older Visual C++ and Embarcadero compilers.
   long srchHandle;
-#else
+#else // Newer Visual C++
   intptr_t srchHandle;
 #endif
   char* buf;
@@ -132,7 +142,7 @@ bool Directory::Load(const std::string& name)
   struct _wfinddata_t data;      // data of current file
 
   // Now put them into the file array
-  srchHandle = _wfindfirst((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+  srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
   delete [] buf;
 
   if ( srchHandle == -1 )
@@ -145,16 +155,17 @@ bool Directory::Load(const std::string& name)
     {
     this->Internal->Files.push_back(Encoding::ToNarrow(data.name));
     }
-  while ( _wfindnext(srchHandle, &data) != -1 );
+  while ( _wfindnext_func(srchHandle, &data) != -1 );
   this->Internal->Path = name;
   return _findclose(srchHandle) != -1;
 }
 
 unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
 {
-#if _MSC_VER < 1300
+#if (defined(_MSC_VER) && _MSC_VER < 1300) || defined(__BORLANDC__)
+  // Older Visual C++ and Embarcadero compilers.
   long srchHandle;
-#else
+#else // Newer Visual C++
   intptr_t srchHandle;
 #endif
   char* buf;
@@ -172,7 +183,7 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
   struct _wfinddata_t data;      // data of current file
 
   // Now put them into the file array
-  srchHandle = _wfindfirst((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+  srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
   delete [] buf;
 
   if ( srchHandle == -1 )
@@ -186,7 +197,7 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
     {
     count++;
     }
-  while ( _wfindnext(srchHandle, &data) != -1 );
+  while ( _wfindnext_func(srchHandle, &data) != -1 );
   _findclose(srchHandle);
   return count;
 }
diff --git a/Source/kwsys/FStream.hxx.in b/Source/kwsys/FStream.hxx.in
index 681e4d8..5471247 100644
--- a/Source/kwsys/FStream.hxx.in
+++ b/Source/kwsys/FStream.hxx.in
@@ -12,154 +12,248 @@
 #ifndef @KWSYS_NAMESPACE at _FStream_hxx
 #define @KWSYS_NAMESPACE at _FStream_hxx
 
+#include <@KWSYS_NAMESPACE@/Configure.hxx>
 #include <@KWSYS_NAMESPACE@/Encoding.hxx>
 #include <fstream>
+#if defined(_WIN32)
+# if !defined(_MSC_VER) && @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
+#  include <ext/stdio_filebuf.h>
+# endif
+#endif
 
 namespace @KWSYS_NAMESPACE@
 {
-#if defined(_MSC_VER) && _MSC_VER >= 1400
+#if defined(_WIN32) && (defined(_MSC_VER) || @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H)
 # if defined(_NOEXCEPT)
 #  define @KWSYS_NAMESPACE at _FStream_NOEXCEPT _NOEXCEPT
 # else
 #  define @KWSYS_NAMESPACE at _FStream_NOEXCEPT
 # endif
+
+#if defined(_MSC_VER)
+
   template<typename CharType,typename Traits>
   class basic_filebuf : public std::basic_filebuf<CharType,Traits>
   {
+# if _MSC_VER >= 1400
     public:
       typedef std::basic_filebuf<CharType,Traits> my_base_type;
       basic_filebuf *open(char const *s,std::ios_base::openmode mode)
       {
+        const std::wstring wstr = Encoding::ToWide(s);
         return static_cast<basic_filebuf*>(
-          my_base_type::open(Encoding::ToWide(s).c_str(), mode)
+          my_base_type::open(wstr.c_str(), mode)
           );
       }
+# endif
+  };
+
+#else
+
+  inline std::wstring getcmode(const std::ios_base::openmode mode) {
+    std::wstring cmode;
+    bool plus = false;
+    if (mode & std::ios_base::app) {
+      cmode += L"a";
+      plus = mode & std::ios_base::in ? true : false;
+    } else if (mode & std::ios_base::trunc ||
+                (mode & std::ios_base::out && (mode & std::ios_base::in) == 0)) {
+      cmode += L"w";
+      plus = mode & std::ios_base::in ? true : false;
+    } else {
+      cmode += L"r";
+      plus = mode & std::ios_base::out ? true : false;
+    }
+    if (plus) {
+      cmode += L"+";
+    }
+    if (mode & std::ios_base::binary) {
+      cmode += L"b";
+    } else {
+      cmode += L"t";
+    }
+    return cmode;
   };
 
+#endif
+
   template<typename CharType,typename Traits = std::char_traits<CharType> >
-  class basic_ifstream : public std::basic_istream<CharType,Traits>
+  class basic_efilebuf
   {
+    public:
+#if defined(_MSC_VER)
+      typedef basic_filebuf<CharType,Traits> internal_buffer_type;
+#else
+      typedef __gnu_cxx::stdio_filebuf<CharType,Traits> internal_buffer_type;
+#endif
+
+      basic_efilebuf() : file_(0)
+      {
+        buf_ = 0;
+      }
+
+      bool _open(char const *file_name,std::ios_base::openmode mode)
+      {
+        if (is_open() || file_) {
+          return false;
+        }
+#if defined(_MSC_VER)
+        const bool success = buf_->open(file_name,mode) != 0;
+#else
+        const std::wstring wstr = Encoding::ToWide(file_name);
+        bool success = false;
+        std::wstring cmode = getcmode(mode);
+        file_ = _wfopen(wstr.c_str(), cmode.c_str());
+        if (file_) {
+          if (buf_) {
+            delete buf_;
+          }
+          buf_ = new internal_buffer_type(file_, mode);
+          success = true;
+        }
+#endif
+        return success;
+      }
+
+      bool is_open()
+      {
+        if (!buf_) {
+          return false;
+        }
+        return buf_->is_open();
+      }
+
+      bool is_open() const
+      {
+        if (!buf_) {
+          return false;
+        }
+        return buf_->is_open();
+      }
+
+      bool _close()
+      {
+        bool success = false;
+        if (buf_) {
+          success = buf_->close() != 0;
+#if !defined(_MSC_VER)
+          if (file_) {
+            success = fclose(file_) == 0 ? success : false;
+            file_ = 0;
+          }
+#endif
+        }
+        return success;
+      }
+
+      static void _set_state(bool success, std::basic_ios<CharType,Traits> *ios, basic_efilebuf* efilebuf)
+      {
+#if !defined(_MSC_VER)
+        ios->rdbuf(efilebuf->buf_);
+#endif
+        if (!success) {
+          ios->setstate(std::ios_base::failbit);
+        } else {
+          ios->clear();
+        }
+      }
+
+      ~basic_efilebuf()
+     {
+       if (buf_) {
+         delete buf_;
+       }
+     }
+
+    protected:
+      internal_buffer_type* buf_;
+      FILE *file_;
+  };
+
+template<typename CharType,typename Traits = std::char_traits<CharType> >
+class basic_ifstream : public std::basic_istream<CharType,Traits>,
+                       public basic_efilebuf<CharType,Traits>
+{
+  using basic_efilebuf<CharType,Traits>::is_open;
+
   public:
-    typedef basic_filebuf<CharType,Traits> internal_buffer_type;
+    typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
     typedef std::basic_istream<CharType,Traits> internal_stream_type;
 
     basic_ifstream() : internal_stream_type(new internal_buffer_type())
     {
-      buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+      this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
     }
     explicit basic_ifstream(char const *file_name,
                             std::ios_base::openmode mode = std::ios_base::in)
       : internal_stream_type(new internal_buffer_type())
     {
-      buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+      this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
       open(file_name,mode);
     }
+
     void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::in)
     {
-      if(!buf_->open(file_name,mode | std::ios_base::in))
-        {
-        this->setstate(std::ios_base::failbit);
-        }
-      else
-        {
-        this->clear();
-        }
-    }
-    bool is_open()
-    {
-      return buf_->is_open();
-    }
-    bool is_open() const
-    {
-      return buf_->is_open();
+      mode = mode | std::ios_base::in;
+      this->_set_state(this->_open(file_name, mode), this, this);
     }
+
     void close()
     {
-      if(!buf_->close())
-        {
-        this->setstate(std::ios_base::failbit);
-        }
-      else
-      {
-        this->clear();
-      }
+      this->_set_state(this->_close(), this, this);
     }
 
     internal_buffer_type *rdbuf() const
     {
-      return buf_;
+      return this->buf_;
     }
 
     ~basic_ifstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT
     {
-      buf_->close();
-      delete buf_;
+      close();
     }
-
-  private:
-    internal_buffer_type* buf_;
 };
 
 template<typename CharType,typename Traits = std::char_traits<CharType> >
-class basic_ofstream : public std::basic_ostream<CharType,Traits>
+class basic_ofstream : public std::basic_ostream<CharType,Traits>,
+                       public basic_efilebuf<CharType,Traits>
 {
+  using basic_efilebuf<CharType,Traits>::is_open;
+
   public:
-  typedef basic_filebuf<CharType,Traits> internal_buffer_type;
+  typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
   typedef std::basic_ostream<CharType,Traits> internal_stream_type;
 
   basic_ofstream() : internal_stream_type(new internal_buffer_type())
   {
-  buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+    this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
   }
   explicit basic_ofstream(char const *file_name,std::ios_base::openmode mode = std::ios_base::out) :
   internal_stream_type(new internal_buffer_type())
   {
-    buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+    this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
     open(file_name,mode);
   }
   void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::out)
   {
-    if(!buf_->open(file_name,mode | std::ios_base::out))
-    {
-    this->setstate(std::ios_base::failbit);
-    }
-    else
-    {
-    this->clear();
-    }
-  }
-  bool is_open()
-  {
-    return buf_->is_open();
-  }
-  bool is_open() const
-  {
-    return buf_->is_open();
+    mode = mode | std::ios_base::out;
+    this->_set_state(this->_open(file_name, mode), this, this);
   }
+
   void close()
   {
-    if(!buf_->close())
-      {
-      this->setstate(std::ios_base::failbit);
-      }
-    else
-      {
-      this->clear();
-      }
+    this->_set_state(this->_close(), this, this);
   }
 
   internal_buffer_type *rdbuf() const
   {
-    return buf_.get();
+    return this->buf_;
   }
+
   ~basic_ofstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT
   {
-    buf_->close();
-    delete buf_;
+    close();
   }
-
-  private:
-  internal_buffer_type* buf_;
 };
 
   typedef basic_ifstream<char> ifstream;
diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx
index 81fb2f9..56a635a 100644
--- a/Source/kwsys/SystemInformation.cxx
+++ b/Source/kwsys/SystemInformation.cxx
@@ -79,9 +79,9 @@ typedef int siginfo_t;
 # undef _WIN32
 #endif
 
-#ifdef __FreeBSD__
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+# include <sys/param.h>
 # include <sys/sysctl.h>
-# include <fenv.h>
 # include <sys/socket.h>
 # include <netdb.h>
 # include <netinet/in.h>
@@ -91,19 +91,10 @@ typedef int siginfo_t;
 # endif
 #endif
 
-#if defined(__OpenBSD__) || defined(__NetBSD__)
-# include <sys/param.h>
-# include <sys/sysctl.h>
-#endif
-
 #if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
 # include <machine/cpu.h>
 #endif
 
-#if defined(__DragonFly__)
-# include <sys/sysctl.h>
-#endif
-
 #ifdef __APPLE__
 # include <sys/sysctl.h>
 # include <mach/vm_statistics.h>
@@ -123,7 +114,7 @@ typedef int siginfo_t;
 # endif
 #endif
 
-#ifdef __linux
+#if defined(__linux) || defined (__sun) || defined(_SCO_DS)
 # include <fenv.h>
 # include <sys/socket.h>
 # include <netdb.h>
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index c6e668d..5da715f 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -66,6 +66,10 @@
 #include <sys/stat.h>
 #include <time.h>
 
+#if defined(_WIN32) && !defined(_MSC_VER) && defined(__GNUC__)
+# include <strings.h> /* for strcasecmp */
+#endif
+
 #ifdef _MSC_VER
 # define umask _umask // Note this is still umask on Borland
 #endif
@@ -388,6 +392,72 @@ class SystemToolsTranslationMap :
 {
 };
 
+/* Type of character storing the environment.  */
+#if defined(_WIN32)
+typedef wchar_t envchar;
+#else
+typedef char envchar;
+#endif
+
+/* Order by environment key only (VAR from VAR=VALUE).  */
+struct kwsysEnvCompare
+{
+  bool operator() (const envchar* l, const envchar* r) const
+    {
+#if defined(_WIN32)
+    const wchar_t* leq = wcschr(l, L'=');
+    const wchar_t* req = wcschr(r, L'=');
+    size_t llen = leq? (leq-l) : wcslen(l);
+    size_t rlen = req? (req-r) : wcslen(r);
+    if(llen == rlen)
+      {
+      return wcsncmp(l,r,llen) < 0;
+      }
+    else
+      {
+      return wcscmp(l,r) < 0;
+      }
+#else
+    const char* leq = strchr(l, '=');
+    const char* req = strchr(r, '=');
+    size_t llen = leq? (leq-l) : strlen(l);
+    size_t rlen = req? (req-r) : strlen(r);
+    if(llen == rlen)
+      {
+      return strncmp(l,r,llen) < 0;
+      }
+    else
+      {
+      return strcmp(l,r) < 0;
+      }
+#endif
+    }
+};
+
+class kwsysEnvSet: public std::set<const envchar*, kwsysEnvCompare>
+{
+public:
+  class Free
+  {
+    const envchar* Env;
+  public:
+    Free(const envchar* env): Env(env) {}
+    ~Free() { free(const_cast<envchar*>(this->Env)); }
+  };
+
+  const envchar* Release(const envchar* env)
+    {
+    const envchar* old = 0;
+    iterator i = this->find(env);
+    if(i != this->end())
+      {
+      old = *i;
+      this->erase(i);
+      }
+    return old;
+    }
+};
+
 #ifdef _WIN32
 struct SystemToolsPathCaseCmp
 {
@@ -406,6 +476,9 @@ struct SystemToolsPathCaseCmp
 class SystemToolsPathCaseMap:
   public std::map<std::string, std::string,
                         SystemToolsPathCaseCmp> {};
+
+class SystemToolsEnvMap :
+    public std::map<std::string,std::string> {};
 #endif
 
 // adds the elements of the env variable path to the arg passed in
@@ -421,14 +494,12 @@ void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
     {
     env = "PATH";
     }
-  const char* cpathEnv = SystemTools::GetEnv(env);
-  if ( !cpathEnv )
+  std::string pathEnv;
+  if ( !SystemTools::GetEnv(env, pathEnv) )
     {
     return;
     }
 
-  std::string pathEnv = cpathEnv;
-
   // A hack to make the below algorithm work.
   if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
     {
@@ -456,28 +527,52 @@ void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
     }
 }
 
+const char* SystemTools::GetEnvImpl(const char* key)
+{
+  const char *v = 0;
+#if defined(_WIN32)
+  std::string env;
+  if (SystemTools::GetEnv(key, env))
+    {
+    std::string& menv = (*SystemTools::EnvMap)[key];
+    menv = env;
+    v = menv.c_str();
+    }
+#else
+  v = getenv(key);
+#endif
+  return v;
+}
+
 const char* SystemTools::GetEnv(const char* key)
 {
-  return getenv(key);
+  return SystemTools::GetEnvImpl(key);
 }
 
 const char* SystemTools::GetEnv(const std::string& key)
 {
-  return SystemTools::GetEnv(key.c_str());
+  return SystemTools::GetEnvImpl(key.c_str());
 }
 
 bool SystemTools::GetEnv(const char* key, std::string& result)
 {
+#if defined(_WIN32)
+  const std::wstring wkey = Encoding::ToWide(key);
+  const wchar_t* wv = _wgetenv(wkey.c_str());
+  if (wv)
+    {
+    result = Encoding::ToNarrow(wv);
+    return true;
+    }
+#else
   const char* v = getenv(key);
   if(v)
     {
     result = v;
     return true;
     }
-  else
-    {
-    return false;
-    }
+#endif
+  return false;
 }
 
 bool SystemTools::GetEnv(const std::string& key, std::string& result)
@@ -485,13 +580,23 @@ bool SystemTools::GetEnv(const std::string& key, std::string& result)
   return SystemTools::GetEnv(key.c_str(), result);
 }
 
-//----------------------------------------------------------------------------
-
-#if defined(__CYGWIN__) || defined(__GLIBC__)
-# define KWSYS_PUTENV_NAME  /* putenv("A")  removes A.  */
-#elif defined(_WIN32)
-# define KWSYS_PUTENV_EMPTY /* putenv("A=") removes A. */
+bool SystemTools::HasEnv(const char* key)
+{
+#if defined(_WIN32)
+  const std::wstring wkey = Encoding::ToWide(key);
+  const wchar_t* v = _wgetenv(wkey.c_str());
+#else
+  const char* v = getenv(key);
 #endif
+  return v != 0;
+}
+
+bool SystemTools::HasEnv(const std::string& key)
+{
+  return SystemTools::HasEnv(key.c_str());
+}
+
+//----------------------------------------------------------------------------
 
 #if KWSYS_CXX_HAS_UNSETENV
 /* unsetenv("A") removes A from the environment.
@@ -511,18 +616,15 @@ static int kwsysUnPutEnv(const std::string& env)
   return 0;
 }
 
-#elif defined(KWSYS_PUTENV_EMPTY) || defined(KWSYS_PUTENV_NAME)
-/* putenv("A=") or putenv("A") removes A from the environment.  */
+#elif defined(__CYGWIN__) || defined(__GLIBC__)
+/* putenv("A") removes A from the environment.  It must not put the
+   memory in the environment because it does not have any "=" syntax.  */
 static int kwsysUnPutEnv(const std::string& env)
 {
   int err = 0;
   size_t pos = env.find('=');
   size_t const len = pos == env.npos ? env.size() : pos;
-# ifdef KWSYS_PUTENV_EMPTY
-  size_t const sz = len + 2;
-# else
   size_t const sz = len + 1;
-# endif
   char local_buf[256];
   char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
   if(!buf)
@@ -530,20 +632,11 @@ static int kwsysUnPutEnv(const std::string& env)
     return -1;
     }
   strncpy(buf, env.c_str(), len);
-# ifdef KWSYS_PUTENV_EMPTY
-  buf[len] = '=';
-  buf[len+1] = 0;
-  if(putenv(buf) < 0)
-    {
-    err = errno;
-    }
-# else
   buf[len] = 0;
   if(putenv(buf) < 0 && errno != EINVAL)
     {
     err = errno;
     }
-# endif
   if(buf != local_buf)
     {
     free(buf);
@@ -556,6 +649,30 @@ static int kwsysUnPutEnv(const std::string& env)
   return 0;
 }
 
+#elif defined(_WIN32)
+/* putenv("A=") places "A=" in the environment, which is as close to
+   removal as we can get with the putenv API.  We have to leak the
+   most recent value placed in the environment for each variable name
+   on program exit in case exit routines access it.  */
+
+static kwsysEnvSet kwsysUnPutEnvSet;
+
+static int kwsysUnPutEnv(std::string const& env)
+{
+  std::wstring wEnv = Encoding::ToWide(env);
+  size_t const pos = wEnv.find('=');
+  size_t const len = pos == wEnv.npos ? wEnv.size() : pos;
+  wEnv.resize(len+1, L'=');
+  wchar_t* newEnv = _wcsdup(wEnv.c_str());
+  if(!newEnv)
+    {
+    return -1;
+    }
+  kwsysEnvSet::Free oldEnv(kwsysUnPutEnvSet.Release(newEnv));
+  kwsysUnPutEnvSet.insert(newEnv);
+  return _wputenv(newEnv);
+}
+
 #else
 /* Manipulate the "environ" global directly.  */
 static int kwsysUnPutEnv(const std::string& env)
@@ -623,68 +740,46 @@ bool SystemTools::UnPutEnv(const std::string& env)
 #  pragma warning disable 444 /* base has non-virtual destructor */
 # endif
 
-/* Order by environment key only (VAR from VAR=VALUE).  */
-struct kwsysEnvCompare
+class kwsysEnv: public kwsysEnvSet
 {
-  bool operator() (const char* l, const char* r) const
-    {
-    const char* leq = strchr(l, '=');
-    const char* req = strchr(r, '=');
-    size_t llen = leq? (leq-l) : strlen(l);
-    size_t rlen = req? (req-r) : strlen(r);
-    if(llen == rlen)
-      {
-      return strncmp(l,r,llen) < 0;
-      }
-    else
-      {
-      return strcmp(l,r) < 0;
-      }
-    }
-};
-
-class kwsysEnv: public std::set<const char*, kwsysEnvCompare>
-{
-  class Free
-  {
-    const char* Env;
-  public:
-    Free(const char* env): Env(env) {}
-    ~Free() { free(const_cast<char*>(this->Env)); }
-  };
 public:
-  typedef std::set<const char*, kwsysEnvCompare> derived;
   ~kwsysEnv()
     {
-    for(derived::iterator i = this->begin(); i != this->end(); ++i)
+    for(iterator i = this->begin(); i != this->end(); ++i)
       {
+#if defined(_WIN32)
+      const std::string s = Encoding::ToNarrow(*i);
+      kwsysUnPutEnv(s.c_str());
+#else
       kwsysUnPutEnv(*i);
-      free(const_cast<char*>(*i));
-      }
-    }
-  const char* Release(const char* env)
-    {
-    const char* old = 0;
-    derived::iterator i = this->find(env);
-    if(i != this->end())
-      {
-      old = *i;
-      this->erase(i);
+#endif
+      free(const_cast<envchar*>(*i));
       }
-    return old;
     }
   bool Put(const char* env)
     {
-    Free oldEnv(this->Release(env));
-    static_cast<void>(oldEnv);
+#if defined(_WIN32)
+    const std::wstring wEnv = Encoding::ToWide(env);
+    wchar_t* newEnv = _wcsdup(wEnv.c_str());
+#else
     char* newEnv = strdup(env);
+#endif
+    Free oldEnv(this->Release(newEnv));
     this->insert(newEnv);
+#if defined(_WIN32)
+    return _wputenv(newEnv) == 0;
+#else
     return putenv(newEnv) == 0;
+#endif
     }
   bool UnPut(const char* env)
     {
+#if defined(_WIN32)
+    const std::wstring wEnv = Encoding::ToWide(env);
+    Free oldEnv(this->Release(wEnv.c_str()));
+#else
     Free oldEnv(this->Release(env));
-    static_cast<void>(oldEnv);
+#endif
     return kwsysUnPutEnv(env) == 0;
     }
 };
@@ -1201,6 +1296,32 @@ bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
 }
 
 //----------------------------------------------------------------------------
+bool SystemTools::PathExists(const std::string& path)
+{
+  if(path.empty())
+    {
+    return false;
+    }
+#if defined(__CYGWIN__)
+  // Convert path to native windows path if possible.
+  char winpath[MAX_PATH];
+  if(SystemTools::PathCygwinToWin32(path.c_str(), winpath))
+    {
+    return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
+    }
+  struct stat st;
+  return lstat(path.c_str(), &st) == 0;
+#elif defined(_WIN32)
+  return (GetFileAttributesW(
+            SystemTools::ConvertToWindowsExtendedPath(path).c_str())
+          != INVALID_FILE_ATTRIBUTES);
+#else
+  struct stat st;
+  return lstat(path.c_str(), &st) == 0;
+#endif
+}
+
+//----------------------------------------------------------------------------
 bool SystemTools::FileExists(const char* filename)
 {
   if(!filename)
@@ -1230,8 +1351,13 @@ bool SystemTools::FileExists(const std::string& filename)
             SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
           != INVALID_FILE_ATTRIBUTES);
 #else
+// SCO OpenServer 5.0.7/3.2's command has 711 permission.
+#if defined(_SCO_DS)
+  return access(filename.c_str(), F_OK) == 0;
+#else
   return access(filename.c_str(), R_OK) == 0;
 #endif
+#endif
 }
 
 //----------------------------------------------------------------------------
@@ -2044,8 +2170,8 @@ void SystemTools::ConvertToUnixSlashes(std::string& path)
     pathCString = path.c_str();
     if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
       {
-      const char* homeEnv = SystemTools::GetEnv("HOME");
-      if (homeEnv)
+      std::string homeEnv;
+      if (SystemTools::GetEnv("HOME", homeEnv))
         {
         path.replace(0,1,homeEnv);
         }
@@ -2590,17 +2716,15 @@ unsigned long SystemTools::FileLength(const std::string& filename)
   return length;
 }
 
-int SystemTools::Strucmp(const char *s1, const char *s2)
+int SystemTools::Strucmp(const char* l, const char* r)
 {
-  // lifted from Graphvis http://www.graphviz.org
-  while ((*s1 != '\0')
-         && (tolower(*s1) == tolower(*s2)))
-    {
-      s1++;
-      s2++;
-    }
-
-  return tolower(*s1) - tolower(*s2);
+  int lc;
+  int rc;
+  do {
+    lc = tolower(*l++);
+    rc = tolower(*r++);
+  } while(lc == rc && lc);
+  return lc - rc;
 }
 
 // return file's modified time
@@ -3860,16 +3984,16 @@ std::string SystemTools::RelativePath(const std::string& local, const std::strin
 }
 
 #ifdef _WIN32
-static int GetCasePathName(const std::string & pathIn,
-                            std::string & casePath)
+static std::string GetCasePathName(std::string const& pathIn)
 {
+  std::string casePath;
   std::vector<std::string> path_components;
   SystemTools::SplitPath(pathIn, path_components);
   if(path_components[0].empty()) // First component always exists.
     {
     // Relative paths cannot be converted.
-    casePath = "";
-    return 0;
+    casePath = pathIn;
+    return casePath;
     }
 
   // Start with root component.
@@ -3893,38 +4017,45 @@ static int GetCasePathName(const std::string & pathIn,
     sep = "/";
     }
 
+  // Convert case of all components that exist.
+  bool converting = true;
   for(; idx < path_components.size(); idx++)
     {
     casePath += sep;
     sep = "/";
-    std::string test_str = casePath;
-    test_str += path_components[idx];
-
-    // If path component contains wildcards, we skip matching
-    // because these filenames are not allowed on windows,
-    // and we do not want to match a different file.
-    if(path_components[idx].find('*') != std::string::npos ||
-       path_components[idx].find('?') != std::string::npos)
-      {
-      casePath = "";
-      return 0;
-      }
 
-    WIN32_FIND_DATAW findData;
-    HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
-      &findData);
-    if (INVALID_HANDLE_VALUE != hFind)
-      {
-      casePath += Encoding::ToNarrow(findData.cFileName);
-      ::FindClose(hFind);
-      }
-    else
+    if (converting)
       {
-      casePath = "";
-      return 0;
+      // If path component contains wildcards, we skip matching
+      // because these filenames are not allowed on windows,
+      // and we do not want to match a different file.
+      if(path_components[idx].find('*') != std::string::npos ||
+         path_components[idx].find('?') != std::string::npos)
+        {
+        converting = false;
+        }
+      else
+        {
+        std::string test_str = casePath;
+        test_str += path_components[idx];
+        WIN32_FIND_DATAW findData;
+        HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
+          &findData);
+        if (INVALID_HANDLE_VALUE != hFind)
+          {
+          path_components[idx] = Encoding::ToNarrow(findData.cFileName);
+          ::FindClose(hFind);
+          }
+        else
+          {
+          converting = false;
+          }
+        }
       }
+
+    casePath += path_components[idx];
     }
-  return (int)casePath.size();
+  return casePath;
 }
 #endif
 
@@ -3943,11 +4074,10 @@ std::string SystemTools::GetActualCaseForPath(const std::string& p)
     {
     return i->second;
     }
-  std::string casePath;
-  int len = GetCasePathName(p, casePath);
-  if(len == 0 || len > MAX_PATH+1)
+  std::string casePath = GetCasePathName(p);
+  if (casePath.size() > MAX_PATH)
     {
-    return p;
+    return casePath;
     }
   (*SystemTools::PathCaseMap)[p] = casePath;
   return casePath;
@@ -4061,16 +4191,9 @@ void SystemTools::SplitPath(const std::string& p,
     if(root.size() == 1)
       {
 #if defined(_WIN32) && !defined(__CYGWIN__)
-      if(const char* userp = getenv("USERPROFILE"))
-        {
-        homedir = userp;
-        }
-      else
+      if (!SystemTools::GetEnv("USERPROFILE", homedir))
 #endif
-      if(const char* h = getenv("HOME"))
-        {
-        homedir = h;
-        }
+      SystemTools::GetEnv("HOME", homedir);
       }
 #ifdef HAVE_GETPWNAM
     else if(passwd* pw = getpwnam(root.c_str()+1))
@@ -4610,8 +4733,11 @@ bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
   std::wstring wtempPath = Encoding::ToWide(tempPath);
   DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0);
   std::vector<wchar_t> buffer(ret);
-  ret = GetShortPathNameW(wtempPath.c_str(),
-                          &buffer[0], static_cast<DWORD>(buffer.size()));
+  if (ret != 0)
+    {
+    ret = GetShortPathNameW(wtempPath.c_str(),
+                            &buffer[0], static_cast<DWORD>(buffer.size()));
+    }
 
   if (ret == 0)
     {
@@ -4811,7 +4937,7 @@ int SystemTools::GetTerminalWidth()
   int width = -1;
 #ifdef HAVE_TTY_INFO
   struct winsize ws;
-  char *columns; /* Unix98 environment variable */
+  std::string columns; /* Unix98 environment variable */
   if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
     {
     width = ws.ws_col;
@@ -4820,12 +4946,11 @@ int SystemTools::GetTerminalWidth()
     {
     width = -1;
     }
-  columns = getenv("COLUMNS");
-  if(columns && *columns)
+  if(SystemTools::GetEnv("COLUMNS", columns) && !columns.empty())
     {
     long t;
     char *endptr;
-    t = strtol(columns, &endptr, 0);
+    t = strtol(columns.c_str(), &endptr, 0);
     if(endptr && !*endptr && (t>0) && (t<1000))
       {
       width = static_cast<int>(t);
@@ -5371,6 +5496,7 @@ static unsigned int SystemToolsManagerCount;
 SystemToolsTranslationMap *SystemTools::TranslationMap;
 #ifdef _WIN32
 SystemToolsPathCaseMap *SystemTools::PathCaseMap;
+SystemToolsEnvMap *SystemTools::EnvMap;
 #endif
 #ifdef __CYGWIN__
 SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
@@ -5421,6 +5547,7 @@ void SystemTools::ClassInitialize()
   SystemTools::TranslationMap = new SystemToolsTranslationMap;
 #ifdef _WIN32
   SystemTools::PathCaseMap = new SystemToolsPathCaseMap;
+  SystemTools::EnvMap = new SystemToolsEnvMap;
 #endif
 #ifdef __CYGWIN__
   SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
@@ -5435,7 +5562,8 @@ void SystemTools::ClassInitialize()
 
   // If the current working directory is a logical path then keep the
   // logical name.
-  if(const char* pwd = getenv("PWD"))
+  std::string pwd_str;
+  if(SystemTools::GetEnv("PWD", pwd_str))
     {
     char buf[2048];
     if(const char* cwd = Getcwd(buf, 2048))
@@ -5447,10 +5575,9 @@ void SystemTools::ClassInitialize()
       std::string pwd_changed;
 
       // Test progressively shorter logical-to-physical mappings.
-      std::string pwd_str = pwd;
       std::string cwd_str = cwd;
       std::string pwd_path;
-      Realpath(pwd, pwd_path);
+      Realpath(pwd_str.c_str(), pwd_path);
       while(cwd_str == pwd_path && cwd_str != pwd_str)
         {
         // The current pair of paths is a working logical mapping.
@@ -5480,6 +5607,7 @@ void SystemTools::ClassFinalize()
   delete SystemTools::TranslationMap;
 #ifdef _WIN32
   delete SystemTools::PathCaseMap;
+  delete SystemTools::EnvMap;
 #endif
 #ifdef __CYGWIN__
   delete SystemTools::Cyg2Win32Map;
@@ -5505,8 +5633,8 @@ static int SystemToolsDebugReport(int, char* message, int*)
 
 void SystemTools::EnableMSVCDebugHook()
 {
-  if (getenv("DART_TEST_FROM_DART") ||
-      getenv("DASHBOARD_TEST_FROM_CTEST"))
+  if (SystemTools::HasEnv("DART_TEST_FROM_DART") ||
+      SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST"))
     {
     _CrtSetReportHook(SystemToolsDebugReport);
     }
diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in
index bba5a5c..5849145 100644
--- a/Source/kwsys/SystemTools.hxx.in
+++ b/Source/kwsys/SystemTools.hxx.in
@@ -53,6 +53,7 @@ namespace @KWSYS_NAMESPACE@
 
 class SystemToolsTranslationMap;
 class SystemToolsPathCaseMap;
+class SystemToolsEnvMap;
 
 /** \class SystemToolsManager
  * \brief Use to make sure SystemTools is initialized before it is used
@@ -305,6 +306,11 @@ public:
   static std::string ConvertToWindowsOutputPath(const std::string&);
 
   /**
+   * Return true if a path with the given name exists in the current directory.
+   */
+  static bool PathExists(const std::string& path);
+
+  /**
    * Return true if a file exists in the current directory.
    * If isFile = true, then make sure the file is a file and
    * not a directory.  If isFile = false, then return true
@@ -368,10 +374,11 @@ public:
   static const char* GetExecutableExtension();
 
   /**
-   *  Given a path that exists on a windows machine, return the
-   *  actuall case of the path as it was created.  If the file
-   *  does not exist path is returned unchanged.  This does nothing
-   *  on unix but return path.
+   * Given a path on a Windows machine, return the actual case of
+   * the path as it exists on disk.  Path components that do not
+   * exist on disk are returned unchanged.  Relative paths are always
+   * returned unchanged.  Drive letters are always made upper case.
+   * This does nothing on non-Windows systems but return the path.
    */
   static std::string GetActualCaseForPath(const std::string& path);
 
@@ -843,6 +850,8 @@ public:
   static const char* GetEnv(const std::string& key);
   static bool GetEnv(const char* key, std::string& result);
   static bool GetEnv(const std::string& key, std::string& result);
+  static bool HasEnv(const char* key);
+  static bool HasEnv(const std::string& key);
 
   /** Put a string into the environment
       of the form var=value */
@@ -981,6 +990,7 @@ private:
     std::vector<std::string>(),
     bool no_system_path = false);
 
+  static const char* GetEnvImpl(const char* key);
 
   /**
    * Path translation table from dir to refdir
@@ -989,6 +999,7 @@ private:
   static SystemToolsTranslationMap *TranslationMap;
 #ifdef _WIN32
   static SystemToolsPathCaseMap *PathCaseMap;
+  static SystemToolsEnvMap *EnvMap;
 #endif
 #ifdef __CYGWIN__
   static SystemToolsTranslationMap *Cyg2Win32Map;
diff --git a/Source/kwsys/auto_ptr.hxx.in b/Source/kwsys/auto_ptr.hxx.in
deleted file mode 100644
index ad9654c..0000000
--- a/Source/kwsys/auto_ptr.hxx.in
+++ /dev/null
@@ -1,219 +0,0 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#ifndef @KWSYS_NAMESPACE at _auto_ptr_hxx
-#define @KWSYS_NAMESPACE at _auto_ptr_hxx
-
-#include <@KWSYS_NAMESPACE@/Configure.hxx>
-
-// The HP compiler and VS6 cannot handle the conversions necessary to use
-// auto_ptr_ref to pass an auto_ptr returned from one function
-// directly to another function as in use_auto_ptr(get_auto_ptr()).
-// We instead use const_cast to achieve the syntax on those platforms.
-// We do not use const_cast on other platforms to maintain the C++
-// standard design and guarantee that if an auto_ptr is bound
-// to a reference-to-const then ownership will be maintained.
-#if defined(__HP_aCC) || (defined(_MSC_VER) && _MSC_VER <= 1200)
-# define @KWSYS_NAMESPACE at _AUTO_PTR_REF 0
-# define @KWSYS_NAMESPACE at _AUTO_PTR_CONST const
-# define @KWSYS_NAMESPACE at _AUTO_PTR_CAST(a) cast(a)
-#else
-# define @KWSYS_NAMESPACE at _AUTO_PTR_REF 1
-# define @KWSYS_NAMESPACE at _AUTO_PTR_CONST
-# define @KWSYS_NAMESPACE at _AUTO_PTR_CAST(a) a
-#endif
-
-// In C++11, clang will warn about using dynamic exception specifications
-// as they are deprecated.  But as this class is trying to faithfully
-// mimic std::auto_ptr, we want to keep the 'throw()' decorations below.
-// So we suppress the warning.
-#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-#  pragma clang diagnostic push
-#  pragma clang diagnostic ignored "-Wdeprecated"
-# endif
-#endif
-
-namespace @KWSYS_NAMESPACE@
-{
-
-template <class X> class auto_ptr;
-
-#if @KWSYS_NAMESPACE at _AUTO_PTR_REF
-namespace detail
-{
-// The auto_ptr_ref template is supposed to be a private member of
-// auto_ptr but Borland 5.8 cannot handle it.  Instead put it in
-// a private namespace.
-template <class Y> struct auto_ptr_ref
-{
-  Y* p_;
-
-  // The extra constructor argument prevents implicit conversion to
-  // auto_ptr_ref from auto_ptr through the constructor.  Normally
-  // this should be done with the explicit keyword but Borland 5.x
-  // generates code in the conversion operator to call itself
-  // infinately.
-  auto_ptr_ref(Y* p, int): p_(p) {}
-};
-}
-#endif
-
-/** C++98 Standard Section 20.4.5 - Template class auto_ptr.  */
-template <class X>
-class auto_ptr
-{
-#if !@KWSYS_NAMESPACE at _AUTO_PTR_REF
-  template <typename Y>
-  static inline auto_ptr<Y>& cast(auto_ptr<Y> const& a)
-    { return const_cast<auto_ptr<Y>&>(a); }
-#endif
-
-  /** The pointer to the object held.  */
-  X* x_;
-
-public:
-  /** The type of object held by the auto_ptr.  */
-  typedef X element_type;
-
-  /** Construct from an auto_ptr holding a compatible object.  This
-      transfers ownership to the newly constructed auto_ptr.  */
-  template <class Y>
-  auto_ptr(auto_ptr<Y> @KWSYS_NAMESPACE at _AUTO_PTR_CONST& a) throw():
-    x_(@KWSYS_NAMESPACE at _AUTO_PTR_CAST(a).release())
-    {
-    }
-
-  /** Assign from an auto_ptr holding a compatible object.  This
-      transfers ownership to the left-hand-side of the assignment.  */
-  template <class Y>
-  auto_ptr& operator=(auto_ptr<Y> @KWSYS_NAMESPACE at _AUTO_PTR_CONST& a) throw()
-    {
-    this->reset(@KWSYS_NAMESPACE at _AUTO_PTR_CAST(a).release());
-    return *this;
-    }
-
-  /**
-   * Explicitly construct from a raw pointer.  This is typically
-   * called with the result of operator new.  For example:
-   *
-   *   auto_ptr<X> ptr(new X());
-   */
-  explicit auto_ptr(X* p=0) throw(): x_(p)
-    {
-    }
-
-  /** Construct from another auto_ptr holding an object of the same
-      type.  This transfers ownership to the newly constructed
-      auto_ptr.  */
-  auto_ptr(auto_ptr @KWSYS_NAMESPACE at _AUTO_PTR_CONST& a) throw():
-    x_(@KWSYS_NAMESPACE at _AUTO_PTR_CAST(a).release())
-    {
-    }
-
-  /** Assign from another auto_ptr holding an object of the same type.
-      This transfers ownership to the newly constructed auto_ptr.  */
-  auto_ptr& operator=(auto_ptr @KWSYS_NAMESPACE at _AUTO_PTR_CONST& a) throw()
-    {
-    this->reset(@KWSYS_NAMESPACE at _AUTO_PTR_CAST(a).release());
-    return *this;
-    }
-
-  /** Destruct and delete the object held.  */
-  ~auto_ptr() throw()
-    {
-    // Assume object destructor is nothrow.
-    delete this->x_;
-    }
-
-  /** Dereference and return a reference to the object held.  */
-  X& operator*() const throw()
-    {
-    return *this->x_;
-    }
-
-  /** Return a pointer to the object held.  */
-  X* operator->() const throw()
-    {
-    return this->x_;
-    }
-
-  /** Return a pointer to the object held.  */
-  X* get() const throw()
-    {
-    return this->x_;
-    }
-
-  /** Return a pointer to the object held and reset to hold no object.
-      This transfers ownership to the caller.  */
-  X* release() throw()
-    {
-    X* x = this->x_;
-    this->x_ = 0;
-    return x;
-    }
-
-  /** Assume ownership of the given object.  The object previously
-      held is deleted.  */
-  void reset(X* p=0) throw()
-    {
-    if(this->x_ != p)
-      {
-      // Assume object destructor is nothrow.
-      delete this->x_;
-      this->x_ = p;
-      }
-    }
-
-  /** Convert to an auto_ptr holding an object of a compatible type.
-      This transfers ownership to the returned auto_ptr.  */
-  template <class Y> operator auto_ptr<Y>() throw()
-    {
-    return auto_ptr<Y>(this->release());
-    }
-
-#if @KWSYS_NAMESPACE at _AUTO_PTR_REF
-  /** Construct from an auto_ptr_ref.  This is used when the
-      constructor argument is a call to a function returning an
-      auto_ptr.  */
-  auto_ptr(detail::auto_ptr_ref<X> r) throw(): x_(r.p_)
-    {
-    }
-
-  /** Assign from an auto_ptr_ref.  This is used when a function
-      returning an auto_ptr is passed on the right-hand-side of an
-      assignment.  */
-  auto_ptr& operator=(detail::auto_ptr_ref<X> r) throw()
-    {
-    this->reset(r.p_);
-    return *this;
-    }
-
-  /** Convert to an auto_ptr_ref.  This is used when a function
-      returning an auto_ptr is the argument to the constructor of
-      another auto_ptr.  */
-  template <class Y> operator detail::auto_ptr_ref<Y>() throw()
-    {
-    return detail::auto_ptr_ref<Y>(this->release(), 1);
-    }
-#endif
-};
-
-} // namespace @KWSYS_NAMESPACE@
-
-// Undo warning suppression.
-#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-#  pragma clang diagnostic pop
-# endif
-#endif
-
-#endif
diff --git a/Source/kwsys/kwsysPlatformTestsCXX.cxx b/Source/kwsys/kwsysPlatformTestsCXX.cxx
index fc87f91..b35808b 100644
--- a/Source/kwsys/kwsysPlatformTestsCXX.cxx
+++ b/Source/kwsys/kwsysPlatformTestsCXX.cxx
@@ -349,3 +349,8 @@ int main()
 void f(std ::wstring*) {}
 int main() { return 0; }
 #endif
+
+#ifdef TEST_KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H
+#include <ext/stdio_filebuf.h>
+int main() { return 0; }
+#endif
diff --git a/Source/kwsys/testAutoPtr.cxx b/Source/kwsys/testAutoPtr.cxx
deleted file mode 100644
index ed75ff4..0000000
--- a/Source/kwsys/testAutoPtr.cxx
+++ /dev/null
@@ -1,166 +0,0 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#ifdef __BORLANDC__
-# pragma warn -8027 /* 'for' not inlined.  */
-# pragma warn -8026 /* exception not inlined.  */
-#endif 
-#include "kwsysPrivate.h"
-#include KWSYS_HEADER(auto_ptr.hxx)
-// Work-around CMake dependency scanning limitation.  This must
-// duplicate the above list of headers.
-#if 0
-# include "auto_ptr.hxx.in"
-#endif
-
-#include <stdio.h>
-
-#define ASSERT(x,y) if (!(x)) { printf("FAIL: " y "\n"); status = 1; }
-
-int instances = 0; // don't declare as static
-
-struct A
-{
-  A() { ++instances; }
-  ~A() { --instances; }
-  A* self() {return this; }
-};
-struct B: public A {};
-
-static int function_call(kwsys::auto_ptr<A> a)
-{
-  return a.get()? 1:0;
-}
-
-static A* get_A(A& a) { return &a; }
-
-static kwsys::auto_ptr<A> generate_auto_ptr_A()
-{
-  return kwsys::auto_ptr<A>(new A);
-}
-
-static kwsys::auto_ptr<B> generate_auto_ptr_B()
-{
-  return kwsys::auto_ptr<B>(new B);
-}
-
-int testAutoPtr(int, char*[])
-{
-  int status = 0;
-
-  // Keep everything in a subscope so we can detect leaks.
-  {
-    kwsys::auto_ptr<A> pa0;
-    kwsys::auto_ptr<A> pa1(new A());
-    kwsys::auto_ptr<B> pb1(new B());
-    kwsys::auto_ptr<B> pb2(new B());
-    kwsys::auto_ptr<A> pa2(new B());
-
-    A* ptr = get_A(*pa1);
-    ASSERT(ptr == pa1.get(),
-          "auto_ptr does not return correct object when dereferenced");
-    ptr = pa1->self();
-    ASSERT(ptr == pa1.get(),
-          "auto_ptr does not return correct pointer from operator->");
-
-    A* before = pa0.get();
-    pa0.reset(new A());
-    ASSERT(pa0.get() && pa0.get() != before,
-          "auto_ptr empty after reset(new A())");
-
-    before = pa0.get();
-    pa0.reset(new B());
-    ASSERT(pa0.get() && pa0.get() != before,
-          "auto_ptr empty after reset(new B())");
-
-    delete pa0.release();
-    ASSERT(!pa0.get(), "auto_ptr holds an object after release()");
-
-    kwsys::auto_ptr<A> pa3(pb1);
-    ASSERT(!pb1.get(),
-           "auto_ptr full after being used to construct another");
-    ASSERT(pa3.get(),
-          "auto_ptr empty after construction from another");
-
-    {
-    kwsys::auto_ptr<A> pa;
-    pa = pa3;
-    ASSERT(!pa3.get(),
-           "auto_ptr full after assignment to another");
-    ASSERT(pa.get(),
-          "auto_ptr empty after assignment from another");
-    }
-
-    {
-    kwsys::auto_ptr<A> pa;
-    pa = pb2;
-    ASSERT(!pb2.get(),
-           "auto_ptr full after assignment to compatible");
-    ASSERT(pa.get(),
-          "auto_ptr empty after assignment from compatible");
-    }
-
-    {
-    int receive = function_call(pa2);
-    ASSERT(receive,
-           "auto_ptr did not receive ownership in called function");
-    ASSERT(!pa2.get(),
-           "auto_ptr did not release ownership to called function");
-    }
-
-    {
-    int received = function_call(generate_auto_ptr_A());
-    ASSERT(received,
-           "auto_ptr in called function did not take ownership "
-           "from factory function");
-    }
-
-#if 0
-    // Is this allowed by the standard?
-    {
-    int received = function_call(generate_auto_ptr_B());
-    ASSERT(received,
-           "auto_ptr in called function did not take ownership "
-           "from factory function with conversion");
-    }
-#endif
-
-    {
-    kwsys::auto_ptr<A> pa(generate_auto_ptr_A());
-    ASSERT(pa.get(),
-      "auto_ptr empty after construction from factory function");
-    }
-
-    {
-    kwsys::auto_ptr<A> pa;
-    pa = generate_auto_ptr_A();
-    ASSERT(pa.get(),
-      "auto_ptr empty after assignment from factory function");
-    }
-
-    {
-    kwsys::auto_ptr<A> pa(generate_auto_ptr_B());
-    ASSERT(pa.get(),
-      "auto_ptr empty after construction from compatible factory function");
-    }
-
-    {
-    kwsys::auto_ptr<A> pa;
-    pa = generate_auto_ptr_B();
-    ASSERT(pa.get(),
-      "auto_ptr empty after assignment from compatible factory function");
-    }
-  }
-
-  ASSERT(instances == 0, "auto_ptr leaked an object");
-
-  return status;
-}
diff --git a/Source/kwsys/testConsoleBuf.cxx b/Source/kwsys/testConsoleBuf.cxx
new file mode 100644
index 0000000..d7775e6
--- /dev/null
+++ b/Source/kwsys/testConsoleBuf.cxx
@@ -0,0 +1,719 @@
+/*============================================================================
+  KWSys - Kitware System Library
+  Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#include "kwsysPrivate.h"
+
+// Ignore Windows version levels defined by command-line flags.  This
+// source needs access to all APIs available on the host in order for
+// the test to run properly.  The test binary is not installed anyway.
+#undef _WIN32_WINNT
+#undef NTDDI_VERSION
+
+#include KWSYS_HEADER(Encoding.hxx)
+
+// Work-around CMake dependency scanning limitation.  This must
+// duplicate the above list of headers.
+#if 0
+# include "Encoding.hxx.in"
+#endif
+
+#if defined(_WIN32)
+
+#include <windows.h>
+#include <string.h>
+#include <wchar.h>
+#include <iostream>
+#include <iomanip>
+#include <stdexcept>
+#include "testConsoleBuf.hxx"
+
+#if defined(_MSC_VER) && _MSC_VER >= 1800
+# define KWSYS_WINDOWS_DEPRECATED_GetVersion
+#endif
+// يونيكود
+static const WCHAR UnicodeInputTestString[] = L"\u064A\u0648\u0646\u064A\u0643\u0648\u062F!";
+static UINT TestCodepage = KWSYS_ENCODING_DEFAULT_CODEPAGE;
+
+static const DWORD waitTimeout = 10 * 1000;
+static STARTUPINFO startupInfo;
+static PROCESS_INFORMATION processInfo;
+static HANDLE beforeInputEvent;
+static HANDLE afterOutputEvent;
+static std::string encodedInputTestString;
+static std::string encodedTestString;
+
+static void displayError(DWORD errorCode) {
+  std::cerr.setf(std::ios::hex, std::ios::basefield);
+  std::cerr << "Failed with error: 0x" << errorCode << "!" << std::endl;
+  LPWSTR message;
+  if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+                     NULL,
+                     errorCode,
+                     0,
+                     (LPWSTR)&message, 0,
+                     NULL)
+  ) {
+    std::cerr << "Error message: " << kwsys::Encoding::ToNarrow(message) << std::endl;
+    HeapFree(GetProcessHeap(), 0, message);
+  } else {
+    std::cerr << "FormatMessage() failed with error: 0x" << GetLastError() << "!" << std::endl;
+  }
+  std::cerr.unsetf(std::ios::hex);
+}
+
+std::basic_streambuf<char> *errstream(const char *unused) {
+  static_cast<void>(unused);
+  return std::cerr.rdbuf();
+}
+
+std::basic_streambuf<wchar_t> *errstream(const wchar_t *unused) {
+  static_cast<void>(unused);
+  return std::wcerr.rdbuf();
+}
+
+//----------------------------------------------------------------------------
+template<typename T>
+static void dumpBuffers(const T *expected, const T *received, size_t size) {
+  std::basic_ostream<T> err(errstream(expected));
+  err << "Expected output: '" << std::basic_string<T>(expected, size) << "'" << std::endl;
+  if (err.fail()) {
+    err.clear();
+    err << "--- Error while outputting ---" << std::endl;
+  }
+  err << "Received output: '" << std::basic_string<T>(received, size) << "'" << std::endl;
+  if (err.fail()) {
+    err.clear();
+    err << "--- Error while outputting ---" << std::endl;
+  }
+  std::cerr << "Expected output | Received output" << std::endl;
+  for (size_t i = 0; i < size; i++) {
+    std::cerr << std::setbase(16) << std::setfill('0') << "     " <<
+    "0x" << std::setw(8) << static_cast<unsigned int>(expected[i]) << " | " <<
+    "0x" << std::setw(8) << static_cast<unsigned int>(received[i]);
+    if (static_cast<unsigned int>(expected[i]) != static_cast<unsigned int>(received[i])) {
+      std::cerr << "   MISMATCH!";
+    }
+    std::cerr << std::endl;
+  }
+  std::cerr << std::endl;
+}
+
+//----------------------------------------------------------------------------
+static bool createProcess(HANDLE hIn, HANDLE hOut, HANDLE hErr)
+{
+  BOOL bInheritHandles = FALSE;
+  DWORD dwCreationFlags = 0;
+  memset(&processInfo, 0, sizeof(processInfo));
+  memset(&startupInfo, 0, sizeof(startupInfo));
+  startupInfo.cb = sizeof(startupInfo);
+  startupInfo.dwFlags = STARTF_USESHOWWINDOW;
+  startupInfo.wShowWindow = SW_HIDE;
+  if (hIn || hOut || hErr) {
+    startupInfo.dwFlags |= STARTF_USESTDHANDLES;
+    startupInfo.hStdInput = hIn;
+    startupInfo.hStdOutput = hOut;
+    startupInfo.hStdError = hErr;
+    bInheritHandles = TRUE;
+  }
+
+  WCHAR cmd[MAX_PATH];
+  if (GetModuleFileNameW(NULL, cmd, MAX_PATH) == 0) {
+    std::cerr << "GetModuleFileName failed!" << std::endl;
+    return false;
+  }
+  WCHAR *p = cmd + wcslen(cmd);
+  while (p > cmd && *p != L'\\') p--;
+  *(p+1) = 0;
+  wcscat(cmd, cmdConsoleBufChild);
+  wcscat(cmd, L".exe");
+
+  bool success = CreateProcessW(NULL,             // No module name (use command line)
+                                cmd,              // Command line
+                                NULL,             // Process handle not inheritable
+                                NULL,             // Thread handle not inheritable
+                                bInheritHandles,  // Set handle inheritance
+                                dwCreationFlags,
+                                NULL,             // Use parent's environment block
+                                NULL,             // Use parent's starting directory
+                                &startupInfo,     // Pointer to STARTUPINFO structure
+                                &processInfo) != 0; // Pointer to PROCESS_INFORMATION structure
+  if (!success) {
+    DWORD lastError = GetLastError();
+    std::cerr << "CreateProcess(" << kwsys::Encoding::ToNarrow(cmd) << ")" << std::endl;
+    displayError(lastError);
+  }
+  return success;
+}
+
+//----------------------------------------------------------------------------
+static void finishProcess(bool success)
+{
+  if (success) {
+    success = WaitForSingleObject(processInfo.hProcess, waitTimeout)
+              == WAIT_OBJECT_0;
+  };
+  if (!success) {
+    TerminateProcess(processInfo.hProcess, 1);
+  }
+  CloseHandle(processInfo.hProcess);
+  CloseHandle(processInfo.hThread);
+}
+
+//----------------------------------------------------------------------------
+static bool createPipe(PHANDLE readPipe, PHANDLE writePipe)
+{
+  SECURITY_ATTRIBUTES securityAttributes;
+  securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
+  securityAttributes.bInheritHandle = TRUE;
+  securityAttributes.lpSecurityDescriptor = NULL;
+  return CreatePipe(readPipe, writePipe, &securityAttributes, 0) == 0
+         ? false : true;
+}
+
+//----------------------------------------------------------------------------
+static void finishPipe(HANDLE readPipe, HANDLE writePipe)
+{
+  if (readPipe != INVALID_HANDLE_VALUE) {
+    CloseHandle(readPipe);
+  }
+  if (writePipe != INVALID_HANDLE_VALUE) {
+    CloseHandle(writePipe);
+  }
+}
+
+//----------------------------------------------------------------------------
+static HANDLE createFile(LPCWSTR fileName)
+{
+  SECURITY_ATTRIBUTES securityAttributes;
+  securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
+  securityAttributes.bInheritHandle = TRUE;
+  securityAttributes.lpSecurityDescriptor = NULL;
+
+  HANDLE file = CreateFileW(fileName,
+                            GENERIC_READ | GENERIC_WRITE,
+                            0,                    // do not share
+                            &securityAttributes,
+                            CREATE_ALWAYS,        // overwrite existing
+                            FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
+                            NULL);                // no template
+  if (file == INVALID_HANDLE_VALUE) {
+    DWORD lastError = GetLastError();
+    std::cerr << "CreateFile(" << kwsys::Encoding::ToNarrow(fileName) << ")" << std::endl;
+    displayError(lastError);
+  }
+  return file;
+}
+
+//----------------------------------------------------------------------------
+static void finishFile(HANDLE file)
+{
+  if (file != INVALID_HANDLE_VALUE) {
+    CloseHandle(file);
+  }
+}
+
+//----------------------------------------------------------------------------
+
+#ifndef MAPVK_VK_TO_VSC
+#  define MAPVK_VK_TO_VSC  (0)
+#endif
+
+static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
+{
+  inputBuffer[0].EventType = KEY_EVENT;
+  inputBuffer[0].Event.KeyEvent.bKeyDown = TRUE;
+  inputBuffer[0].Event.KeyEvent.wRepeatCount = 1;
+  SHORT keyCode = VkKeyScanW(chr);
+  if (keyCode == -1) {
+    // Character can't be entered with current keyboard layout
+    // Just set any, it doesn't really matter
+    keyCode = 'K';
+  }
+  inputBuffer[0].Event.KeyEvent.wVirtualKeyCode = LOBYTE(keyCode);
+  inputBuffer[0].Event.KeyEvent.wVirtualScanCode =
+      MapVirtualKey(inputBuffer[0].Event.KeyEvent.wVirtualKeyCode,
+                    MAPVK_VK_TO_VSC);
+  inputBuffer[0].Event.KeyEvent.uChar.UnicodeChar = chr;
+  inputBuffer[0].Event.KeyEvent.dwControlKeyState = 0;
+  if ((HIBYTE(keyCode) & 1) == 1) {
+    inputBuffer[0].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
+  }
+  if ((HIBYTE(keyCode) & 2) == 2) {
+    inputBuffer[0].Event.KeyEvent.dwControlKeyState |= RIGHT_CTRL_PRESSED;
+  }
+  if ((HIBYTE(keyCode) & 4) == 4) {
+    inputBuffer[0].Event.KeyEvent.dwControlKeyState |= RIGHT_ALT_PRESSED;
+  }
+  inputBuffer[1].EventType = inputBuffer[0].EventType;
+  inputBuffer[1].Event.KeyEvent.bKeyDown = FALSE;
+  inputBuffer[1].Event.KeyEvent.wRepeatCount = 1;
+  inputBuffer[1].Event.KeyEvent.wVirtualKeyCode   = inputBuffer[0].Event.
+                                                      KeyEvent.wVirtualKeyCode;
+  inputBuffer[1].Event.KeyEvent.wVirtualScanCode  = inputBuffer[0].Event.
+                                                      KeyEvent.wVirtualScanCode;
+  inputBuffer[1].Event.KeyEvent.uChar.UnicodeChar = inputBuffer[0].Event.
+                                                      KeyEvent.uChar.UnicodeChar;
+  inputBuffer[1].Event.KeyEvent.dwControlKeyState = 0;
+}
+
+//----------------------------------------------------------------------------
+static int testPipe()
+{
+  int didFail = 1;
+  HANDLE inPipeRead = INVALID_HANDLE_VALUE;
+  HANDLE inPipeWrite = INVALID_HANDLE_VALUE;
+  HANDLE outPipeRead = INVALID_HANDLE_VALUE;
+  HANDLE outPipeWrite = INVALID_HANDLE_VALUE;
+  HANDLE errPipeRead = INVALID_HANDLE_VALUE;
+  HANDLE errPipeWrite = INVALID_HANDLE_VALUE;
+  UINT currentCodepage = GetConsoleCP();
+  char buffer[200];
+  char buffer2[200];
+  try {
+    if (!createPipe(&inPipeRead, &inPipeWrite) ||
+        !createPipe(&outPipeRead, &outPipeWrite) ||
+        !createPipe(&errPipeRead, &errPipeWrite)) {
+      throw std::runtime_error("createFile failed!");
+    }
+    if (TestCodepage == CP_ACP) {
+      TestCodepage = GetACP();
+    }
+    if (!SetConsoleCP(TestCodepage)) {
+      throw std::runtime_error("SetConsoleCP failed!");
+    }
+
+    DWORD bytesWritten = 0;
+    if (!WriteFile(inPipeWrite, encodedInputTestString.c_str(),
+                   (DWORD)encodedInputTestString.size(), &bytesWritten, NULL)
+        || bytesWritten == 0) {
+      throw std::runtime_error("WriteFile failed!");
+    }
+
+    if (createProcess(inPipeRead, outPipeWrite, errPipeWrite)) {
+      try {
+        DWORD status;
+        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+          std::cerr.setf(std::ios::hex, std::ios::basefield);
+          std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+          std::cerr.unsetf(std::ios::hex);
+          throw std::runtime_error("WaitForSingleObject failed!");
+        }
+        DWORD bytesRead = 0;
+        if (!ReadFile(outPipeRead, buffer, sizeof(buffer), &bytesRead, NULL)
+            || bytesRead == 0) {
+          throw std::runtime_error("ReadFile#1 failed!");
+        }
+        if ((bytesRead < encodedTestString.size() + 1 + encodedInputTestString.size()
+             && !ReadFile(outPipeRead, buffer + bytesRead,
+                          sizeof(buffer) - bytesRead, &bytesRead, NULL))
+            || bytesRead == 0) {
+          throw std::runtime_error("ReadFile#2 failed!");
+        }
+        if (memcmp(buffer, encodedTestString.c_str(),
+                   encodedTestString.size()) == 0 &&
+            memcmp(buffer + encodedTestString.size() + 1,
+                   encodedInputTestString.c_str(),
+                   encodedInputTestString.size()) == 0) {
+          bytesRead = 0;
+          if (!ReadFile(errPipeRead, buffer2, sizeof(buffer2), &bytesRead, NULL)
+              || bytesRead == 0) {
+            throw std::runtime_error("ReadFile#3 failed!");
+          }
+          buffer2[bytesRead - 1] = 0;
+          didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
+        }
+        if (didFail != 0) {
+          std::cerr << "Pipe's output didn't match expected output!" << std::endl;
+          dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
+          dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size());
+          dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+        }
+      } catch (const std::runtime_error &ex) {
+        DWORD lastError = GetLastError();
+        std::cerr << "In function testPipe, line " <<  __LINE__ << ": "
+                  << ex.what() << std::endl;
+        displayError(lastError);
+      }
+      finishProcess(didFail == 0);
+    }
+  } catch (const std::runtime_error &ex) {
+    DWORD lastError = GetLastError();
+    std::cerr << "In function testPipe, line " <<  __LINE__ << ": "
+              << ex.what() << std::endl;
+    displayError(lastError);
+  }
+  finishPipe(inPipeRead, inPipeWrite);
+  finishPipe(outPipeRead, outPipeWrite);
+  finishPipe(errPipeRead, errPipeWrite);
+  SetConsoleCP(currentCodepage);
+  return didFail;
+}
+
+//----------------------------------------------------------------------------
+static int testFile()
+{
+  int didFail = 1;
+  HANDLE inFile = INVALID_HANDLE_VALUE;
+  HANDLE outFile = INVALID_HANDLE_VALUE;
+  HANDLE errFile = INVALID_HANDLE_VALUE;
+  try {
+    if ((inFile = createFile(L"stdinFile.txt")) == INVALID_HANDLE_VALUE ||
+        (outFile = createFile(L"stdoutFile.txt")) == INVALID_HANDLE_VALUE ||
+        (errFile = createFile(L"stderrFile.txt")) == INVALID_HANDLE_VALUE) {
+      throw std::runtime_error("createFile failed!");
+    }
+    DWORD bytesWritten = 0;
+    char buffer[200];
+    char buffer2[200];
+
+    int length;
+    if ((length = WideCharToMultiByte(TestCodepage, 0, UnicodeInputTestString, -1,
+                                      buffer, sizeof(buffer),
+                                      NULL, NULL)) == 0) {
+      throw std::runtime_error("WideCharToMultiByte failed!");
+    }
+    buffer[length - 1] = '\n';
+    if (!WriteFile(inFile, buffer, length, &bytesWritten, NULL)
+        || bytesWritten == 0) {
+      throw std::runtime_error("WriteFile failed!");
+    }
+    if (SetFilePointer(inFile, 0, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
+      throw std::runtime_error("SetFilePointer failed!");
+    }
+
+    if (createProcess(inFile, outFile, errFile)) {
+      DWORD bytesRead = 0;
+      try {
+        DWORD status;
+        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+          std::cerr.setf(std::ios::hex, std::ios::basefield);
+          std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+          std::cerr.unsetf(std::ios::hex);
+          throw std::runtime_error("WaitForSingleObject failed!");
+        }
+        if (SetFilePointer(outFile, 0, 0, FILE_BEGIN)
+            == INVALID_SET_FILE_POINTER) {
+          throw std::runtime_error("SetFilePointer#1 failed!");
+        }
+        if (!ReadFile(outFile, buffer, sizeof(buffer), &bytesRead, NULL)
+            || bytesRead == 0) {
+          throw std::runtime_error("ReadFile#1 failed!");
+        }
+        buffer[bytesRead - 1] = 0;
+        if (memcmp(buffer, encodedTestString.c_str(),
+                   encodedTestString.size()) == 0 &&
+            memcmp(buffer + encodedTestString.size() + 1,
+                   encodedInputTestString.c_str(),
+                   encodedInputTestString.size() - 1) == 0) {
+          bytesRead = 0;
+          if (SetFilePointer(errFile, 0, 0, FILE_BEGIN)
+              == INVALID_SET_FILE_POINTER) {
+            throw std::runtime_error("SetFilePointer#2 failed!");
+          }
+          if (!ReadFile(errFile, buffer2, sizeof(buffer2), &bytesRead, NULL)
+              || bytesRead == 0) {
+            throw std::runtime_error("ReadFile#2 failed!");
+          }
+          buffer2[bytesRead - 1] = 0;
+          didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
+        }
+        if (didFail != 0) {
+          std::cerr << "File's output didn't match expected output!" << std::endl;
+          dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
+          dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size() - 1);
+          dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+        }
+      } catch (const std::runtime_error &ex) {
+        DWORD lastError = GetLastError();
+        std::cerr << "In function testFile, line " <<  __LINE__ << ": "
+                  << ex.what() << std::endl;
+        displayError(lastError);
+      }
+      finishProcess(didFail == 0);
+    }
+  } catch (const std::runtime_error &ex) {
+    DWORD lastError = GetLastError();
+    std::cerr << "In function testFile, line " <<  __LINE__ << ": "
+              << ex.what() << std::endl;
+    displayError(lastError);
+  }
+  finishFile(inFile);
+  finishFile(outFile);
+  finishFile(errFile);
+  return didFail;
+}
+
+#ifndef _WIN32_WINNT_VISTA
+# define _WIN32_WINNT_VISTA 0x0600
+#endif
+
+//----------------------------------------------------------------------------
+static int testConsole()
+{
+  int didFail = 1;
+  HANDLE parentIn = GetStdHandle(STD_INPUT_HANDLE);
+  HANDLE parentOut = GetStdHandle(STD_OUTPUT_HANDLE);
+  HANDLE parentErr = GetStdHandle(STD_ERROR_HANDLE);
+  HANDLE hIn = parentIn;
+  HANDLE hOut = parentOut;
+  DWORD consoleMode;
+  bool newConsole = false;
+  bool forceNewConsole = false;
+  bool restoreConsole = false;
+  LPCWSTR TestFaceName = L"Lucida Console";
+  const DWORD TestFontFamily = 0x00000036;
+  const DWORD TestFontSize = 0x000c0000;
+  HKEY hConsoleKey;
+  WCHAR FaceName[200];
+  FaceName[0] = 0;
+  DWORD FaceNameSize = sizeof(FaceName);
+  DWORD FontFamily = TestFontFamily;
+  DWORD FontSize = TestFontSize;
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
+# pragma warning (push)
+# ifdef __INTEL_COMPILER
+#  pragma warning (disable:1478)
+# else
+#  pragma warning (disable:4996)
+# endif
+#endif
+  const bool isVistaOrGreater = LOBYTE(LOWORD(GetVersion())) >= HIBYTE(_WIN32_WINNT_VISTA);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
+# pragma warning (pop)
+#endif
+  if (!isVistaOrGreater) {
+    if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0, KEY_READ | KEY_WRITE,
+                      &hConsoleKey) == ERROR_SUCCESS) {
+      DWORD dwordSize = sizeof(DWORD);
+      if (RegQueryValueExW(hConsoleKey, L"FontFamily", NULL, NULL,
+                           (LPBYTE)&FontFamily, &dwordSize) == ERROR_SUCCESS) {
+        if (FontFamily != TestFontFamily) {
+          RegQueryValueExW(hConsoleKey, L"FaceName", NULL, NULL,
+                           (LPBYTE)FaceName, &FaceNameSize);
+          RegQueryValueExW(hConsoleKey, L"FontSize", NULL, NULL,
+                           (LPBYTE)&FontSize, &dwordSize);
+
+          RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
+                         (BYTE *)&TestFontFamily, sizeof(TestFontFamily));
+          RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
+                         (BYTE *)TestFaceName, (DWORD)((wcslen(TestFaceName) + 1) * sizeof(WCHAR)));
+          RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
+                         (BYTE *)&TestFontSize, sizeof(TestFontSize));
+
+          restoreConsole = true;
+          forceNewConsole = true;
+        }
+      } else {
+        std::cerr << "RegGetValueW(FontFamily) failed!" << std::endl;
+      }
+      RegCloseKey(hConsoleKey);
+    } else {
+      std::cerr << "RegOpenKeyExW(HKEY_CURRENT_USER\\Console) failed!" << std::endl;
+    }
+  }
+  if (forceNewConsole || GetConsoleMode(parentOut, &consoleMode) == 0) {
+    // Not a real console, let's create new one.
+    FreeConsole();
+    if (!AllocConsole()) {
+      std::cerr << "AllocConsole failed!" << std::endl;
+      return didFail;
+    }
+    SECURITY_ATTRIBUTES securityAttributes;
+    securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
+    securityAttributes.bInheritHandle = TRUE;
+    securityAttributes.lpSecurityDescriptor = NULL;
+    hIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
+                       &securityAttributes, OPEN_EXISTING, 0, NULL);
+    if (hIn == INVALID_HANDLE_VALUE) {
+      DWORD lastError = GetLastError();
+      std::cerr << "CreateFile(CONIN$)" << std::endl;
+      displayError(lastError);
+    }
+    hOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
+                       &securityAttributes, OPEN_EXISTING, 0, NULL);
+    if (hOut == INVALID_HANDLE_VALUE) {
+      DWORD lastError = GetLastError();
+      std::cerr << "CreateFile(CONOUT$)" << std::endl;
+      displayError(lastError);
+    }
+    SetStdHandle(STD_INPUT_HANDLE, hIn);
+    SetStdHandle(STD_OUTPUT_HANDLE, hOut);
+    SetStdHandle(STD_ERROR_HANDLE, hOut);
+    newConsole = true;
+  }
+
+#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
+  if (isVistaOrGreater) {
+    CONSOLE_FONT_INFOEX consoleFont;
+    memset(&consoleFont, 0, sizeof(consoleFont));
+    consoleFont.cbSize = sizeof(consoleFont);
+    HMODULE kernel32 = LoadLibraryW(L"kernel32.dll");
+    typedef BOOL (WINAPI *GetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+    typedef BOOL (WINAPI *SetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+    GetCurrentConsoleFontExFunc getConsoleFont = (GetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "GetCurrentConsoleFontEx");
+    SetCurrentConsoleFontExFunc setConsoleFont = (SetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "SetCurrentConsoleFontEx");
+    if (getConsoleFont(hOut, FALSE, &consoleFont)) {
+      if (consoleFont.FontFamily != TestFontFamily) {
+        consoleFont.FontFamily = TestFontFamily;
+        wcscpy(consoleFont.FaceName, TestFaceName);
+        if (!setConsoleFont(hOut, FALSE, &consoleFont)) {
+          std::cerr << "SetCurrentConsoleFontEx failed!" << std::endl;
+        }
+      }
+    } else {
+      std::cerr << "GetCurrentConsoleFontEx failed!" << std::endl;
+    }
+  } else {
+#endif
+    if (restoreConsole && RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0,
+                                        KEY_WRITE, &hConsoleKey) == ERROR_SUCCESS) {
+      RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
+                     (BYTE *)&FontFamily, sizeof(FontFamily));
+      if (FaceName[0] != 0) {
+        RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
+                       (BYTE *)FaceName, FaceNameSize);
+      } else {
+        RegDeleteValueW(hConsoleKey, L"FaceName");
+      }
+      RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
+                     (BYTE *)&FontSize, sizeof(FontSize));
+      RegCloseKey(hConsoleKey);
+    }
+#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
+  }
+#endif
+
+  if (createProcess(NULL, NULL, NULL)) {
+    try {
+      DWORD status;
+      if ((status = WaitForSingleObject(beforeInputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+        std::cerr.setf(std::ios::hex, std::ios::basefield);
+        std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+        std::cerr.unsetf(std::ios::hex);
+        throw std::runtime_error("WaitForSingleObject#1 failed!");
+      }
+      INPUT_RECORD inputBuffer[(sizeof(UnicodeInputTestString) /
+                                sizeof(UnicodeInputTestString[0])) * 2];
+      memset(&inputBuffer, 0, sizeof(inputBuffer));
+      unsigned int i;
+      for (i = 0; i < (sizeof(UnicodeInputTestString) /
+                       sizeof(UnicodeInputTestString[0]) - 1); i++) {
+        writeInputKeyEvent(&inputBuffer[i*2], UnicodeInputTestString[i]);
+      }
+      writeInputKeyEvent(&inputBuffer[i*2], VK_RETURN);
+      DWORD eventsWritten = 0;
+      // We need to wait a bit before writing to console so child process have started waiting for input on stdin.
+      Sleep(300);
+      if (!WriteConsoleInputW(hIn, inputBuffer, sizeof(inputBuffer) /
+                                                sizeof(inputBuffer[0]),
+                              &eventsWritten) || eventsWritten == 0) {
+        throw std::runtime_error("WriteConsoleInput failed!");
+      }
+      if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+        std::cerr.setf(std::ios::hex, std::ios::basefield);
+        std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+        std::cerr.unsetf(std::ios::hex);
+        throw std::runtime_error("WaitForSingleObject#2 failed!");
+      }
+      CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo;
+      if (!GetConsoleScreenBufferInfo(hOut, &screenBufferInfo)) {
+        throw std::runtime_error("GetConsoleScreenBufferInfo failed!");
+      }
+
+      COORD coord;
+      DWORD charsRead = 0;
+      coord.X = 0;
+      coord.Y = screenBufferInfo.dwCursorPosition.Y - 4;
+      WCHAR *outputBuffer = new WCHAR[screenBufferInfo.dwSize.X * 4];
+      if (!ReadConsoleOutputCharacterW(hOut, outputBuffer,
+          screenBufferInfo.dwSize.X * 4, coord, &charsRead)
+          || charsRead == 0) {
+        delete[] outputBuffer;
+        throw std::runtime_error("ReadConsoleOutputCharacter failed!");
+      }
+      std::wstring wideTestString = kwsys::Encoding::ToWide(encodedTestString);
+      std::wstring wideInputTestString = kwsys::Encoding::ToWide(encodedInputTestString);
+      if (memcmp(outputBuffer, wideTestString.c_str(),
+                 wideTestString.size() * sizeof(wchar_t)) == 0 &&
+          memcmp(outputBuffer + screenBufferInfo.dwSize.X * 1,
+                 wideTestString.c_str(), wideTestString.size() * sizeof(wchar_t)) == 0 &&
+          memcmp(outputBuffer + screenBufferInfo.dwSize.X * 2,
+                 UnicodeInputTestString, sizeof(UnicodeInputTestString) -
+                                         sizeof(WCHAR)) == 0 &&
+          memcmp(outputBuffer + screenBufferInfo.dwSize.X * 3,
+                 wideInputTestString.c_str(),
+                 (wideInputTestString.size() - 1) * sizeof(wchar_t)) == 0
+      ) {
+        didFail = 0;
+      } else {
+        std::cerr << "Console's output didn't match expected output!" << std::endl;
+        dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer, wideTestString.size());
+        dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 1, wideTestString.size());
+        dumpBuffers<wchar_t>(UnicodeInputTestString, outputBuffer + screenBufferInfo.dwSize.X * 2, (sizeof(UnicodeInputTestString) - 1) / sizeof(WCHAR));
+        dumpBuffers<wchar_t>(wideInputTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 3, wideInputTestString.size() - 1);
+      }
+      delete[] outputBuffer;
+    } catch (const std::runtime_error &ex) {
+      DWORD lastError = GetLastError();
+      std::cerr << "In function testConsole, line " <<  __LINE__ << ": "
+                << ex.what() << std::endl;
+      displayError(lastError);
+    }
+    finishProcess(didFail == 0);
+  }
+  if (newConsole) {
+    SetStdHandle(STD_INPUT_HANDLE, parentIn);
+    SetStdHandle(STD_OUTPUT_HANDLE, parentOut);
+    SetStdHandle(STD_ERROR_HANDLE, parentErr);
+    CloseHandle(hIn);
+    CloseHandle(hOut);
+    FreeConsole();
+  }
+  return didFail;
+}
+
+#endif
+
+//----------------------------------------------------------------------------
+int testConsoleBuf(int, char*[])
+{
+  int ret = 0;
+
+#if defined(_WIN32)
+  beforeInputEvent = CreateEventW(NULL,
+                       FALSE,  // auto-reset event
+                       FALSE,  // initial state is nonsignaled
+                       BeforeInputEventName);  // object name
+  if (!beforeInputEvent) {
+    std::cerr << "CreateEvent#1 failed " << GetLastError() << std::endl;
+    return 1;
+  }
+
+  afterOutputEvent = CreateEventW(NULL, FALSE, FALSE, AfterOutputEventName);
+  if (!afterOutputEvent) {
+    std::cerr << "CreateEvent#2 failed " << GetLastError() << std::endl;
+    return 1;
+  }
+
+  encodedTestString = kwsys::Encoding::ToNarrow(UnicodeTestString);
+  encodedInputTestString = kwsys::Encoding::ToNarrow(UnicodeInputTestString);
+  encodedInputTestString += "\n";
+
+  ret |= testPipe();
+  ret |= testFile();
+  ret |= testConsole();
+
+  CloseHandle(beforeInputEvent);
+  CloseHandle(afterOutputEvent);
+#endif
+
+  return ret;
+}
diff --git a/Source/kwsys/testConsoleBuf.hxx b/Source/kwsys/testConsoleBuf.hxx
new file mode 100644
index 0000000..7c2f4c6
--- /dev/null
+++ b/Source/kwsys/testConsoleBuf.hxx
@@ -0,0 +1,25 @@
+/*============================================================================
+  KWSys - Kitware System Library
+  Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef testConsoleBuf_hxx
+#define testConsoleBuf_hxx
+
+static const wchar_t cmdConsoleBufChild[] = L"testConsoleBufChild";
+
+static const wchar_t BeforeInputEventName[] = L"BeforeInputEvent";
+static const wchar_t AfterOutputEventName[] = L"AfterOutputEvent";
+
+// यूनिकोड είναι здорово!
+static const wchar_t UnicodeTestString[] = L"\u092F\u0942\u0928\u093F\u0915\u094B\u0921 "
+                                           L"\u03B5\u03AF\u03BD\u03B1\u03B9 "
+                                           L"\u0437\u0434\u043E\u0440\u043E\u0432\u043E!";
+
+#endif
diff --git a/Source/kwsys/testConsoleBufChild.cxx b/Source/kwsys/testConsoleBufChild.cxx
new file mode 100644
index 0000000..2da39f2
--- /dev/null
+++ b/Source/kwsys/testConsoleBufChild.cxx
@@ -0,0 +1,63 @@
+/*============================================================================
+  KWSys - Kitware System Library
+  Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#include "kwsysPrivate.h"
+
+#include KWSYS_HEADER(ConsoleBuf.hxx)
+#include KWSYS_HEADER(Encoding.hxx)
+
+// Work-around CMake dependency scanning limitation.  This must
+// duplicate the above list of headers.
+#if 0
+# include "ConsoleBuf.hxx.in"
+# include "Encoding.hxx.in"
+#endif
+
+#include <iostream>
+#include "testConsoleBuf.hxx"
+
+//----------------------------------------------------------------------------
+int main(int argc, const char* argv[])
+{
+#if defined(_WIN32)
+  kwsys::ConsoleBuf::Manager out(std::cout);
+  kwsys::ConsoleBuf::Manager err(std::cerr, true);
+  kwsys::ConsoleBuf::Manager in(std::cin);
+
+  if (argc > 1) {
+    std::cout << argv[1] << std::endl;
+    std::cerr << argv[1] << std::endl;
+  } else {
+    std::string str = kwsys::Encoding::ToNarrow(UnicodeTestString);
+    std::cout << str << std::endl;
+    std::cerr << str << std::endl;
+  }
+
+  std::string input;
+  HANDLE event = OpenEventW(EVENT_MODIFY_STATE, FALSE, BeforeInputEventName);
+  if (event) {
+    SetEvent(event);
+    CloseHandle(event);
+  }
+
+  std::cin >> input;
+  std::cout << input << std::endl;
+  event = OpenEventW(EVENT_MODIFY_STATE, FALSE, AfterOutputEventName);
+  if (event) {
+    SetEvent(event);
+    CloseHandle(event);
+  }
+#else
+  static_cast<void>(argc);
+  static_cast<void>(argv);
+#endif
+  return 0;
+}
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index 4d97688..880b46e 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -204,6 +204,14 @@ static bool CheckFileOperations()
       << testNewDir << std::endl;
     res = false;
     }
+  // check existence
+  if (!kwsys::SystemTools::PathExists(testNewDir))
+    {
+    std::cerr
+      << "Problem with PathExists for: "
+      << testNewDir << std::endl;
+    res = false;
+    }
   // remove it
   if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
     {
@@ -221,6 +229,15 @@ static bool CheckFileOperations()
       << testNewDir << std::endl;
     res = false;
     }
+  // check existence
+  if (kwsys::SystemTools::PathExists(testNewDir))
+    {
+    std::cerr
+      << "After RemoveADirectory: "
+      << "Problem with PathExists for: "
+      << testNewDir << std::endl;
+    res = false;
+    }
   // create it using the char* version
   if (!kwsys::SystemTools::MakeDirectory(testNewDir.c_str()))
     {
@@ -329,6 +346,31 @@ static bool CheckFileOperations()
     res = false;
     }
 
+  // calling with an empty string should return false
+  if (kwsys::SystemTools::PathExists(std::string()))
+    {
+    std::cerr
+      << "Problem with PathExists(std::string())"
+      << std::endl;
+    res = false;
+    }
+  // PathExists(x) should return true on a directory
+  if (!kwsys::SystemTools::PathExists(testNewDir))
+    {
+    std::cerr
+      << "Problem with PathExists for: "
+      << testNewDir << std::endl;
+    res = false;
+    }
+  // should work, was created as new file before
+  if (!kwsys::SystemTools::PathExists(testNewFile))
+    {
+    std::cerr
+      << "Problem with PathExists for: "
+      << testNewDir << std::endl;
+    res = false;
+    }
+
   // Reset umask
 #if defined(_WIN32) && !defined(__CYGWIN__)
   // NOTE:  Windows doesn't support toggling _S_IREAD.
@@ -848,9 +890,9 @@ static bool CheckPutEnv(const std::string& env, const char* name, const char* va
                     << "\") failed!" << std::endl;
     return false;
     }
-  const char* v = kwsys::SystemTools::GetEnv(name);
-  v = v? v : "(null)";
-  if(strcmp(v, value) != 0)
+  std::string v = "(null)";
+  kwsys::SystemTools::GetEnv(name, v);
+  if(v != value)
     {
     std::cerr << "GetEnv(\"" << name << "\") returned \""
                     << v << "\", not \"" << value << "\"!" << std::endl;
@@ -867,7 +909,8 @@ static bool CheckUnPutEnv(const char* env, const char* name)
                     << std::endl;
     return false;
     }
-  if(const char* v = kwsys::SystemTools::GetEnv(name))
+  std::string v;
+  if(kwsys::SystemTools::GetEnv(name, v))
     {
     std::cerr << "GetEnv(\"" << name << "\") returned \""
                     << v << "\", not (null)!" << std::endl;
@@ -897,7 +940,7 @@ static bool CheckRelativePath(
   const std::string& expected)
 {
   std::string result = kwsys::SystemTools::RelativePath(local, remote);
-  if(expected != result)
+  if (!kwsys::SystemTools::ComparePath(expected, result))
     {
     std::cerr << "RelativePath(" << local << ", " << remote
       << ")  yielded " << result << " instead of " << expected << std::endl;
@@ -922,7 +965,7 @@ static bool CheckCollapsePath(
   const std::string& expected)
 {
   std::string result = kwsys::SystemTools::CollapseFullPath(path);
-  if(expected != result)
+  if (!kwsys::SystemTools::ComparePath(expected, result))
     {
     std::cerr << "CollapseFullPath(" << path
       << ")  yielded " << result << " instead of " << expected << std::endl;
diff --git a/Templates/TestDriver.cxx.in b/Templates/TestDriver.cxx.in
index ffa6999..3e0afa5 100644
--- a/Templates/TestDriver.cxx.in
+++ b/Templates/TestDriver.cxx.in
@@ -33,19 +33,21 @@ static functionMapEntry cmakeGeneratedFunctionMapEntries[] = {
 static char* lowercase(const char *string)
 {
   char *new_string, *p;
+  size_t stringSize = 0;
 
 #ifdef __cplusplus
-  new_string = static_cast<char *>(malloc(sizeof(char) *
-    static_cast<size_t>(strlen(string) + 1)));
+  stringSize = static_cast<size_t>(strlen(string) + 1);
+  new_string = static_cast<char *>(malloc(sizeof(char) * stringSize));
 #else
-  new_string = (char *)(malloc(sizeof(char) * (size_t)(strlen(string) + 1)));
+  stringSize = (size_t)(strlen(string) + 1);
+  new_string = (char *)(malloc(sizeof(char) * stringSize));
 #endif
 
   if (!new_string)
     {
     return 0;
     }
-  strcpy(new_string, string);
+  strncpy(new_string, string, stringSize);
   p = new_string;
   while (*p != 0)
     {
diff --git a/Templates/cygwin-package.sh.in b/Templates/cygwin-package.sh.in
deleted file mode 100755
index 69b6c0f..0000000
--- a/Templates/cygwin-package.sh.in
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/bin/sh
-
-# this is a sample shell script used for building a cmake
-# based project for a cygwin setup package.
-
-# get the current directory
-TOP_DIR=`cd \`echo "$0" | sed -n '/\//{s/\/[^\/]*$//;p;}'\`;pwd`
-
-# create build directory
-mkdirs()
-{
-  (
-  mkdir -p "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build"
-  )
-}
-
-# cd into
-# untar source tree and apply patch
-prep()
-{
-  (
-  cd "$TOP_DIR" &&
-  tar xvfj @CPACK_PACKAGE_FILE_NAME at .tar.bz2
-  patch -p0 < "@CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at .patch" &&
-  mkdirs
-  )
-}
-
-# configure the build tree in .build directory
-# of the source tree
-conf()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  cmake ..
-  )
-}
-
-# build the package in the .build directory
-build()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  make &&
-  make test
-  )
-}
-
-# clean the build tree
-clean()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  make clean
-  )
-}
-
-# create the package
-pkg()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  cpack &&
-  mv @CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at .tar.bz2 "$TOP_DIR"
-  )
-}
-
-# create the source package
-spkg()
-{
- (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  cpack --config  CPackSourceConfig.cmake &&
-  mv @CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at -src.tar.bz2 "$TOP_DIR"
-  )
-}
-
-# clean up
-finish()
-{
-  (
-  rm -rf "@CPACK_PACKAGE_FILE_NAME@"
-  )
-}
-
-case $1 in
-  prep)         prep    ; STATUS=$? ;;
-  mkdirs)       mkdirs  ; STATUS=$? ;;
-  conf)         conf    ; STATUS=$? ;;
-  build)        build   ; STATUS=$? ;;
-  clean)        clean   ; STATUS=$? ;;
-  package)      pkg     ; STATUS=$? ;;
-  pkg)          pkg     ; STATUS=$? ;;
-  src-package)  spkg    ; STATUS=$? ;;
-  spkg)         spkg    ; STATUS=$? ;;
-  finish)       finish  ; STATUS=$? ;;
-  all) (
-       prep && conf && build && pkg && spkg && finish ;
-       STATUS=$?
-       ) ;;
-  *) echo "Error: bad argument (all or one of these: prep mkdirs conf build clean package pkg src-package spkg finish)" ; exit 1 ;;
-esac
-exit ${STATUS}
diff --git a/Tests/AliasTarget/CMakeLists.txt b/Tests/AliasTarget/CMakeLists.txt
index 47ccbdc..e156420 100644
--- a/Tests/AliasTarget/CMakeLists.txt
+++ b/Tests/AliasTarget/CMakeLists.txt
@@ -8,7 +8,7 @@ set(CMAKE_CXX_STANDARD 98)
 # template support also need a flag to use the newer C++ library.
 if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
     CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA")
+  string(APPEND CMAKE_CXX_FLAGS " -AA")
 endif ()
 
 # Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
@@ -66,6 +66,11 @@ endif()
 add_library(iface INTERFACE)
 add_library(Alias::Iface ALIAS iface)
 
+get_property(_aliased_target_set TARGET foo PROPERTY ALIASED_TARGET SET)
+if(_aliased_target_set)
+  message(SEND_ERROR "ALIASED_TARGET is set for target foo")
+endif()
+
 get_target_property(_notAlias1 foo ALIASED_TARGET)
 if (NOT DEFINED _notAlias1)
   message(SEND_ERROR "_notAlias1 is not defined")
@@ -78,12 +83,6 @@ if (NOT _notAlias1 STREQUAL _notAlias1-NOTFOUND)
 endif()
 
 get_property(_notAlias2 TARGET foo PROPERTY ALIASED_TARGET)
-if (NOT DEFINED _notAlias2)
-  message(SEND_ERROR "_notAlias2 is not defined")
-endif()
 if (_notAlias2)
-  message(SEND_ERROR "_notAlias2 is defined, but foo is not an ALIAS")
-endif()
-if (NOT _notAlias2 STREQUAL _notAlias2-NOTFOUND)
-  message(SEND_ERROR "_notAlias2 not defined to a -NOTFOUND variant")
+  message(SEND_ERROR "_notAlias2 evaluates to true, but foo is not an ALIAS")
 endif()
diff --git a/Tests/AliasTarget/commandgenerator.cpp b/Tests/AliasTarget/commandgenerator.cpp
index aaab014..c4d80a1 100644
--- a/Tests/AliasTarget/commandgenerator.cpp
+++ b/Tests/AliasTarget/commandgenerator.cpp
@@ -5,8 +5,7 @@
 
 int main(int argc, char** argv)
 {
-  std::fstream fout;
-  fout.open("commandoutput.h", std::ios::out);
+  std::ofstream fout("commandoutput.h");
   if (!fout)
     return 1;
   fout << "#define COMMANDOUTPUT_DEFINE\n";
diff --git a/Tests/AliasTarget/targetgenerator.cpp b/Tests/AliasTarget/targetgenerator.cpp
index b3e6ee2..4de4792 100644
--- a/Tests/AliasTarget/targetgenerator.cpp
+++ b/Tests/AliasTarget/targetgenerator.cpp
@@ -3,8 +3,7 @@
 
 int main(int argc, char** argv)
 {
-  std::fstream fout;
-  fout.open("targetoutput.h", std::ios::out);
+  std::ofstream fout("targetoutput.h");
   if (!fout)
     return 1;
   fout << "#define TARGETOUTPUT_DEFINE\n";
diff --git a/Tests/CFBundleTest/CMakeLists.txt b/Tests/CFBundleTest/CMakeLists.txt
index 5cda527..0fe6bb7 100644
--- a/Tests/CFBundleTest/CMakeLists.txt
+++ b/Tests/CFBundleTest/CMakeLists.txt
@@ -50,7 +50,6 @@ set_source_files_properties(
 set_target_properties(CFBundleTest PROPERTIES
     BUNDLE 1
     BUNDLE_EXTENSION plugin
-    XCODE_ATTRIBUTE_WRAPPER_EXTENSION plugin  #sets the extension to .plugin
     XCODE_ATTRIBUTE_MACH_O_TYPE mh_bundle
     XCODE_ATTRIBUTE_INFOPLIST_FILE ${CMAKE_CURRENT_BINARY_DIR}/Info.plist
     MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_BINARY_DIR}/Info.plist
diff --git a/Tests/CMakeLib/CMakeLists.txt b/Tests/CMakeLib/CMakeLists.txt
index 7ef3c03..405917a 100644
--- a/Tests/CMakeLib/CMakeLists.txt
+++ b/Tests/CMakeLib/CMakeLists.txt
@@ -11,6 +11,7 @@ set(CMakeLib_TESTS
   testUTF8
   testXMLParser
   testXMLSafe
+  testFindPackageCommand
   )
 
 set(testRST_ARGS ${CMAKE_CURRENT_SOURCE_DIR})
diff --git a/Tests/CMakeLib/PseudoMemcheck/memtester.cxx.in b/Tests/CMakeLib/PseudoMemcheck/memtester.cxx.in
index b141942..e2cdec8 100644
--- a/Tests/CMakeLib/PseudoMemcheck/memtester.cxx.in
+++ b/Tests/CMakeLib/PseudoMemcheck/memtester.cxx.in
@@ -4,8 +4,7 @@
 
 #define RETVAL @_retval@
 
-int
-main(int ac, char **av)
+int main(int ac, char** av)
 {
   cmsys::Encoding::CommandLineArguments args =
     cmsys::Encoding::CommandLineArguments::Main(ac, av);
@@ -16,42 +15,39 @@ main(int ac, char **av)
   std::string logarg;
   bool nextarg = false;
 
-  if (exename.find("valgrind") != exename.npos)
+  if (exename.find("valgrind") != exename.npos) {
     logarg = "--log-file=";
-  else if (exename.find("purify") != exename.npos)
+  } else if (exename.find("purify") != exename.npos) {
 #ifdef _WIN32
     logarg = "/SAVETEXTDATA=";
 #else
     logarg = "-log-file=";
 #endif
-  else if (exename.find("BC") != exename.npos)
-    {
+  } else if (exename.find("BC") != exename.npos) {
     nextarg = true;
     logarg = "/X";
-    }
+  }
 
   if (!logarg.empty()) {
     std::string logfile;
     for (int i = 1; i < argc; i++) {
       std::string arg = argv[i];
-      if (arg.find(logarg) == 0)
-        {
-        if (nextarg)
-          {
-          if (i == argc - 1)
+      if (arg.find(logarg) == 0) {
+        if (nextarg) {
+          if (i == argc - 1) {
             return 1; // invalid command line
-          logfile = argv[i + 1];
           }
-        else
-          {
+          logfile = argv[i + 1];
+        } else {
           logfile = arg.substr(logarg.length());
-          }
-        // keep searching, it may be overridden later to provoke an error
         }
+        // keep searching, it may be overridden later to provoke an error
       }
+    }
 
-    if (!logfile.empty())
+    if (!logfile.empty()) {
       cmSystemTools::Touch(logfile, true);
+    }
   }
 
   return RETVAL;
diff --git a/Tests/CMakeLib/run_compile_commands.cxx b/Tests/CMakeLib/run_compile_commands.cxx
index 1cfd381..0bf0a7c 100644
--- a/Tests/CMakeLib/run_compile_commands.cxx
+++ b/Tests/CMakeLib/run_compile_commands.cxx
@@ -1,5 +1,13 @@
 #include "cmSystemTools.h"
 
+#include <cmsys/FStream.hxx>
+#include <iostream>
+#include <map>
+#include <stdlib.h>
+#include <string>
+#include <utility>
+#include <vector>
+
 class CompileCommandParser
 {
 public:
@@ -18,7 +26,10 @@ public:
   };
   typedef std::vector<CommandType> TranslationUnitsType;
 
-  CompileCommandParser(std::ifstream* input) { this->Input = input; }
+  CompileCommandParser(std::istream& input)
+    : Input(input)
+  {
+  }
 
   void Parse()
   {
@@ -46,10 +57,12 @@ private:
   void ParseTranslationUnit()
   {
     this->Command = CommandType();
-    if (!Expect('{'))
+    if (!Expect('{')) {
       return;
-    if (Expect('}'))
+    }
+    if (Expect('}')) {
       return;
+    }
     do {
       ParseString();
       std::string name = this->String;
@@ -64,8 +77,9 @@ private:
   void ParseString()
   {
     this->String = "";
-    if (!Expect('"'))
+    if (!Expect('"')) {
       return;
+    }
     while (!Expect('"')) {
       Expect('\\');
       this->String.append(1, C);
@@ -84,8 +98,9 @@ private:
 
   void ExpectOrDie(char c, const std::string& message)
   {
-    if (!Expect(c))
+    if (!Expect(c)) {
       ErrorExit(std::string("'") + c + "' expected " + message + ".");
+    }
   }
 
   void NextNonWhitespace()
@@ -97,9 +112,10 @@ private:
 
   void Next()
   {
-    this->C = char(Input->get());
-    if (this->Input->bad())
+    this->C = char(Input.get());
+    if (this->Input.bad()) {
       ErrorExit("Unexpected end of file.");
+    }
   }
 
   void ErrorExit(const std::string& message)
@@ -118,13 +134,13 @@ private:
   TranslationUnitsType TranslationUnits;
   CommandType Command;
   std::string String;
-  std::ifstream* Input;
+  std::istream& Input;
 };
 
 int main()
 {
-  std::ifstream file("compile_commands.json");
-  CompileCommandParser parser(&file);
+  cmsys::ifstream file("compile_commands.json");
+  CompileCommandParser parser(file);
   parser.Parse();
   for (CompileCommandParser::TranslationUnitsType::const_iterator
          it = parser.GetTranslationUnits().begin(),
@@ -132,7 +148,8 @@ int main()
        it != end; ++it) {
     std::vector<std::string> command;
     cmSystemTools::ParseUnixCommandLine(it->at("command").c_str(), command);
-    if (!cmSystemTools::RunSingleCommand(command, 0, 0, 0,
+    if (!cmSystemTools::RunSingleCommand(command, CM_NULLPTR, CM_NULLPTR,
+                                         CM_NULLPTR,
                                          it->at("directory").c_str())) {
       std::cout << "ERROR: Failed to run command \"" << command[0] << "\""
                 << std::endl;
diff --git a/Tests/CMakeLib/testFindPackageCommand.cxx b/Tests/CMakeLib/testFindPackageCommand.cxx
new file mode 100644
index 0000000..7622756
--- /dev/null
+++ b/Tests/CMakeLib/testFindPackageCommand.cxx
@@ -0,0 +1,67 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmFindPackageCommand.h"
+
+#include <iostream>
+#include <string>
+
+#define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
+#define cmFailed(m)                                                           \
+  std::cout << "FAILED: " << (m) << "\n";                                     \
+  failed = 1
+
+int testFindPackageCommand(int /*unused*/, char* /*unused*/ [])
+{
+  int failed = 0;
+
+  // ----------------------------------------------------------------------
+  // Test cmFindPackage::Sort
+  std::vector<std::string> testString;
+  testString.push_back("lib-0.0");
+  testString.push_back("lib-1.2");
+  testString.push_back("lib-2.0");
+  testString.push_back("lib-19.0.1");
+  testString.push_back("lib-20.01.1");
+  testString.push_back("lib-20.2.2a");
+
+  cmFindPackageCommand::Sort(testString.begin(), testString.end(),
+                             cmFindPackageCommand::Natural,
+                             cmFindPackageCommand::Asc);
+  if (!(testString[0] == "lib-0.0" && testString[1] == "lib-1.2" &&
+        testString[2] == "lib-2.0" && testString[3] == "lib-19.0.1" &&
+        testString[4] == "lib-20.01.1" && testString[5] == "lib-20.2.2a")) {
+    cmFailed("cmSystemTools::Sort fail with Natural ASC");
+  }
+
+  cmFindPackageCommand::Sort(testString.begin(), testString.end(),
+                             cmFindPackageCommand::Natural,
+                             cmFindPackageCommand::Dec);
+  if (!(testString[5] == "lib-0.0" && testString[4] == "lib-1.2" &&
+        testString[3] == "lib-2.0" && testString[2] == "lib-19.0.1" &&
+        testString[1] == "lib-20.01.1" && testString[0] == "lib-20.2.2a")) {
+    cmFailed("cmSystemTools::Sort fail with Natural ASC");
+  }
+
+  cmFindPackageCommand::Sort(testString.begin(), testString.end(),
+                             cmFindPackageCommand::Name_order,
+                             cmFindPackageCommand::Dec);
+  if (!(testString[5] == "lib-0.0" && testString[4] == "lib-1.2" &&
+        testString[3] == "lib-19.0.1" && testString[2] == "lib-2.0" &&
+        testString[1] == "lib-20.01.1" && testString[0] == "lib-20.2.2a")) {
+    cmFailed("cmSystemTools::Sort fail with Name DEC");
+  }
+
+  cmFindPackageCommand::Sort(testString.begin(), testString.end(),
+                             cmFindPackageCommand::Name_order,
+                             cmFindPackageCommand::Asc);
+  if (!(testString[0] == "lib-0.0" && testString[1] == "lib-1.2" &&
+        testString[2] == "lib-19.0.1" && testString[3] == "lib-2.0" &&
+        testString[4] == "lib-20.01.1" && testString[5] == "lib-20.2.2a")) {
+    cmFailed("cmSystemTools::Sort fail with Natural ASC");
+  }
+
+  if (!failed) {
+    cmPassed("cmSystemTools::Sort working");
+  }
+  return failed;
+}
diff --git a/Tests/CMakeLib/testGeneratedFileStream.cxx b/Tests/CMakeLib/testGeneratedFileStream.cxx
index 67dd69a..1d2ec32 100644
--- a/Tests/CMakeLib/testGeneratedFileStream.cxx
+++ b/Tests/CMakeLib/testGeneratedFileStream.cxx
@@ -1,22 +1,16 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratedFileStream.h"
 #include "cmSystemTools.h"
 
+#include <iostream>
+#include <string>
+
 #define cmFailed(m1, m2)                                                      \
-  std::cout << "FAILED: " << m1 << m2 << "\n";                                \
+  std::cout << "FAILED: " << (m1) << (m2) << "\n";                            \
   failed = 1
 
-int testGeneratedFileStream(int, char* [])
+int testGeneratedFileStream(int /*unused*/, char* /*unused*/ [])
 {
   int failed = 0;
   cmGeneratedFileStream gm;
diff --git a/Tests/CMakeLib/testRST.cxx b/Tests/CMakeLib/testRST.cxx
index e5a96c2..e1b0903 100644
--- a/Tests/CMakeLib/testRST.cxx
+++ b/Tests/CMakeLib/testRST.cxx
@@ -1,18 +1,12 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRST.h"
-
 #include "cmSystemTools.h"
 
+#include <cmsys/FStream.hxx>
+#include <iostream>
+#include <string>
+
 void reportLine(std::ostream& os, bool ret, std::string const& line, bool eol)
 {
   if (ret) {
@@ -52,8 +46,8 @@ int testRST(int argc, char* argv[])
   }
 
   // Compare expected and actual outputs.
-  std::ifstream e_fin(e_name.c_str());
-  std::ifstream a_fin(a_name.c_str());
+  cmsys::ifstream e_fin(e_name.c_str());
+  cmsys::ifstream a_fin(a_name.c_str());
   if (!e_fin) {
     std::cerr << "Could not open input " << e_name << std::endl;
     return 1;
diff --git a/Tests/CMakeLib/testSystemTools.cxx b/Tests/CMakeLib/testSystemTools.cxx
index a3846c0..b16b088 100644
--- a/Tests/CMakeLib/testSystemTools.cxx
+++ b/Tests/CMakeLib/testSystemTools.cxx
@@ -1,32 +1,90 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSystemTools.h"
 
-#define cmPassed(m) std::cout << "Passed: " << m << "\n"
+#include <iostream>
+#include <string>
+
+#define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
 #define cmFailed(m)                                                           \
-  std::cout << "FAILED: " << m << "\n";                                       \
+  std::cout << "FAILED: " << (m) << "\n";                                     \
   failed = 1
 
-int testSystemTools(int, char* [])
+#define cmAssert(exp, m)                                                      \
+  if ((exp)) {                                                                \
+    cmPassed(m);                                                              \
+  } else {                                                                    \
+    cmFailed(m);                                                              \
+  }
+
+int testSystemTools(int /*unused*/, char* /*unused*/ [])
 {
   int failed = 0;
   // ----------------------------------------------------------------------
   // Test cmSystemTools::UpperCase
   std::string str = "abc";
   std::string strupper = "ABC";
-  if (cmSystemTools::UpperCase(str) == strupper) {
-    cmPassed("cmSystemTools::UpperCase is working");
-  } else {
-    cmFailed("cmSystemTools::UpperCase is working");
+  cmAssert(cmSystemTools::UpperCase(str) == strupper,
+           "cmSystemTools::UpperCase");
+
+  // ----------------------------------------------------------------------
+  // Test cmSystemTools::strverscmp
+  cmAssert(cmSystemTools::strverscmp("", "") == 0, "strverscmp empty string");
+  cmAssert(cmSystemTools::strverscmp("abc", "") > 0,
+           "strverscmp string vs empty string");
+  cmAssert(cmSystemTools::strverscmp("abc", "abc") == 0,
+           "strverscmp same string");
+  cmAssert(cmSystemTools::strverscmp("abd", "abc") > 0,
+           "strverscmp character string");
+  cmAssert(cmSystemTools::strverscmp("abc", "abd") < 0,
+           "strverscmp symmetric");
+  cmAssert(cmSystemTools::strverscmp("12345", "12344") > 0,
+           "strverscmp natural numbers");
+  cmAssert(cmSystemTools::strverscmp("100", "99") > 0,
+           "strverscmp natural numbers different digits");
+  cmAssert(cmSystemTools::strverscmp("12345", "00345") > 0,
+           "strverscmp natural against decimal (same length)");
+  cmAssert(cmSystemTools::strverscmp("99999999999999", "99999999999991") > 0,
+           "strverscmp natural overflow");
+  cmAssert(cmSystemTools::strverscmp("00000000000009", "00000000000001") > 0,
+           "strverscmp deciaml precision");
+  cmAssert(cmSystemTools::strverscmp("a.b.c.0", "a.b.c.000") > 0,
+           "strverscmp multiple zeros");
+  cmAssert(cmSystemTools::strverscmp("lib_1.2_10", "lib_1.2_2") > 0,
+           "strverscmp last number ");
+  cmAssert(cmSystemTools::strverscmp("12lib", "2lib") > 0,
+           "strverscmp first number ");
+  cmAssert(cmSystemTools::strverscmp("02lib", "002lib") > 0,
+           "strverscmp first number decimal ");
+  cmAssert(cmSystemTools::strverscmp("10", "9a") > 0,
+           "strverscmp letter filler ");
+  cmAssert(cmSystemTools::strverscmp("000", "0001") > 0,
+           "strverscmp zero and leading zeros  ");
+
+  // test sorting using standard strvercmp input
+  std::vector<std::string> testString;
+  testString.push_back("000");
+  testString.push_back("00");
+  testString.push_back("01");
+  testString.push_back("010");
+  testString.push_back("09");
+  testString.push_back("0");
+  testString.push_back("1");
+  testString.push_back("9");
+  testString.push_back("10");
+
+  // test global ordering of input strings
+  for (size_t i = 0; i < testString.size() - 1; i++) {
+    for (size_t j = i + 1; j < testString.size(); j++) {
+      if (cmSystemTools::strverscmp(testString[i], testString[j]) >= 0) {
+        cmFailed("cmSystemTools::strverscmp error in comparing strings " +
+                 testString[i] + " " + testString[j]);
+      }
+    }
+  }
+
+  if (!failed) {
+    cmPassed("cmSystemTools::strverscmp working");
   }
   return failed;
 }
diff --git a/Tests/CMakeLib/testUTF8.cxx b/Tests/CMakeLib/testUTF8.cxx
index 1da23fe..fb5f3d8 100644
--- a/Tests/CMakeLib/testUTF8.cxx
+++ b/Tests/CMakeLib/testUTF8.cxx
@@ -1,18 +1,7 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include <cm_utf8.h>
-
 #include <stdio.h>
-#include <string.h>
 
 typedef char test_utf8_char[5];
 
@@ -97,7 +86,7 @@ static bool decode_bad(test_utf8_char const s)
   return true;
 }
 
-int testUTF8(int, char* [])
+int testUTF8(int /*unused*/, char* /*unused*/ [])
 {
   int result = 0;
   for (test_utf8_entry const* e = good_entry; e->n; ++e) {
diff --git a/Tests/CMakeLib/testXMLParser.cxx b/Tests/CMakeLib/testXMLParser.cxx
index 1fd5113..d5e9764 100644
--- a/Tests/CMakeLib/testXMLParser.cxx
+++ b/Tests/CMakeLib/testXMLParser.cxx
@@ -4,7 +4,7 @@
 
 #include <iostream>
 
-int testXMLParser(int, char* [])
+int testXMLParser(int /*unused*/, char* /*unused*/ [])
 {
   // TODO: Derive from parser and check attributes.
   cmXMLParser parser;
diff --git a/Tests/CMakeLib/testXMLSafe.cxx b/Tests/CMakeLib/testXMLSafe.cxx
index 34c38fb..6c59128 100644
--- a/Tests/CMakeLib/testXMLSafe.cxx
+++ b/Tests/CMakeLib/testXMLSafe.cxx
@@ -1,17 +1,10 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmXMLSafe.h"
 
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-#include <cmXMLSafe.h>
-
-#include "cmStandardIncludes.h"
+#include <sstream>
+#include <stdio.h>
+#include <string>
 
 struct test_pair
 {
@@ -25,10 +18,10 @@ static test_pair const pairs[] = {
   { "angles <>", "angles <>" },
   { "ampersand &", "ampersand &" },
   { "bad-byte \x80", "bad-byte [NON-UTF-8-BYTE-0x80]" },
-  { 0, 0 }
+  { CM_NULLPTR, CM_NULLPTR }
 };
 
-int testXMLSafe(int, char* [])
+int testXMLSafe(int /*unused*/, char* /*unused*/ [])
 {
   int result = 0;
   for (test_pair const* p = pairs; p->in; ++p) {
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index f21e430..7df9403 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -83,6 +83,17 @@ if(BUILD_TESTING)
     set(MAKE_SUPPORTS_SPACES 0)
   endif()
 
+  # assume no resources building to test
+  set(CMake_TEST_RESOURCES FALSE)
+  # for windows and cygwin assume we have resources
+  if(WIN32 OR CYGWIN)
+    set(CMake_TEST_RESOURCES TRUE)
+  endif()
+  # for borland and watcom there is no resource support
+  if(WATCOM OR BORLAND)
+    set(CMake_TEST_RESOURCES FALSE)
+  endif()
+
   set(build_generator_args
     --build-generator ${CMAKE_GENERATOR}
     )
@@ -262,17 +273,7 @@ if(BUILD_TESTING)
   ADD_TEST_MACRO(CompileFeatures CompileFeatures)
   ADD_TEST_MACRO(CMakeCommands.target_compile_features target_compile_features)
 
-  # assume no resources building to test
-  set(TEST_RESOURCES FALSE)
-  # for windows and cygwin assume we have resources
-  if(WIN32 OR CYGWIN)
-    set(TEST_RESOURCES TRUE)
-  endif()
-  # for borland and watcom there is no resource support
-  if(WATCOM OR BORLAND)
-    set(TEST_RESOURCES FALSE)
-  endif()
-  if(TEST_RESOURCES)
+  if(CMake_TEST_RESOURCES)
     ADD_TEST_MACRO(VSResource VSResource)
     if (CMAKE_GENERATOR MATCHES "Ninja")
       add_test_macro(VSResourceNinjaForceRSP VSResourceNinjaForceRSP)
@@ -485,7 +486,6 @@ if(BUILD_TESTING)
     )
   list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Module/ExternalData")
 
-  ADD_TEST_MACRO(Module.GenerateExportHeader GenerateExportHeader)
   ADD_TEST_MACRO(Module.FindDependency FindDependency)
 
   ADD_TEST_MACRO(Module.WriteCompilerDetectionHeader WriteCompilerDetectionHeader)
@@ -569,60 +569,43 @@ if(BUILD_TESTING)
   ADD_LINK_FLAGS_TEST(mod_flags_config dll_flags_config)
   ADD_LINK_FLAGS_TEST(exe_flags_config mod_flags_config)
 
-  # If we are running right now with a UnixMakefiles based generator,
+  # If we are running right now with a Unix Makefiles or Ninja based generator,
   # build the "Simple" test with the ExtraGenerators, if available
   # This doesn't test whether the generated project files work (unfortunately),
   # mainly it tests that cmake doesn't crash when generating these project files.
-  if(${CMAKE_GENERATOR} MATCHES "Unix Makefiles"  OR  ${CMAKE_GENERATOR} MATCHES "KDevelop")
+  if(${CMAKE_GENERATOR} MATCHES "Unix Makefiles" OR ${CMAKE_GENERATOR} MATCHES "Ninja")
+
     # check which generators we have
     execute_process(COMMAND ${CMAKE_CMAKE_COMMAND} --help
       OUTPUT_VARIABLE cmakeOutput ERROR_VARIABLE cmakeOutput)
-    # check for the Eclipse generator
-    if ("${cmakeOutput}" MATCHES Eclipse)
-      add_test(Simple_EclipseGenerator ${CMAKE_CTEST_COMMAND}
-         --build-and-test
-         "${CMake_SOURCE_DIR}/Tests/Simple"
-         "${CMake_BINARY_DIR}/Tests/Simple_EclipseGenerator"
-         --build-two-config
-         --build-generator "Eclipse CDT4 - Unix Makefiles"
-         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
-         --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
-         --build-project Simple
-         --build-options ${build_options}
-         --test-command Simple)
-      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Simple_EclipseGenerator")
-    endif ()
 
-    # check for the CodeBlocks generator
-    if ("${cmakeOutput}" MATCHES CodeBlocks)
-      add_test(Simple_CodeBlocksGenerator ${CMAKE_CTEST_COMMAND}
-         --build-and-test
-         "${CMake_SOURCE_DIR}/Tests/Simple"
-         "${CMake_BINARY_DIR}/Tests/Simple_CodeBlocksGenerator"
-         --build-two-config
-         --build-generator "CodeBlocks - Unix Makefiles"
-         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
-         --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
-         --build-project Simple
-         --build-options ${build_options}
-         --test-command Simple)
-      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Simple_CodeBlocksGenerator")
-    endif ()
-    # check for the KDevelop3 generator
-    if ("${cmakeOutput}" MATCHES KDevelop3)
-      add_test(Simple_KDevelop3Generator ${CMAKE_CTEST_COMMAND}
-         --build-and-test
-         "${CMake_SOURCE_DIR}/Tests/Simple"
-         "${CMake_BINARY_DIR}/Tests/Simple_KDevelop3Generator"
-         --build-two-config
-         --build-generator "KDevelop3 - Unix Makefiles"
-         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
-         --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
-         --build-project Simple
-         --build-options ${build_options}
-         --test-command Simple)
-      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Simple_KDevelop3Generator")
-    endif ()
+    set(extraGenerators
+      "CodeBlocks"
+      "CodeLite"
+      "Eclipse CDT4"
+      "Kate"
+      "KDevelop3"
+      "Sublime Text 2")
+
+    foreach(extraGenerator ${extraGenerators})
+      if ("${cmakeOutput}" MATCHES "${extraGenerator} - ${CMAKE_GENERATOR}")
+        set(extraGeneratorTestName "Simple_${extraGenerator}Generator")
+        string(REPLACE " " "" extraGeneratorTestName ${extraGeneratorTestName})
+
+        add_test(${extraGeneratorTestName} ${CMAKE_CTEST_COMMAND}
+          --build-and-test
+          "${CMake_SOURCE_DIR}/Tests/Simple"
+          "${CMake_BINARY_DIR}/Tests/${extraGeneratorTestName}"
+          --build-two-config
+          --build-generator "${extraGenerator} - ${CMAKE_GENERATOR}"
+          --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
+          --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
+          --build-project Simple
+          --build-options ${build_options}
+          --test-command Simple)
+        list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/${extraGeneratorTestName}")
+      endif ()
+    endforeach(extraGenerator)
 
   endif()
 
@@ -693,8 +676,6 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
       win64_release.cmake)
     ADD_NIGHTLY_BUILD_TEST(CMakeNightlyOSX
       osx_release.cmake)
-    ADD_NIGHTLY_BUILD_TEST(CMakeNightlyLinux32
-      linux32_release.cmake)
     ADD_NIGHTLY_BUILD_TEST(CMakeNightlyLinux64
       linux64_release.cmake)
     set_property(TEST CMakeNightlyWin64 PROPERTY DEPENDS CMakeNightlyWin32)
@@ -954,6 +935,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     set(CPackComponents_BUILD_OPTIONS)
     if(APPLE)
       set(CPackComponents_BUILD_OPTIONS -DCPACK_BINARY_DRAGNDROP:BOOL=ON)
+      if(CMake_TEST_XCODE_VERSION VERSION_GREATER "4.6")
+        set(CPackComponents_BUILD_OPTIONS ${CPackComponents_BUILD_OPTIONS}
+          -DCPACK_BINARY_PRODUCTBUILD:BOOL=ON)
+      endif()
     endif()
     if(NSIS_MAKENSIS_EXECUTABLE)
       set(CPackComponents_BUILD_OPTIONS ${CPackComponents_BUILD_OPTIONS}
@@ -998,6 +983,9 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     list(APPEND ACTIVE_CPACK_GENERATORS "ZIP")
     if(APPLE)
       list(APPEND ACTIVE_CPACK_GENERATORS "DragNDrop")
+      if(CMake_TEST_XCODE_VERSION VERSION_GREATER "4.6")
+        list(APPEND ACTIVE_CPACK_GENERATORS "productbuild")
+      endif()
     endif()
 
     # set up list of component packaging ways
@@ -1108,6 +1096,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     set(CPackComponents_BUILD_OPTIONS)
     if(APPLE)
       set(CPackComponents_BUILD_OPTIONS -DCPACK_BINARY_DRAGNDROP:BOOL=ON)
+      if(CMake_TEST_XCODE_VERSION VERSION_GREATER "4.6")
+        set(CPackComponents_BUILD_OPTIONS ${CPackComponents_BUILD_OPTIONS}
+          -DCPACK_BINARY_PRODUCTBUILD:BOOL=ON)
+      endif()
     endif()
     if(NOT NSIS_MAKENSIS_EXECUTABLE)
       set(CPackComponents_BUILD_OPTIONS ${CPackComponents_BUILD_OPTIONS}
@@ -1365,6 +1357,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     add_subdirectory(FindBoost)
   endif()
 
+  if(CMake_TEST_FindBZip2)
+    add_subdirectory(FindBZip2)
+  endif()
+
   if(CMake_TEST_FindGSL)
     add_subdirectory(FindGSL)
   endif()
@@ -1373,14 +1369,26 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     add_subdirectory(FindGTest)
   endif()
 
+  if(CMake_TEST_FindICU)
+    add_subdirectory(FindICU)
+  endif()
+
   if(CMake_TEST_FindJsonCpp)
     add_subdirectory(FindJsonCpp)
   endif()
 
+  if(CMake_TEST_FindLibUV)
+    add_subdirectory(FindLibUV)
+  endif()
+
   if(CMake_TEST_FindLTTngUST)
     add_subdirectory(FindLTTngUST)
   endif()
 
+  if(CMake_TEST_FindOpenCL)
+    add_subdirectory(FindOpenCL)
+  endif()
+
   if(CMake_TEST_FindOpenSSL)
     add_subdirectory(FindOpenSSL)
   endif()
@@ -1393,6 +1401,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     add_subdirectory(FindTIFF)
   endif()
 
+  if(CMake_TEST_FindVulkan)
+    add_subdirectory(FindVulkan)
+  endif()
+
   if(CMake_TEST_FindXalanC)
     add_subdirectory(FindXalanC)
   endif()
@@ -1405,8 +1417,9 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
 
   # Matlab module
   if(CMake_TEST_FindMatlab)
-    ADD_TEST_MACRO(FindMatlab.basic_checks      ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>)
-    ADD_TEST_MACRO(FindMatlab.versions_checks   ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>)
+    ADD_TEST_MACRO(FindMatlab.basic_checks      ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
+    ADD_TEST_MACRO(FindMatlab.versions_checks   ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
+    ADD_TEST_MACRO(FindMatlab.components_checks ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
   endif()
 
   find_package(GTK2 QUIET)
@@ -1441,6 +1454,18 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     )
   list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectSubdir")
 
+  add_test(NAME ExternalProjectSourceSubdir
+    COMMAND ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+    --build-and-test
+    "${CMake_SOURCE_DIR}/Tests/ExternalProjectSourceSubdir"
+    "${CMake_BINARY_DIR}/Tests/ExternalProjectSourceSubdir"
+    ${build_generator_args}
+    --build-project ExternalProjectSourceSubdir
+    --force-new-ctest-process
+    --build-options ${build_options}
+    )
+  list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectSourceSubdir")
+
   add_test(ExternalProjectLocal ${CMAKE_CTEST_COMMAND}
     --build-and-test
     "${CMake_SOURCE_DIR}/Tests/ExternalProjectLocal"
@@ -2141,6 +2166,9 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     if(vs12)
       add_test_VSNsightTegra(vs12 "Visual Studio 12 2013")
     endif()
+    if(vs14)
+      add_test_VSNsightTegra(vs14 "Visual Studio 14 2015")
+    endif()
   endif()
 
   if (APPLE)
@@ -2698,6 +2726,15 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
   ADD_TEST_MACRO(CMakeCommands.target_compile_definitions target_compile_definitions)
   ADD_TEST_MACRO(CMakeCommands.target_compile_options target_compile_options)
 
+  if(CMake_TEST_SERVER_MODE)
+    # The cmake server-mode test requires python for a simple client.
+    find_package(PythonInterp QUIET)
+    if(PYTHON_EXECUTABLE)
+      set(Server_BUILD_OPTIONS -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE})
+      ADD_TEST_MACRO(Server Server)
+    endif()
+  endif()
+
   configure_file(
     "${CMake_SOURCE_DIR}/Tests/CTestTestCrash/test.cmake.in"
     "${CMake_BINARY_DIR}/Tests/CTestTestCrash/test.cmake"
@@ -3064,10 +3101,23 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
       --build-project testf
       --build-two-config
       --build-options ${build_options}
-        -DCMake_TEST_NESTED_MAKE_PROGRAM:FILEPATH=${CMake_TEST_EXPLICIT_MAKE_PROGRAM}
       --test-command testf)
     list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Fortran")
 
+    if(CMAKE_Fortran_COMPILER_SUPPORTS_F90)
+      add_test(FortranModules ${CMAKE_CTEST_COMMAND}
+        --build-and-test
+        "${CMake_SOURCE_DIR}/Tests/FortranModules"
+        "${CMake_BINARY_DIR}/Tests/FortranModules"
+        ${build_generator_args}
+        --build-project FortranModules
+        --build-options ${build_options}
+          -DCMake_TEST_NESTED_MAKE_PROGRAM:FILEPATH=${CMake_TEST_EXPLICIT_MAKE_PROGRAM}
+          -DCMake_TEST_Fortran_SUBMODULES:BOOL=${CMake_TEST_Fortran_SUBMODULES}
+        )
+      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/FortranModules")
+    endif()
+
     # FortranCInterface tests.
     if(UNIX)
       configure_file(${CMAKE_CURRENT_SOURCE_DIR}/FortranC/Flags.cmake.in
@@ -3092,6 +3142,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
   find_package(Java COMPONENTS Development QUIET)
   if(Java_JAVA_EXECUTABLE AND Java_JAVAC_EXECUTABLE AND Java_JAR_EXECUTABLE AND NOT MINGW
       AND NOT "${CMAKE_GENERATOR}" MATCHES "Xcode")
+
+    set(JavaExportImport_BUILD_OPTIONS -DCMake_TEST_NESTED_MAKE_PROGRAM:FILEPATH=${CMake_TEST_EXPLICIT_MAKE_PROGRAM})
+    ADD_TEST_MACRO(JavaExportImport JavaExportImport)
+
     get_filename_component(JNIPATH ${JAVA_COMPILE} PATH)
     find_file(JNI_H jni.h
       "${JNIPATH}/../include"
diff --git a/Tests/CMakeOnly/CheckCXXSymbolExists/CMakeLists.txt b/Tests/CMakeOnly/CheckCXXSymbolExists/CMakeLists.txt
index 9528aa3..f058c19 100644
--- a/Tests/CMakeOnly/CheckCXXSymbolExists/CMakeLists.txt
+++ b/Tests/CMakeOnly/CheckCXXSymbolExists/CMakeLists.txt
@@ -50,7 +50,7 @@ else ()
 endif ()
 
 if (CMAKE_COMPILER_IS_GNUCXX)
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
+  string(APPEND CMAKE_CXX_FLAGS " -O3")
   unset(CSE_RESULT_O3 CACHE)
   message(STATUS "Testing with optimization -O3")
 
diff --git a/Tests/CMakeOnly/CheckStructHasMember/CMakeLists.txt b/Tests/CMakeOnly/CheckStructHasMember/CMakeLists.txt
index f06d5c3..a584505 100644
--- a/Tests/CMakeOnly/CheckStructHasMember/CMakeLists.txt
+++ b/Tests/CMakeOnly/CheckStructHasMember/CMakeLists.txt
@@ -77,7 +77,7 @@ endforeach()
 set(CMAKE_TRY_COMPILE_CONFIGURATION ${CMAKE_BUILD_TYPE})
 
 if (CMAKE_COMPILER_IS_GNUCC)
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
+    string(APPEND CMAKE_C_FLAGS " -O3")
     unset(CSHM_RESULT_O3 CACHE)
     unset(CSHM_RESULT_O3_C CACHE)
     unset(CSHM_RESULT_O3_CXX CACHE)
diff --git a/Tests/CMakeOnly/CheckSymbolExists/CMakeLists.txt b/Tests/CMakeOnly/CheckSymbolExists/CMakeLists.txt
index 7656577..7f01463 100644
--- a/Tests/CMakeOnly/CheckSymbolExists/CMakeLists.txt
+++ b/Tests/CMakeOnly/CheckSymbolExists/CMakeLists.txt
@@ -39,7 +39,7 @@ else ()
 endif ()
 
 if (CMAKE_COMPILER_IS_GNUCC)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
+  string(APPEND CMAKE_C_FLAGS " -O3")
   unset(CSE_RESULT_O3 CACHE)
   message(STATUS "Testing with optimization -O3")
 
diff --git a/Tests/CMakeOnly/find_library/CMakeLists.txt b/Tests/CMakeOnly/find_library/CMakeLists.txt
index 2d4ecaf..9958650 100644
--- a/Tests/CMakeOnly/find_library/CMakeLists.txt
+++ b/Tests/CMakeOnly/find_library/CMakeLists.txt
@@ -33,16 +33,23 @@ endmacro()
 
 set(CMAKE_FIND_LIBRARY_PREFIXES "lib")
 set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
+set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS TRUE)
 set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS TRUE)
 
 set(CMAKE_SIZEOF_VOID_P 4)
 foreach(lib
+    lib/32/libtest5.a
     lib/A/lib/libtest1.a
+    lib/A/lib32/libtest3.a
     lib/A/libtest1.a
     lib/libtest1.a
     lib/libtest2.a
     lib/libtest3.a
     lib/libtest3.a
+    lib32/A/lib/libtest2.a
+    lib32/A/lib32/libtest4.a
+    lib32/A/libtest4.a
+    lib32/libtest4.a
     )
   test_find_library_subst(${lib})
 endforeach()
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib/32/libtest5.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib/32/libtest5.a
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib/A/lib32/libtest3.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib/A/lib32/libtest3.a
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib32/A/lib/libtest2.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib32/A/lib/libtest2.a
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib32/A/lib32/libtest4.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib32/A/lib32/libtest4.a
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib32/A/libtest4.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib32/A/libtest4.a
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/CMakeOnly/find_library/lib32/libtest4.a
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/CMakeOnly/find_library/lib32/libtest4.a
diff --git a/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in b/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
index da614e9..1313dbf 100644
--- a/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
+++ b/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
@@ -112,6 +112,12 @@ set(linux64_test3_libs "gfortran;m;quadmath;m;c")
 set(linux64_test3_dirs "/usr/lib/gcc/x86_64-redhat-linux/5.1.1;/usr/lib64;/lib64;/usr/lib")
 list(APPEND platforms linux64_test3)
 
+# clang -fsanitize=memory
+set(linux64_clang_sanitize_memory_text [[ "/usr/bin/ld" --hash-style=both --build-id --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o a.out /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crt1.o /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crti.o /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/crtbegin.o -L/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0 -L/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu -L/ [...]
+set(linux64_clang_sanitize_memory_libs "pthread;rt;m;dl;c")
+set(linux64_clang_sanitize_memory_dirs "/usr/lib/gcc/x86_64-linux-gnu/5.4.0;/usr/lib/x86_64-linux-gnu;/lib/x86_64-linux-gnu;/lib64;/usr/lib;/usr/lib/llvm-3.8/lib;/lib")
+list(APPEND platforms linux64_clang_sanitize_memory)
+
 #-----------------------------------------------------------------------------
 # Mac
 
diff --git a/Tests/CMakeTests/ModuleNoticesTest.cmake.in b/Tests/CMakeTests/ModuleNoticesTest.cmake.in
index 8ecebd3..7ae6607 100644
--- a/Tests/CMakeTests/ModuleNoticesTest.cmake.in
+++ b/Tests/CMakeTests/ModuleNoticesTest.cmake.in
@@ -1,21 +1,8 @@
-# Regex to match copyright/license notices.
-# We require the Kitware copyright on the first line, but this can
-# match any additional copyright holder notices.
-set(notice_regex "
-#=============================================================================
-# Copyright (20[0-9][0-9]-)?20[0-9][0-9] [^\n]+(
-# Copyright (20[0-9][0-9]-)?20[0-9][0-9] [^\n]+)*
-#
-# Distributed under the OSI-approved BSD License \\(the \"License\"\\);
-# see accompanying file Copyright\\.txt for details\\.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE\\.
-# See the License for more information\\.
-#=============================================================================
-# \\(To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.\\)
-")
+# Regex to match license notices at the top of module files.
+set(notice_regex [[^# Distributed under the OSI-approved BSD 3-Clause License\.  See accompanying
+# file Copyright\.txt or https://cmake\.org/licensing for details\.
+
+]])
 string(REPLACE "\n" "\r?\n" notice_regex "${notice_regex}")
 string(REPLACE "\r\r" "\r" notice_regex "${notice_regex}")
 
@@ -35,7 +22,7 @@ foreach(module ${all_modules})
   message(STATUS "module: ${module}")
   file(READ "${dir}/${module}" module_content)
   if(NOT "${module_content}" MATCHES "${notice_regex}")
-    set(notice_missing "${notice_missing}  ${module}\n")
+    string(APPEND notice_missing "  ${module}\n")
   endif()
 endforeach()
 
diff --git a/Tests/CMakeTests/String-TIMESTAMP-MonthWeekNames.cmake b/Tests/CMakeTests/String-TIMESTAMP-MonthWeekNames.cmake
new file mode 100644
index 0000000..1cd44ff
--- /dev/null
+++ b/Tests/CMakeTests/String-TIMESTAMP-MonthWeekNames.cmake
@@ -0,0 +1,11 @@
+string(TIMESTAMP output "%a;%b")
+message("~${output}~")
+
+list(LENGTH output output_length)
+
+set(expected_output_length 2)
+
+if(NOT output_length EQUAL ${expected_output_length})
+    message(FATAL_ERROR "expected ${expected_output_length} entries in output "
+        "with all specifiers; found ${output_length}")
+endif()
diff --git a/Tests/CMakeTests/StringTest.cmake.in b/Tests/CMakeTests/StringTest.cmake.in
index aba35fe..a45b205 100644
--- a/Tests/CMakeTests/StringTest.cmake.in
+++ b/Tests/CMakeTests/StringTest.cmake.in
@@ -36,6 +36,8 @@ set(TIMESTAMP-IncompleteSpecifier-RESULT 0)
 set(TIMESTAMP-IncompleteSpecifier-STDERR "~foobar%~")
 set(TIMESTAMP-AllSpecifiers-RESULT 0)
 set(TIMESTAMP-AllSpecifiers-STDERR "~[0-9]+(;[0-9]+)*~")
+set(TIMESTAMP-MonthWeekNames-RESULT 0)
+set(TIMESTAMP-MonthWeekNames-STDERR "~[^%]+;[^%]+~")
 set(TIMESTAMP-UnixTime-RESULT 0)
 set(TIMESTAMP-UnixTime-STDERR "~[1-9][0-9]+~")
 
@@ -60,6 +62,7 @@ check_cmake_test(String
   TIMESTAMP-UnknownSpecifier
   TIMESTAMP-IncompleteSpecifier
   TIMESTAMP-AllSpecifiers
+  TIMESTAMP-MonthWeekNames
   TIMESTAMP-UnixTime
   )
 
diff --git a/Tests/CMakeTests/VersionTest.cmake.in b/Tests/CMakeTests/VersionTest.cmake.in
index 4e946ab..f045605 100644
--- a/Tests/CMakeTests/VersionTest.cmake.in
+++ b/Tests/CMakeTests/VersionTest.cmake.in
@@ -83,10 +83,24 @@ foreach(v IN LISTS LESSV)
     message(FATAL_ERROR "${CMAKE_MATCH_2} is less than ${CMAKE_MATCH_1}?")
   endif()
 
+  # check greater or equal (same as less negative)
+  if(CMAKE_MATCH_2 VERSION_GREATER_EQUAL CMAKE_MATCH_1)
+    message(STATUS "${CMAKE_MATCH_2} is not less than ${CMAKE_MATCH_1}")
+  else()
+    message(FATAL_ERROR "${CMAKE_MATCH_2} is less than ${CMAKE_MATCH_1}?")
+  endif()
+
   # check greater negative case
   if(NOT CMAKE_MATCH_1 VERSION_GREATER CMAKE_MATCH_2)
     message(STATUS "${CMAKE_MATCH_1} is not greater than ${CMAKE_MATCH_2}")
   else()
     message(FATAL_ERROR "${CMAKE_MATCH_1} is greater than ${CMAKE_MATCH_2}?")
   endif()
+
+  # check less or equal (same as greater negative) case
+  if(CMAKE_MATCH_1 VERSION_LESS_EQUAL CMAKE_MATCH_2)
+    message(STATUS "${CMAKE_MATCH_1} is not greater than ${CMAKE_MATCH_2}")
+  else()
+    message(FATAL_ERROR "${CMAKE_MATCH_1} is greater than ${CMAKE_MATCH_2}?")
+  endif()
 endforeach()
diff --git a/Tests/CMakeTests/WhileTest.cmake.in b/Tests/CMakeTests/WhileTest.cmake.in
index cc22978..9066544 100644
--- a/Tests/CMakeTests/WhileTest.cmake.in
+++ b/Tests/CMakeTests/WhileTest.cmake.in
@@ -2,13 +2,13 @@ set(NUMBERS "")
 set(COUNT 0)
 
 while(COUNT LESS 200)
-    set(NUMBERS "${NUMBERS} ${COUNT}")
+    string(APPEND NUMBERS " ${COUNT}")
     set(COUNT "2${COUNT}")
 
     set(NCOUNT 3)
     while(NCOUNT LESS 31)
-        set(NUMBERS "${NUMBERS} ${NCOUNT}")
-        set(NCOUNT "${NCOUNT}0")
+        string(APPEND NUMBERS " ${NCOUNT}")
+        string(APPEND NCOUNT "0")
     endwhile()
 endwhile()
 
diff --git a/Tests/CPackComponents/Issue 7470.html b/Tests/CPackComponents/Issue 7470.html
index 12df2c8..c2a1688 100644
--- a/Tests/CPackComponents/Issue 7470.html	
+++ b/Tests/CPackComponents/Issue 7470.html	
@@ -3,7 +3,7 @@
 The install rule for this file demonstrates the problem described in<br/>
 CMake issue #7470:<br/>
 <br/>
-<a href="http://public.kitware.com/Bug/view.php?id=7470">
-http://public.kitware.com/Bug/view.php?id=7470</a><br/>
+<a href="https://gitlab.kitware.com/cmake/cmake/issues/7470">
+https://gitlab.kitware.com/cmake/cmake/issues/7470</a><br/>
 </body>
 </html>
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
index d51650c..f1391cd 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
@@ -41,7 +41,7 @@ if(LINTIAN_EXECUTABLE)
                                   FILENAME "${_f}"
                                   ERROR_REGEX_STRINGS "${STRINGS_TO_AVOID}")
 
-    set(lintian_output_errors_all "${lintian_output_errors_all}${lintian_output_errors}")
+    string(APPEND lintian_output_errors_all "${lintian_output_errors}")
   endforeach()
 
   if(NOT "${lintian_output_errors_all}" STREQUAL "")
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult.cmake
index b4e567c..2f9e2fc 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult.cmake
@@ -126,7 +126,7 @@ function(lintian_check_specific_errors output_errors)
     string(REGEX MATCHALL "${_s}" "_TMP_CHECK_ERROR" "${lintian_output}")
 
     if(NOT "${_TMP_CHECK_ERROR}" STREQUAL "")
-      set(ERROR_ACC "${ERROR_ACC}\nlintian: ${_f}: output contains an undesirable regex:\n\t${_TMP_CHECK_ERROR}")
+      string(APPEND ERROR_ACC "\nlintian: ${_f}: output contains an undesirable regex:\n\t${_TMP_CHECK_ERROR}")
     endif()
   endforeach()
 
diff --git a/Tests/CTestLimitDashJ/CMakeLists.txt b/Tests/CTestLimitDashJ/CMakeLists.txt
index 0c5950c..92d743f 100644
--- a/Tests/CTestLimitDashJ/CMakeLists.txt
+++ b/Tests/CTestLimitDashJ/CMakeLists.txt
@@ -1,7 +1,7 @@
 cmake_minimum_required(VERSION 2.8)
 project(CTestLimitDashJ NONE)
 
-# This file demonstrates http://public.kitware.com/Bug/view.php?id=12904
+# This file demonstrates https://gitlab.kitware.com/cmake/cmake/issues/12904
 # when configured with CMake 2.8.10.2 and earlier, and when running
 # "ctest -j 4" in the resulting build tree. This example is hard-coded
 # to assume -j 4 just to reproduce the issue easily. Adjust the
diff --git a/Tests/CTestTestStopTime/GetDate.cmake b/Tests/CTestTestStopTime/GetDate.cmake
index edc6519..1f4cb24 100644
--- a/Tests/CTestTestStopTime/GetDate.cmake
+++ b/Tests/CTestTestStopTime/GetDate.cmake
@@ -106,11 +106,11 @@ macro(ADD_SECONDS sec)
   set(new_min ${${GD_PREFIX}MINUTE})
   set(new_hr ${${GD_PREFIX}HOUR})
   math(EXPR new_sec "${sec} + ${${GD_PREFIX}SECOND}")
-  while(${new_sec} GREATER 60 OR ${new_sec} EQUAL 60)
+  while(${new_sec} GREATER_EQUAL 60)
     math(EXPR new_sec "${new_sec} - 60")
     math(EXPR new_min "${${GD_PREFIX}MINUTE} + 1")
   endwhile()
-  while(${new_min} GREATER 60 OR ${new_min} EQUAL 60)
+  while(${new_min} GREATER_EQUAL 60)
     math(EXPR new_min "${new_min} - 60")
     math(EXPR new_hr "${${GD_PREFIX}HOUR} + 1")
   endwhile()
diff --git a/Tests/CTestUpdateBZR.cmake.in b/Tests/CTestUpdateBZR.cmake.in
index 8fb1d34..da181d2 100644
--- a/Tests/CTestUpdateBZR.cmake.in
+++ b/Tests/CTestUpdateBZR.cmake.in
@@ -4,7 +4,7 @@
 #-----------------------------------------------------------------------------
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
-set(TOP "${TOP}/@CTestUpdateBZR_DIR@")
+string(APPEND TOP "/@CTestUpdateBZR_DIR@")
 
 # Include code common to all update tests.
 include("@CMAKE_CURRENT_SOURCE_DIR@/CTestUpdateCommon.cmake")
diff --git a/Tests/CTestUpdateCVS.cmake.in b/Tests/CTestUpdateCVS.cmake.in
index 277b3a6..5389bdf 100644
--- a/Tests/CTestUpdateCVS.cmake.in
+++ b/Tests/CTestUpdateCVS.cmake.in
@@ -4,7 +4,7 @@
 #-----------------------------------------------------------------------------
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
-set(TOP "${TOP}/@CTestUpdateCVS_DIR@")
+string(APPEND TOP "/@CTestUpdateCVS_DIR@")
 set(UPDATE_NOT_GLOBAL 1)
 set(UPDATE_MAYBE Updated{CTestConfig.cmake})
 
diff --git a/Tests/CTestUpdateCommon.cmake b/Tests/CTestUpdateCommon.cmake
index 458e427..61aa13b 100644
--- a/Tests/CTestUpdateCommon.cmake
+++ b/Tests/CTestUpdateCommon.cmake
@@ -84,9 +84,9 @@ function(check_updates build)
   set(MSG "")
   if(MISSING)
     # List the missing entries
-    set(MSG "${MSG}Update.xml is missing expected entries:\n")
+    string(APPEND MSG "Update.xml is missing expected entries:\n")
     foreach(f ${MISSING})
-      set(MSG "${MSG}  ${f}\n")
+      string(APPEND MSG "  ${f}\n")
     endforeach()
   else()
     # Success
@@ -96,9 +96,9 @@ function(check_updates build)
   # Report the result
   if(EXTRA)
     # List the extra entries
-    set(MSG "${MSG}Update.xml has extra unexpected entries:\n")
+    string(APPEND MSG "Update.xml has extra unexpected entries:\n")
     foreach(f ${EXTRA})
-      set(MSG "${MSG}  ${f}\n")
+      string(APPEND MSG "  ${f}\n")
     endforeach()
   else()
     # Success
@@ -112,9 +112,9 @@ function(check_updates build)
     if(UPDATE_LOG_FILE)
       file(READ ${UPDATE_LOG_FILE} UPDATE_LOG LIMIT ${max_update_xml_size})
       string(REPLACE "\n" "\n  " UPDATE_LOG "${UPDATE_LOG}")
-      set(MSG "${MSG}Update log:\n  ${UPDATE_LOG}")
+      string(APPEND MSG "Update log:\n  ${UPDATE_LOG}")
     else()
-      set(MSG "${MSG}No update log found!")
+      string(APPEND MSG "No update log found!")
     endif()
 
     # Display the error message
diff --git a/Tests/CTestUpdateGIT.cmake.in b/Tests/CTestUpdateGIT.cmake.in
index 46230cc..7d0fa0f 100644
--- a/Tests/CTestUpdateGIT.cmake.in
+++ b/Tests/CTestUpdateGIT.cmake.in
@@ -4,7 +4,7 @@
 #-----------------------------------------------------------------------------
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
-set(TOP "${TOP}/@CTestUpdateGIT_DIR@")
+string(APPEND TOP "/@CTestUpdateGIT_DIR@")
 set(UPDATE_EXTRA Updated{module})
 
 # Include code common to all update tests.
diff --git a/Tests/CTestUpdateHG.cmake.in b/Tests/CTestUpdateHG.cmake.in
index c76bf91..055d309 100644
--- a/Tests/CTestUpdateHG.cmake.in
+++ b/Tests/CTestUpdateHG.cmake.in
@@ -4,7 +4,7 @@
 #-----------------------------------------------------------------------------
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
-set(TOP "${TOP}/@CTestUpdateHG_DIR@")
+string(APPEND TOP "/@CTestUpdateHG_DIR@")
 
 # Include code common to all update tests.
 include("@CMAKE_CURRENT_SOURCE_DIR@/CTestUpdateCommon.cmake")
diff --git a/Tests/CTestUpdateP4.cmake.in b/Tests/CTestUpdateP4.cmake.in
index f0420c4..5eef9fb 100644
--- a/Tests/CTestUpdateP4.cmake.in
+++ b/Tests/CTestUpdateP4.cmake.in
@@ -5,7 +5,7 @@
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
 set(P4_TOP "${TOP}")
-set(TOP "${TOP}/@CTestUpdateP4_DIR@")
+string(APPEND TOP "/@CTestUpdateP4_DIR@")
 
 # Include code common to all update tests.
 set(REPOSITORY_FILE_PREFIX "//ctest/")
@@ -48,9 +48,9 @@ if(UNIX)
   file(MAKE_DIRECTORY ${P4_ROOT})
 
   set(P4_SERVER "nohup '${P4D}' -d -r '${P4_ROOT}'")
-  set(P4_SERVER "${P4_SERVER} -L '${P4_ROOT}/p4.log'")
-  set(P4_SERVER "${P4_SERVER} -J '${P4_ROOT}/journal'")
-  set(P4_SERVER "${P4_SERVER} -p ${P4_PORT} >/dev/null 2>&1 &")
+  string(APPEND P4_SERVER " -L '${P4_ROOT}/p4.log'")
+  string(APPEND P4_SERVER " -J '${P4_ROOT}/journal'")
+  string(APPEND P4_SERVER " -p ${P4_PORT} >/dev/null 2>&1 &")
 
   message("Server command line: ${P4_SERVER}")
 
diff --git a/Tests/CTestUpdateSVN.cmake.in b/Tests/CTestUpdateSVN.cmake.in
index b757a44..12a3526 100644
--- a/Tests/CTestUpdateSVN.cmake.in
+++ b/Tests/CTestUpdateSVN.cmake.in
@@ -4,7 +4,7 @@
 #-----------------------------------------------------------------------------
 # Test in a directory next to this script.
 get_filename_component(TOP "${CMAKE_CURRENT_LIST_FILE}" PATH)
-set(TOP "${TOP}/@CTestUpdateSVN_DIR@")
+string(APPEND TOP "/@CTestUpdateSVN_DIR@")
 set(UPDATE_GLOBAL_ELEMENTS SVNPath)
 
 # Include code common to all update tests.
diff --git a/Tests/CheckFortran.cmake b/Tests/CheckFortran.cmake
index ebbb426..93990ad 100644
--- a/Tests/CheckFortran.cmake
+++ b/Tests/CheckFortran.cmake
@@ -1,16 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
-#=============================================================================
-# Copyright 2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
 
 if(NOT DEFINED CMAKE_Fortran_COMPILER)
   set(_desc "Looking for a Fortran compiler")
@@ -22,6 +12,7 @@ project(CheckFortran Fortran)
 file(WRITE \"\${CMAKE_CURRENT_BINARY_DIR}/result.cmake\"
   \"set(CMAKE_Fortran_COMPILER \\\"\${CMAKE_Fortran_COMPILER}\\\")\\n\"
   \"set(CMAKE_Fortran_FLAGS \\\"\${CMAKE_Fortran_FLAGS}\\\")\\n\"
+  \"set(CMAKE_Fortran_COMPILER_SUPPORTS_F90 \\\"\${CMAKE_Fortran_COMPILER_SUPPORTS_F90}\\\")\\n\"
   )
 ")
   execute_process(
@@ -47,4 +38,6 @@ file(WRITE \"\${CMAKE_CURRENT_BINARY_DIR}/result.cmake\"
   mark_as_advanced(CMAKE_Fortran_COMPILER)
   set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS}" CACHE STRING "Fortran flags")
   mark_as_advanced(CMAKE_Fortran_FLAGS)
+  set(CMAKE_Fortran_COMPILER_SUPPORTS_F90 "${CMAKE_Fortran_COMPILER_SUPPORTS_F90}" CACHE BOOL "Fortran compiler supports F90")
+  mark_as_advanced(CMAKE_Fortran_COMPILER_SUPPORTS_F90)
 endif()
diff --git a/Tests/Complex/CMakeLists.txt b/Tests/Complex/CMakeLists.txt
index 83ca7f4..075faa7 100644
--- a/Tests/Complex/CMakeLists.txt
+++ b/Tests/Complex/CMakeLists.txt
@@ -40,7 +40,7 @@ endforeach()
 # Test building without per-rule echo lines in Makefiles.
 set_property(GLOBAL PROPERTY RULE_MESSAGES OFF)
 
-set(CPACK_SOURCE_IGNORE_FILES "~$;\\.cvsignore$;^C:/hoffman/My Builds/testcase.*/CVS/;^C:/hoffman/My Builds/testcase.*/\\.svn/;^C:/hoffman/My Builds/testcase.*/sweigart/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/eos2001/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_tables_new/;^C:/hoffman/My Builds/testcase/COPYING$;^C:/hoffman/My Builds/testcase/INSTALL$;^C:/hoffman/My Builds/testcase/Makefile$;^C:/hoffman/My Builds/testcase/Makefile\\.in$;^C:/hoffman/My Builds/t [...]
+set(CPACK_SOURCE_IGNORE_FILES "~$;^C:/hoffman/My Builds/testcase.*/CVS/;^C:/hoffman/My Builds/testcase.*/\\.svn/;^C:/hoffman/My Builds/testcase.*/sweigart/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/eos2001/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_tables_new/;^C:/hoffman/My Builds/testcase/COPYING$;^C:/hoffman/My Builds/testcase/INSTALL$;^C:/hoffman/My Builds/testcase/Makefile$;^C:/hoffman/My Builds/testcase/Makefile\\.in$;^C:/hoffman/My Builds/testcase/.*\\.l [...]
 
 #
 # Define a macro
@@ -92,10 +92,16 @@ endif()
 if(NOT 2.4 EQUAL 2.4)
   message(FATAL_ERROR "Failed: NOT 2.4 EQUAL 2.4")
 endif()
+if(NOT 2.4 LESS_EQUAL 2.4)
+  message(FATAL_ERROR "Failed: NOT 2.4 LESS_EQUAL 2.4")
+endif()
+if(NOT 2.4 GREATER_EQUAL 2.4)
+  message(FATAL_ERROR "Failed: NOT 2.4 GREATER_EQUAL 2.4")
+endif()
 
 if(CMAKE_SYSTEM MATCHES "OSF1-V")
   if(NOT CMAKE_COMPILER_IS_GNUCXX)
-     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -timplicit_local -no_implicit_include ")
+     string(APPEND CMAKE_CXX_FLAGS " -timplicit_local -no_implicit_include ")
   endif()
 endif()
 
@@ -436,7 +442,7 @@ set(CMAKE_CXX_EXTENSIONS TRUE)
 # template support also need a flag to use the newer C++ library.
 if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
     CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA")
+  string(APPEND CMAKE_CXX_FLAGS " -AA")
 endif ()
 
 # Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
diff --git a/Tests/Complex/Executable/CMakeLists.txt b/Tests/Complex/Executable/CMakeLists.txt
index c30dcbc..2a79629 100644
--- a/Tests/Complex/Executable/CMakeLists.txt
+++ b/Tests/Complex/Executable/CMakeLists.txt
@@ -1,8 +1,8 @@
 #
 # Create exe.
 #
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DTEST_CXX_FLAGS")
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST_C_FLAGS")
+string(APPEND CMAKE_CXX_FLAGS " -DTEST_CXX_FLAGS")
+string(APPEND CMAKE_C_FLAGS " -DTEST_C_FLAGS")
 
 # Create an imported target for if(TARGET) test below.
 add_library(ExeImportedTarget UNKNOWN IMPORTED)
diff --git a/Tests/Complex/Executable/complex.cxx b/Tests/Complex/Executable/complex.cxx
index 5f79ac0..3b09229 100644
--- a/Tests/Complex/Executable/complex.cxx
+++ b/Tests/Complex/Executable/complex.cxx
@@ -455,7 +455,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_LESS
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_LESS is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_LESS is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_LESS is defined.");
 #endif
@@ -467,7 +467,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_LESS2
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_LESS2 is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_LESS2 is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_LESS2 is defined.");
 #endif
@@ -478,6 +478,24 @@ int main()
   cmPassed("SHOULD_NOT_BE_DEFINED_GREATER is not defined.");
 #endif
 
+#ifndef SHOULD_BE_DEFINED_GREATER
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER2
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER2
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER2 is defined.");
+#endif
+
 #ifdef SHOULD_NOT_BE_DEFINED_EQUAL
   cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_EQUAL is defined.");
 #else
@@ -485,28 +503,93 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_EQUAL
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_EQUAL is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_EQUAL is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_EQUAL is defined.");
 #endif
 
-#ifndef SHOULD_BE_DEFINED_GREATER
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER is not defined.\n");
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL is defined.");
 #else
-  cmPassed("SHOULD_BE_DEFINED_GREATER is defined.");
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL is not defined.");
 #endif
 
-#ifdef SHOULD_NOT_BE_DEFINED_GREATER2
-  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER2 is defined.");
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL is not defined.");
 #else
-  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER2 is not defined.");
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL is defined.");
 #endif
 
-#ifndef SHOULD_BE_DEFINED_GREATER2
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL2
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER2 is not defined.\n");
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL2 is defined.");
 #else
-  cmPassed("SHOULD_BE_DEFINED_GREATER2 is defined.");
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL3 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL3 is defined.");
 #endif
 
 #ifdef SHOULD_NOT_BE_DEFINED_STRLESS
@@ -516,7 +599,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_STRLESS
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRLESS is defined.");
 #endif
@@ -528,8 +611,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_STRLESS2
-  cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS2 is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS2 is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRLESS2 is defined.");
 #endif
@@ -543,7 +625,7 @@ int main()
 
 #ifndef SHOULD_BE_DEFINED_STRGREATER
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER is not defined.\n");
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRGREATER is defined.");
 #endif
@@ -557,11 +639,95 @@ int main()
 
 #ifndef SHOULD_BE_DEFINED_STRGREATER2
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER2 is not defined.\n");
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER2 is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRGREATER2 is defined.");
 #endif
 
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL3 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2 is "
+           "defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL2
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL2 is not "
+           "defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3 is "
+           "defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL3
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL3 is not "
+           "defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL3 is defined.");
+#endif
+
 // ----------------------------------------------------------------------
 // Test FOREACH
 
diff --git a/Tests/Complex/Library/CMakeLists.txt b/Tests/Complex/Library/CMakeLists.txt
index f00cbd6..dbf806e 100644
--- a/Tests/Complex/Library/CMakeLists.txt
+++ b/Tests/Complex/Library/CMakeLists.txt
@@ -43,7 +43,7 @@ endif()
 #
 set(SharedLibrarySources sharedFile)
 add_library(CMakeTestLibraryShared SHARED ${SharedLibrarySources})
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST_C_FLAGS")
+string(APPEND CMAKE_C_FLAGS " -DTEST_C_FLAGS")
 add_library(CMakeTestCLibraryShared SHARED testConly.c)
 define_property(
   TARGET PROPERTY FOO
diff --git a/Tests/Complex/VarTests.cmake b/Tests/Complex/VarTests.cmake
index 70b803a..8be59be 100644
--- a/Tests/Complex/VarTests.cmake
+++ b/Tests/Complex/VarTests.cmake
@@ -126,6 +126,12 @@ else ()
   add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER)
 endif ()
 
+if (SNUM1_VAR GREATER SNUM2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER2)
+endif ()
+
 if (SNUM2_VAR EQUAL SNUM1_VAR)
   add_definitions(-DSHOULD_NOT_BE_DEFINED_EQUAL)
 else ()
@@ -138,10 +144,40 @@ else ()
   add_definitions(-DSHOULD_NOT_BE_DEFINED_EQUAL)
 endif ()
 
-if (SNUM1_VAR GREATER SNUM2_VAR)
-  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER2)
+if (SNUM1_VAR LESS_EQUAL SNUM2_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL)
 else ()
-  add_definitions(-DSHOULD_BE_DEFINED_GREATER2)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_LESS_EQUAL)
+endif ()
+
+if (SNUM2_VAR LESS_EQUAL SNUM1_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_LESS_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL2)
+endif ()
+
+if (SNUM1_VAR LESS_EQUAL SNUM3_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL3)
+endif ()
+
+if (SNUM2_VAR GREATER_EQUAL SNUM1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL)
+endif ()
+
+if (SNUM1_VAR GREATER_EQUAL SNUM2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL2)
+endif ()
+
+if (SNUM1_VAR GREATER_EQUAL SNUM3_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL3)
 endif ()
 
 set (SSTR1_VAR "abc")
@@ -171,6 +207,42 @@ else ()
   add_definitions(-DSHOULD_BE_DEFINED_STRGREATER2)
 endif ()
 
+if (SSTR1_VAR STRLESS_EQUAL SSTR2_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL)
+endif ()
+
+if (SSTR2_VAR STRLESS_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL2)
+endif ()
+
+if (SSTR1_VAR STRLESS_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3)
+endif ()
+
+if (SSTR2_VAR STRGREATER_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL)
+endif ()
+
+if (SSTR1_VAR STRGREATER_EQUAL SSTR2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL2)
+endif ()
+
+if (SSTR1_VAR STRGREATER_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3)
+endif ()
+
 #
 # Test FOREACH
 #
@@ -180,5 +252,5 @@ endforeach()
 
 set(FOREACH_CONCAT "")
 foreach (INDEX a;b;c;d;e;f;g)
-  set(FOREACH_CONCAT "${FOREACH_CONCAT}${INDEX}")
+  string(APPEND FOREACH_CONCAT "${INDEX}")
 endforeach()
diff --git a/Tests/ComplexOneConfig/CMakeLists.txt b/Tests/ComplexOneConfig/CMakeLists.txt
index 2d92809..1b833b2 100644
--- a/Tests/ComplexOneConfig/CMakeLists.txt
+++ b/Tests/ComplexOneConfig/CMakeLists.txt
@@ -33,7 +33,7 @@ endforeach()
 # Test building without per-rule echo lines in Makefiles.
 set_property(GLOBAL PROPERTY RULE_MESSAGES OFF)
 
-set(CPACK_SOURCE_IGNORE_FILES "~$;\\.cvsignore$;^C:/hoffman/My Builds/testcase.*/CVS/;^C:/hoffman/My Builds/testcase.*/\\.svn/;^C:/hoffman/My Builds/testcase.*/sweigart/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/eos2001/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_tables_new/;^C:/hoffman/My Builds/testcase/COPYING$;^C:/hoffman/My Builds/testcase/INSTALL$;^C:/hoffman/My Builds/testcase/Makefile$;^C:/hoffman/My Builds/testcase/Makefile\\.in$;^C:/hoffman/My Builds/t [...]
+set(CPACK_SOURCE_IGNORE_FILES "~$;^C:/hoffman/My Builds/testcase.*/CVS/;^C:/hoffman/My Builds/testcase.*/\\.svn/;^C:/hoffman/My Builds/testcase.*/sweigart/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/eos2001/;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_tables_new/;^C:/hoffman/My Builds/testcase/COPYING$;^C:/hoffman/My Builds/testcase/INSTALL$;^C:/hoffman/My Builds/testcase/Makefile$;^C:/hoffman/My Builds/testcase/Makefile\\.in$;^C:/hoffman/My Builds/testcase/.*\\.l [...]
 
 #
 # Define a macro
@@ -88,7 +88,7 @@ endif()
 
 if(CMAKE_SYSTEM MATCHES "OSF1-V")
   if(NOT CMAKE_COMPILER_IS_GNUCXX)
-     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -timplicit_local -no_implicit_include ")
+     string(APPEND CMAKE_CXX_FLAGS " -timplicit_local -no_implicit_include ")
   endif()
 endif()
 
@@ -399,7 +399,7 @@ set(CMAKE_CXX_EXTENSIONS TRUE)
 # template support also need a flag to use the newer C++ library.
 if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
     CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA")
+  string(APPEND CMAKE_CXX_FLAGS " -AA")
 endif ()
 
 # Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
diff --git a/Tests/ComplexOneConfig/Executable/CMakeLists.txt b/Tests/ComplexOneConfig/Executable/CMakeLists.txt
index 4897b48..f935aed 100644
--- a/Tests/ComplexOneConfig/Executable/CMakeLists.txt
+++ b/Tests/ComplexOneConfig/Executable/CMakeLists.txt
@@ -1,8 +1,8 @@
 #
 # Create exe.
 #
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DTEST_CXX_FLAGS")
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST_C_FLAGS")
+string(APPEND CMAKE_CXX_FLAGS " -DTEST_CXX_FLAGS")
+string(APPEND CMAKE_C_FLAGS " -DTEST_C_FLAGS")
 
 # Create an imported target for if(TARGET) test below.
 add_library(ExeImportedTarget UNKNOWN IMPORTED)
diff --git a/Tests/ComplexOneConfig/Executable/complex.cxx b/Tests/ComplexOneConfig/Executable/complex.cxx
index 5f79ac0..9e4eaad 100644
--- a/Tests/ComplexOneConfig/Executable/complex.cxx
+++ b/Tests/ComplexOneConfig/Executable/complex.cxx
@@ -478,6 +478,24 @@ int main()
   cmPassed("SHOULD_NOT_BE_DEFINED_GREATER is not defined.");
 #endif
 
+#ifndef SHOULD_BE_DEFINED_GREATER
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER is not defined.\n");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER2
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER2
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER2 is defined.");
+#endif
+
 #ifdef SHOULD_NOT_BE_DEFINED_EQUAL
   cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_EQUAL is defined.");
 #else
@@ -490,23 +508,88 @@ int main()
   cmPassed("SHOULD_BE_DEFINED_EQUAL is defined.");
 #endif
 
-#ifndef SHOULD_BE_DEFINED_GREATER
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_GREATER is not defined.\n");
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL is defined.");
 #else
-  cmPassed("SHOULD_BE_DEFINED_GREATER is defined.");
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL is not defined.");
 #endif
 
-#ifdef SHOULD_NOT_BE_DEFINED_GREATER2
-  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER2 is defined.");
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL is not defined.");
 #else
-  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER2 is not defined.");
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL is defined.");
 #endif
 
-#ifndef SHOULD_BE_DEFINED_GREATER2
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL2
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER2 is not defined.\n");
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL2 is defined.");
 #else
-  cmPassed("SHOULD_BE_DEFINED_GREATER2 is defined.");
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_LESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_LESS_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_LESS_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_LESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_LESS_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_LESS_EQUAL3 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_GREATER_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_GREATER_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_GREATER_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_GREATER_EQUAL3 is defined.");
 #endif
 
 #ifdef SHOULD_NOT_BE_DEFINED_STRLESS
@@ -516,7 +599,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_STRLESS
-  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRLESS is defined.");
 #endif
@@ -528,8 +611,7 @@ int main()
 #endif
 
 #ifndef SHOULD_BE_DEFINED_STRLESS2
-  cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS2 is not defined.\n");
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRLESS2 is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRLESS2 is defined.");
 #endif
@@ -543,7 +625,7 @@ int main()
 
 #ifndef SHOULD_BE_DEFINED_STRGREATER
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER is not defined.\n");
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRGREATER is defined.");
 #endif
@@ -557,11 +639,95 @@ int main()
 
 #ifndef SHOULD_BE_DEFINED_STRGREATER2
   cmFailed(
-    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER2 is not defined.\n");
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER2 is not defined.");
 #else
   cmPassed("SHOULD_BE_DEFINED_STRGREATER2 is defined.");
 #endif
 
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL2
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL2 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3 is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRLESS_EQUAL3
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRLESS_EQUAL3 is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRLESS_EQUAL3 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL is defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL
+  cmFailed(
+    "IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL is not defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2 is "
+           "defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL2
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL2 is not "
+           "defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL2 is defined.");
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3
+  cmFailed("IF or SET is broken, SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3 is "
+           "defined.");
+#else
+  cmPassed("SHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3 is not defined.");
+#endif
+
+#ifndef SHOULD_BE_DEFINED_STRGREATER_EQUAL3
+  cmFailed("IF or SET is broken, SHOULD_BE_DEFINED_STRGREATER_EQUAL3 is not "
+           "defined.");
+#else
+  cmPassed("SHOULD_BE_DEFINED_STRGREATER_EQUAL3 is defined.");
+#endif
+
 // ----------------------------------------------------------------------
 // Test FOREACH
 
diff --git a/Tests/ComplexOneConfig/Library/CMakeLists.txt b/Tests/ComplexOneConfig/Library/CMakeLists.txt
index f00cbd6..dbf806e 100644
--- a/Tests/ComplexOneConfig/Library/CMakeLists.txt
+++ b/Tests/ComplexOneConfig/Library/CMakeLists.txt
@@ -43,7 +43,7 @@ endif()
 #
 set(SharedLibrarySources sharedFile)
 add_library(CMakeTestLibraryShared SHARED ${SharedLibrarySources})
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST_C_FLAGS")
+string(APPEND CMAKE_C_FLAGS " -DTEST_C_FLAGS")
 add_library(CMakeTestCLibraryShared SHARED testConly.c)
 define_property(
   TARGET PROPERTY FOO
diff --git a/Tests/ComplexOneConfig/VarTests.cmake b/Tests/ComplexOneConfig/VarTests.cmake
index 70b803a..7dd8519 100644
--- a/Tests/ComplexOneConfig/VarTests.cmake
+++ b/Tests/ComplexOneConfig/VarTests.cmake
@@ -126,6 +126,12 @@ else ()
   add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER)
 endif ()
 
+if (SNUM1_VAR GREATER SNUM2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER2)
+endif ()
+
 if (SNUM2_VAR EQUAL SNUM1_VAR)
   add_definitions(-DSHOULD_NOT_BE_DEFINED_EQUAL)
 else ()
@@ -138,10 +144,40 @@ else ()
   add_definitions(-DSHOULD_NOT_BE_DEFINED_EQUAL)
 endif ()
 
-if (SNUM1_VAR GREATER SNUM2_VAR)
-  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER2)
+if (SNUM1_VAR LESS_EQUAL SNUM2_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL)
 else ()
-  add_definitions(-DSHOULD_BE_DEFINED_GREATER2)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_LESS_EQUAL)
+endif ()
+
+if (SNUM2_VAR LESS_EQUAL SNUM1_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_LESS_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL2)
+endif ()
+
+if (SNUM1_VAR LESS_EQUAL SNUM3_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_LESS_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_LESS_EQUAL3)
+endif ()
+
+if (SNUM2_VAR GREATER_EQUAL SNUM1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL)
+endif ()
+
+if (SNUM1_VAR GREATER_EQUAL SNUM2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL2)
+endif ()
+
+if (SNUM1_VAR GREATER_EQUAL SNUM3_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_GREATER_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_GREATER_EQUAL3)
 endif ()
 
 set (SSTR1_VAR "abc")
@@ -171,6 +207,42 @@ else ()
   add_definitions(-DSHOULD_BE_DEFINED_STRGREATER2)
 endif ()
 
+if (SSTR1_VAR STRLESS_EQUAL SSTR2_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL)
+endif ()
+
+if (SSTR2_VAR STRLESS_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL2)
+endif ()
+
+if (SSTR1_VAR STRLESS_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRLESS_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRLESS_EQUAL3)
+endif ()
+
+if (SSTR2_VAR STRGREATER_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL)
+endif ()
+
+if (SSTR1_VAR STRGREATER_EQUAL SSTR2_VAR)
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL2)
+else ()
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL2)
+endif ()
+
+if (SSTR1_VAR STRGREATER_EQUAL SSTR1_VAR)
+  add_definitions(-DSHOULD_BE_DEFINED_STRGREATER_EQUAL3)
+else ()
+  add_definitions(-DSHOULD_NOT_BE_DEFINED_STRGREATER_EQUAL3)
+endif ()
+
 #
 # Test FOREACH
 #
@@ -180,5 +252,5 @@ endforeach()
 
 set(FOREACH_CONCAT "")
 foreach (INDEX a;b;c;d;e;f;g)
-  set(FOREACH_CONCAT "${FOREACH_CONCAT}${INDEX}")
+  string(APPEND FOREACH_CONCAT "${INDEX}")
 endforeach()
diff --git a/Tests/CustomCommand/CMakeLists.txt b/Tests/CustomCommand/CMakeLists.txt
index 268069d..db57e19 100644
--- a/Tests/CustomCommand/CMakeLists.txt
+++ b/Tests/CustomCommand/CMakeLists.txt
@@ -376,8 +376,8 @@ foreach(arg ${CHECK_ARGS} "")
   set(ARG "${arg}")
   string(REPLACE "\\" "\\\\" ARG "${ARG}")
   string(REPLACE "\"" "\\\"" ARG "${ARG}")
-  set(EXPECTED_ARGUMENTS
-    "${EXPECTED_ARGUMENTS}  \"${ARG}\",
+  string(APPEND EXPECTED_ARGUMENTS
+    "  \"${ARG}\",
 ")
 endforeach()
 configure_file(${CMAKE_CURRENT_SOURCE_DIR}/check_command_line.c.in
@@ -476,7 +476,7 @@ add_custom_command(
 
 add_library(NormOutput "${gen_file}")
 
-set(gen_path "${gen_path}/bar")
+string(APPEND gen_path "/bar")
 set(gen_file "${gen_path}/bar.cxx")
 
 add_custom_command(
diff --git a/Tests/ExternalProjectSourceSubdir/CMakeLists.txt b/Tests/ExternalProjectSourceSubdir/CMakeLists.txt
new file mode 100644
index 0000000..4688acf
--- /dev/null
+++ b/Tests/ExternalProjectSourceSubdir/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.6)
+project(ExternalProjectSourceSubdir NONE)
+include(ExternalProject)
+
+ExternalProject_Add(Example
+  SOURCE_SUBDIR subdir
+  SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Example
+  BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/Example
+  INSTALL_COMMAND ""
+  )
diff --git a/Tests/ExternalProjectSourceSubdir/Example/subdir/CMakeLists.txt b/Tests/ExternalProjectSourceSubdir/Example/subdir/CMakeLists.txt
new file mode 100644
index 0000000..bbc3ca0
--- /dev/null
+++ b/Tests/ExternalProjectSourceSubdir/Example/subdir/CMakeLists.txt
@@ -0,0 +1,2 @@
+cmake_minimum_required(VERSION 3.0)
+project(empty)
diff --git a/Tests/FindBZip2/CMakeLists.txt b/Tests/FindBZip2/CMakeLists.txt
new file mode 100644
index 0000000..0eb3b99
--- /dev/null
+++ b/Tests/FindBZip2/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindBZip2.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindBZip2/Test"
+  "${CMake_BINARY_DIR}/Tests/FindBZip2/Test"
+  ${build_generator_args}
+  --build-project TestFindBZip2
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindBZip2/Test/CMakeLists.txt b/Tests/FindBZip2/Test/CMakeLists.txt
new file mode 100644
index 0000000..e9cb618
--- /dev/null
+++ b/Tests/FindBZip2/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindBZip2 C)
+include(CTest)
+
+find_package(BZip2 REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_BZip2_VERSION="${BZip2_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt BZip2::BZip2)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${BZIP2_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${BZIP2_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindBZip2/Test/main.c b/Tests/FindBZip2/Test/main.c
new file mode 100644
index 0000000..8e24c94
--- /dev/null
+++ b/Tests/FindBZip2/Test/main.c
@@ -0,0 +1,23 @@
+#include <bzlib.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+int main()
+{
+  int chunksize = 1024;
+  FILE* file = fopen("test.bzip2", "wb");
+  char* buf = malloc(sizeof(char) * chunksize);
+  int error, rsize;
+  unsigned int in, out;
+  BZFILE* bzfile = BZ2_bzWriteOpen(&error, file, 64, 1, 10);
+
+  /* Don't actually write anything for the purposes of the test */
+
+  BZ2_bzWriteClose(&error, bzfile, 1, &in, &out);
+  free(buf);
+  fclose(file);
+
+  remove("test.bzip2");
+
+  return 0;
+}
diff --git a/Tests/FindICU/CMakeLists.txt b/Tests/FindICU/CMakeLists.txt
new file mode 100644
index 0000000..4acaaf2
--- /dev/null
+++ b/Tests/FindICU/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindICU.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindICU/Test"
+  "${CMake_BINARY_DIR}/Tests/FindICU/Test"
+  ${build_generator_args}
+  --build-project TestFindICU
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindICU/Test/CMakeLists.txt b/Tests/FindICU/Test/CMakeLists.txt
new file mode 100644
index 0000000..1247ac7
--- /dev/null
+++ b/Tests/FindICU/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+project(TestFindICU LANGUAGES CXX)
+include(CTest)
+
+find_package(ICU REQUIRED COMPONENTS i18n uc)
+
+add_executable(test_icu_tgt main.cpp)
+target_link_libraries(test_icu_tgt ICU::i18n ICU::uc)
+add_test(NAME test_icu_tgt COMMAND test_icu_tgt)
+
+add_executable(test_icu_var main.cpp)
+target_include_directories(test_icu_var PRIVATE ${ICU_INCLUDE_DIRS})
+target_link_libraries(test_icu_var PRIVATE ${ICU_LIBRARIES})
+add_test(NAME test_icu_var COMMAND test_icu_var)
diff --git a/Tests/FindICU/Test/main.cpp b/Tests/FindICU/Test/main.cpp
new file mode 100644
index 0000000..64cc5d3
--- /dev/null
+++ b/Tests/FindICU/Test/main.cpp
@@ -0,0 +1,24 @@
+#include <unicode/uclean.h>
+#include <unicode/ustring.h>
+#include <unicode/utypes.h>
+
+#include <unicode/ucal.h>
+#include <unicode/ucnv.h>
+#include <unicode/udat.h>
+
+int main()
+{
+  UConverter* cnv = 0;
+  UErrorCode status = U_ZERO_ERROR;
+  ucnv_open(NULL, &status);
+
+  UChar uchars[100];
+  const char* chars = "Test";
+  if (cnv && U_SUCCESS(status)) {
+    int32_t len = ucnv_toUChars(cnv, uchars, 100, chars, -1, &status);
+  }
+
+  ucnv_close(cnv);
+  u_cleanup();
+  return (U_FAILURE(status) ? 1 : 0);
+}
diff --git a/Tests/FindLibUV/CMakeLists.txt b/Tests/FindLibUV/CMakeLists.txt
new file mode 100644
index 0000000..08aa958
--- /dev/null
+++ b/Tests/FindLibUV/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibUV.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindLibUV/Test"
+  "${CMake_BINARY_DIR}/Tests/FindLibUV/Test"
+  ${build_generator_args}
+  --build-project TestFindLibUV
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindLibUV/Test/CMakeLists.txt b/Tests/FindLibUV/Test/CMakeLists.txt
new file mode 100644
index 0000000..257ddf3
--- /dev/null
+++ b/Tests/FindLibUV/Test/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.6)
+project(TestFindLibUV C)
+include(CTest)
+
+# CMake does not actually provide FindLibUV publicly.
+set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../Source/Modules)
+
+find_package(LibUV REQUIRED)
+
+add_executable(test_libuv_tgt main.c)
+target_link_libraries(test_libuv_tgt LibUV::LibUV)
+add_test(NAME test_libuv_tgt COMMAND test_libuv_tgt)
+
+add_executable(test_libuv_var main.c)
+target_include_directories(test_libuv_var PRIVATE ${LibUV_INCLUDE_DIRS})
+target_link_libraries(test_libuv_var PRIVATE ${LibUV_LIBRARIES})
+add_test(NAME test_libuv_var COMMAND test_libuv_var)
diff --git a/Tests/FindLibUV/Test/main.c b/Tests/FindLibUV/Test/main.c
new file mode 100644
index 0000000..cbd0db3
--- /dev/null
+++ b/Tests/FindLibUV/Test/main.c
@@ -0,0 +1,7 @@
+#include <uv.h>
+
+int main()
+{
+  uv_loop_close(uv_default_loop());
+  return 0;
+}
diff --git a/Tests/FindMatlab/components_checks/CMakeLists.txt b/Tests/FindMatlab/components_checks/CMakeLists.txt
new file mode 100644
index 0000000..3dec093
--- /dev/null
+++ b/Tests/FindMatlab/components_checks/CMakeLists.txt
@@ -0,0 +1,23 @@
+
+cmake_minimum_required (VERSION 2.8.12)
+enable_testing()
+project(component_checks)
+
+set(MATLAB_FIND_DEBUG TRUE)
+
+# the success of the following command is dependent on the current configuration:
+# - on 32bits builds (cmake is building with 32 bits), it looks for 32 bits Matlab
+# - on 64bits builds (cmake is building with 64 bits), it looks for 64 bits Matlab
+find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY ENG_LIBRARY MAT_LIBRARY MAIN_PROGRAM)
+
+message(STATUS "FindMatlab libraries: ${Matlab_LIBRARIES}")
+
+matlab_add_mex(
+    # target name
+    NAME cmake_matlab_test_wrapper1
+    # output name
+    OUTPUT_NAME cmake_matlab_mex1
+    SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper1.cpp
+    DOCUMENTATION ${CMAKE_CURRENT_SOURCE_DIR}/../help_text1.m.txt
+    LINK_TO ${Matlab_LIBRARIES}
+  )
diff --git a/Tests/FindOpenCL/CMakeLists.txt b/Tests/FindOpenCL/CMakeLists.txt
new file mode 100644
index 0000000..88d2eae
--- /dev/null
+++ b/Tests/FindOpenCL/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindOpenCL.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindOpenCL/Test"
+  "${CMake_BINARY_DIR}/Tests/FindOpenCL/Test"
+  ${build_generator_args}
+  --build-project TestFindOpenCL
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindOpenCL/Test/CMakeLists.txt b/Tests/FindOpenCL/Test/CMakeLists.txt
new file mode 100644
index 0000000..f8a6587
--- /dev/null
+++ b/Tests/FindOpenCL/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindOpenCL C)
+include(CTest)
+
+find_package(OpenCL REQUIRED)
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt OpenCL::OpenCL)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${OpenCL_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${OpenCL_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindOpenCL/Test/main.c b/Tests/FindOpenCL/Test/main.c
new file mode 100644
index 0000000..dc77636
--- /dev/null
+++ b/Tests/FindOpenCL/Test/main.c
@@ -0,0 +1,17 @@
+#ifdef __APPLE__
+#include <OpenCL/opencl.h>
+#else
+#include <CL/cl.h>
+#endif
+
+int main()
+{
+  cl_uint platformIdCount;
+
+  // We can't assert on the result because this may return an error if no ICD
+  // is
+  // found
+  clGetPlatformIDs(0, NULL, &platformIdCount);
+
+  return 0;
+}
diff --git a/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfig.cmake b/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfig.cmake
new file mode 100644
index 0000000..deffa57
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfig.cmake	
@@ -0,0 +1 @@
+# Test config file.
diff --git a/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfigVersion.cmake b/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfigVersion.cmake
new file mode 100644
index 0000000..d8cac77
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 1.3/lib/cmake/Baz/BazConfigVersion.cmake	
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.3)
+if("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL 1)
+  set(PACKAGE_VERSION_COMPATIBLE 1)
+  if("${PACKAGE_FIND_VERSION_MINOR}" EQUAL 3)
+    set(PACKAGE_VERSION_EXACT 1)
+  endif()
+endif()
diff --git a/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfig.cmake b/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfig.cmake
new file mode 100644
index 0000000..deffa57
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfig.cmake	
@@ -0,0 +1 @@
+# Test config file.
diff --git a/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfigVersion.cmake b/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfigVersion.cmake
new file mode 100644
index 0000000..5026fad
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 2.0/share/Baz 2/BazConfigVersion.cmake	
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 2.0)
+if("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL 2)
+  set(PACKAGE_VERSION_COMPATIBLE 1)
+  if("${PACKAGE_FIND_VERSION_MINOR}" EQUAL 0)
+    set(PACKAGE_VERSION_EXACT 1)
+  endif()
+endif()
diff --git a/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfig.cmake b/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfig.cmake
new file mode 100644
index 0000000..deffa57
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfig.cmake	
@@ -0,0 +1 @@
+# Test config file.
diff --git a/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfigVersion.cmake b/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfigVersion.cmake
new file mode 100644
index 0000000..a180143
--- /dev/null
+++ b/Tests/FindPackageTest/Baz 2.1/lib/Baz 2/cmake/BazConfigVersion.cmake	
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 2.1)
+if("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL 2)
+  set(PACKAGE_VERSION_COMPATIBLE 1)
+  if("${PACKAGE_FIND_VERSION_MINOR}" EQUAL 1)
+    set(PACKAGE_VERSION_EXACT 1)
+  endif()
+endif()
diff --git a/Tests/FindPackageTest/CMakeLists.txt b/Tests/FindPackageTest/CMakeLists.txt
index fadd0fe..1a6f204 100644
--- a/Tests/FindPackageTest/CMakeLists.txt
+++ b/Tests/FindPackageTest/CMakeLists.txt
@@ -102,6 +102,7 @@ endif()
 set(PACKAGES
   foo Foo Bar Blub TFramework Tframework TApp Tapp Special
   VersionedA VersionedB VersionedC VersionedD VersionedE
+  VersionedF VersionedG VersionedH
   WrongA WrongB WrongC WrongD
   wibbleA wibbleB
   RecursiveA RecursiveB RecursiveC
@@ -142,6 +143,10 @@ find_package(VersionedB 3.1 EXACT NAMES zot)
 find_package(VersionedC 4.0 EXACT NAMES zot)
 find_package(VersionedD 1.1 EXACT NAMES Baz)
 find_package(VersionedE 1.2 EXACT NAMES Baz)
+find_package(VersionedF 1.3 EXACT NAMES Baz)
+find_package(VersionedG 2.0 EXACT NAMES Baz)
+find_package(VersionedH 2.1 EXACT NAMES Baz)
+
 
 # Test Config files which set Xyz_FOUND themselves:
 find_package(SetFoundTRUE NO_MODULE)
@@ -158,12 +163,12 @@ find_package(WrongB 1.2 EXACT NAMES Baz)
 
 # Test wrong initial path when result is missing.
 set(WrongC_DIR "${VersionedD_DIR}")
-find_package(WrongC 1.3 EXACT QUIET NAMES Baz)
+find_package(WrongC 1.4 EXACT QUIET NAMES Baz)
 
 # Test wrong initial cache entry of UNINITIALIZED type when result is missing.
 set(WrongD_DIR "${VersionedD_DIR}" CACHE UNINITIALIZED "Wrong Value" FORCE)
 get_property(type CACHE WrongD_DIR PROPERTY TYPE)
-find_package(WrongD 1.3 EXACT QUIET NAMES Baz)
+find_package(WrongD 1.4 EXACT QUIET NAMES Baz)
 
 # HINTS should override the system but PATHS should not
 list(INSERT CMAKE_SYSTEM_PREFIX_PATH 0 "${CMAKE_CURRENT_SOURCE_DIR}/A")
@@ -216,6 +221,9 @@ set(VersionedB_EXPECTED "lib/zot-3.1/zot-config.cmake")
 set(VersionedC_EXPECTED "lib/cmake/zot-4.0/zot-config.cmake")
 set(VersionedD_EXPECTED "Baz 1.1/BazConfig.cmake")
 set(VersionedE_EXPECTED "Baz 1.2/CMake/BazConfig.cmake")
+set(VersionedF_EXPECTED "Baz 1.3/lib/cmake/Baz/BazConfig.cmake")
+set(VersionedG_EXPECTED "Baz 2.0/share/Baz 2/BazConfig.cmake")
+set(VersionedH_EXPECTED "Baz 2.1/lib/Baz 2/cmake/BazConfig.cmake")
 set(WrongA_EXPECTED "${VersionedE_EXPECTED}")
 set(WrongB_EXPECTED "${VersionedE_EXPECTED}")
 set(WrongC_MISSING "WrongC_DIR-NOTFOUND")
@@ -333,7 +341,7 @@ endif()
 # Choose a unique version.
 string(REGEX REPLACE "-.*$" "" version ${CMAKE_VERSION})
 string(RANDOM LENGTH 4 ALPHABET "0123456789" v)
-set(version "${version}.${v}")
+string(APPEND version ".${v}")
 
 message(STATUS "Preparing export(PACKAGE) test project")
 try_compile(EXPORTER_COMPILED
@@ -625,3 +633,33 @@ endif()
 if(PACKAGE_VERSION_UNSUITABLE)
   message(SEND_ERROR "PACKAGE_VERSION_UNSUITABLE set, but must not be !")
 endif()
+
+
+############################################################################
+##Test FIND_PACKAGE using sorting
+set(CMAKE_PREFIX_PATH ${CMAKE_CURRENT_SOURCE_DIR})
+SET(CMAKE_FIND_PACKAGE_SORT_ORDER NAME)
+SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION ASC)
+
+set(SortLib_DIR "" CACHE FILEPATH "Wipe out find results for testing." FORCE)
+FIND_PACKAGE(SortLib CONFIG)
+IF (NOT "${SortLib_VERSION}" STREQUAL "3.1.1")
+  message(SEND_ERROR "FIND_PACKAGE_SORT_ORDER Name Asc! ${SortLib_VERSION}")
+endif()
+unset(SortLib_VERSION)
+
+
+set(SortLib_DIR "" CACHE FILEPATH "Wipe out find results for testing." FORCE)
+SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
+SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
+FIND_PACKAGE(SortLib CONFIG)
+IF (NOT "${SortLib_VERSION}" STREQUAL "3.10.1")
+  message(SEND_ERROR "FIND_PACKAGE_SORT_ORDER Natural! Dec ${SortLib_VERSION}")
+endif()
+set(SortLib_DIR "" CACHE FILEPATH "Wipe out find results for testing." FORCE)
+unset(SortLib_VERSION)
+
+
+unset(CMAKE_FIND_PACKAGE_SORT_ORDER)
+unset(CMAKE_FIND_PACKAGE_SORT_DIRECTION)
+set(CMAKE_PREFIX_PATH )
diff --git a/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfig.cmake b/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfig.cmake
new file mode 100644
index 0000000..c1f2088
--- /dev/null
+++ b/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfig.cmake
@@ -0,0 +1,2 @@
+set(SORT_LIB_VERSION 3.1.1)
+message("SortLib 3.1.1 config reached")
diff --git a/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfigVersion.cmake b/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfigVersion.cmake
new file mode 100644
index 0000000..fa927c7
--- /dev/null
+++ b/Tests/FindPackageTest/SortLib-3.1.1/SortLibConfigVersion.cmake
@@ -0,0 +1,9 @@
+set(PACKAGE_VERSION 3.1.1)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 3)
+  if(PACKAGE_FIND_VERSION_MINOR EQUAL 1)
+    set(PACKAGE_VERSION_COMPATIBLE 1)
+    if(PACKAGE_FIND_VERSION_PATCH EQUAL 1)
+      set(PACKAGE_VERSION_EXACT 1)
+    endif()
+  endif()
+endif()
diff --git a/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfig.cmake b/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfig.cmake
new file mode 100644
index 0000000..3f3f659
--- /dev/null
+++ b/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfig.cmake
@@ -0,0 +1,2 @@
+set(SORT_LIB_VERSION 3.10.1)
+message("SortLib 3.10.1 config reached")
diff --git a/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfigVersion.cmake b/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfigVersion.cmake
new file mode 100644
index 0000000..6f44c2d
--- /dev/null
+++ b/Tests/FindPackageTest/SortLib-3.10.1/SortLibConfigVersion.cmake
@@ -0,0 +1,9 @@
+set(PACKAGE_VERSION 3.10.1)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 3)
+  if(PACKAGE_FIND_VERSION_MINOR EQUAL 10)
+    set(PACKAGE_VERSION_COMPATIBLE 1)
+    if(PACKAGE_FIND_VERSION_PATCH EQUAL 1)
+      set(PACKAGE_VERSION_EXACT 1)
+    endif()
+  endif()
+endif()
diff --git a/Tests/FindTIFF/Test/CMakeLists.txt b/Tests/FindTIFF/Test/CMakeLists.txt
index f17cda7..6985e3f 100644
--- a/Tests/FindTIFF/Test/CMakeLists.txt
+++ b/Tests/FindTIFF/Test/CMakeLists.txt
@@ -7,11 +7,11 @@ set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../Source/Modules)
 
 find_package(TIFF REQUIRED)
 
-add_executable(test_xercesc_tgt main.c)
-target_link_libraries(test_xercesc_tgt TIFF::TIFF)
-add_test(NAME test_xercesc_tgt COMMAND test_xercesc_tgt)
+add_executable(test_tiff_tgt main.c)
+target_link_libraries(test_tiff_tgt TIFF::TIFF)
+add_test(NAME test_tiff_tgt COMMAND test_tiff_tgt)
 
-add_executable(test_xercesc_var main.c)
-target_include_directories(test_xercesc_var PRIVATE ${TIFF_INCLUDE_DIRS})
-target_link_libraries(test_xercesc_var PRIVATE ${TIFF_LIBRARIES})
-add_test(NAME test_xercesc_var COMMAND test_xercesc_var)
+add_executable(test_tiff_var main.c)
+target_include_directories(test_tiff_var PRIVATE ${TIFF_INCLUDE_DIRS})
+target_link_libraries(test_tiff_var PRIVATE ${TIFF_LIBRARIES})
+add_test(NAME test_tiff_var COMMAND test_tiff_var)
diff --git a/Tests/FindVulkan/CMakeLists.txt b/Tests/FindVulkan/CMakeLists.txt
new file mode 100644
index 0000000..46ce1c6
--- /dev/null
+++ b/Tests/FindVulkan/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindVulkan.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindVulkan/Test"
+  "${CMake_BINARY_DIR}/Tests/FindVulkan/Test"
+  ${build_generator_args}
+  --build-project TestFindVulkan
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindVulkan/Test/CMakeLists.txt b/Tests/FindVulkan/Test/CMakeLists.txt
new file mode 100644
index 0000000..0b13d53
--- /dev/null
+++ b/Tests/FindVulkan/Test/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindVulkan C)
+include(CTest)
+
+SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/../../)
+find_package(Vulkan REQUIRED)
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt Vulkan::Vulkan)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${Vulkan_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${Vulkan_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindVulkan/Test/main.c b/Tests/FindVulkan/Test/main.c
new file mode 100644
index 0000000..b29c9ec
--- /dev/null
+++ b/Tests/FindVulkan/Test/main.c
@@ -0,0 +1,29 @@
+#include <vulkan/vulkan.h>
+
+int main()
+{
+  VkInstanceCreateInfo instanceCreateInfo = {};
+  instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
+
+  VkApplicationInfo applicationInfo = {};
+  applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
+  applicationInfo.apiVersion = VK_API_VERSION_1_0;
+  applicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
+  applicationInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
+  applicationInfo.pApplicationName = "CMake Test application";
+  applicationInfo.pEngineName = "CMake Test Engine";
+
+  instanceCreateInfo.pApplicationInfo = &applicationInfo;
+
+  VkInstance instance = VK_NULL_HANDLE;
+  vkCreateInstance(&instanceCreateInfo, NULL, &instance);
+
+  // We can't assert here because in general vkCreateInstance will return an
+  // error if no driver is found - but if we get here, FindVulkan is working
+
+  if (instance != VK_NULL_HANDLE) {
+    vkDestroyInstance(instance, NULL);
+  }
+
+  return 0;
+}
diff --git a/Tests/Fortran/CMakeLists.txt b/Tests/Fortran/CMakeLists.txt
index 1268982..740e6f5 100644
--- a/Tests/Fortran/CMakeLists.txt
+++ b/Tests/Fortran/CMakeLists.txt
@@ -1,8 +1,5 @@
 cmake_minimum_required (VERSION 3.1)
 project(testf C CXX Fortran)
-if(NOT DEFINED CMake_TEST_NESTED_MAKE_PROGRAM AND NOT CMAKE_GENERATOR MATCHES "Visual Studio")
-  set(CMake_TEST_NESTED_MAKE_PROGRAM "${CMAKE_MAKE_PROGRAM}")
-endif()
 
 message("CTEST_FULL_OUTPUT ")
 set(CMAKE_VERBOSE_MAKEFILE 1)
@@ -67,7 +64,7 @@ function(test_fortran_c_interface_module)
     SYMBOL_NAMESPACE "F_"
     SYMBOLS ${FORTRAN_FUNCTIONS}
     )
-  include_directories("${testf_BINARY_DIR}")
+  include_directories("${CMAKE_CURRENT_BINARY_DIR}")
 
   # if the name mangling is not found for a F90 compiler
   # print out some diagnostic stuff for the dashboard
@@ -111,7 +108,7 @@ function(test_fortran_c_interface_module)
   target_link_libraries(maincxx mycxx)
 
   # print out some stuff to help debug on machines via cdash
-  file(READ "${testf_BINARY_DIR}/foo.h" fooh)
+  file(READ "${CMAKE_CURRENT_BINARY_DIR}/foo.h" fooh)
   message("foo.h contents:\n${fooh}")
 endfunction()
 
@@ -144,85 +141,3 @@ else()
   endif()
 
 endif()
-
-
-
-
-set(TEST_MODULE_DEPENDS 0)
-if(CMAKE_Fortran_COMPILER_SUPPORTS_F90)
-  add_executable(test_module
-    test_module_main.f90
-    test_module_implementation.f90
-    test_module_interface.f90)
-
-  add_executable(test_use_in_comment_fixedform
-    test_use_in_comment_fixedform.f)
-  set_property(SOURCE test_use_in_comment_fixedform.f PROPERTY Fortran_FORMAT FIXED)
-  add_executable(test_use_in_comment_freeform
-    test_use_in_comment_freeform.f90)
-  set_property(SOURCE test_use_in_comment_freeform.f90 PROPERTY Fortran_FORMAT FREE)
-
-  add_executable(test_in_interface
-    in_interface/main.f90
-    in_interface/module.f90)
-
-  add_definitions(-DFOO -DBAR=1)
-  include_directories(${testf_SOURCE_DIR}/include)
-  add_executable(test_preprocess test_preprocess.F90 test_preprocess_module.F90)
-
-  set(TEST_MODULE_DEPENDS 1)
-endif()
-
-if(TEST_MODULE_DEPENDS)
-  # Build the external project separately using a custom target.
-  # Make sure it uses the same build configuration as this test.
-  if(CMAKE_CONFIGURATION_TYPES)
-    set(External_CONFIG_TYPE -C "${CMAKE_CFG_INTDIR}")
-    set(External_BUILD_TYPE)
-  else()
-    set(External_CONFIG_TYPE)
-    set(External_BUILD_TYPE -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE})
-  endif()
-  set(External_SOURCE_DIR "${testf_SOURCE_DIR}/External")
-  set(External_BINARY_DIR "${testf_BINARY_DIR}/External")
-  if("${testf_BINARY_DIR}" MATCHES " ")
-    # Our build tree has a space, so the build tool supports spaces.
-    # Test using modules from a path with spaces.
-    set(External_BINARY_DIR "${External_BINARY_DIR} Build")
-  endif()
-  add_custom_command(
-    OUTPUT ${testf_BINARY_DIR}/ExternalProject
-    COMMAND ${CMAKE_CTEST_COMMAND}
-    ARGS ${External_CONFIG_TYPE}
-         --build-and-test
-         ${External_SOURCE_DIR}
-         ${External_BINARY_DIR}
-         --build-noclean
-         --build-two-config
-         --build-project ExtFort
-         --build-generator ${CMAKE_GENERATOR}
-         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
-         --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
-         --build-options -DCMAKE_Fortran_COMPILER:STRING=${CMAKE_Fortran_COMPILER}
-                         -DCMAKE_Fortran_FLAGS:STRING=${CMAKE_Fortran_FLAGS}
-                         -DCMAKE_Fortran_FLAGS_DEBUG:STRING=${CMAKE_Fortran_FLAGS_DEBUG}
-                         -DCMAKE_Fortran_FLAGS_RELEASE:STRING=${CMAKE_Fortran_FLAGS_RELEASE}
-                         -DCMAKE_Fortran_FLAGS_MINSIZEREL:STRING=${CMAKE_Fortran_FLAGS_MINSIZEREL}
-                         -DCMAKE_Fortran_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_Fortran_FLAGS_RELWITHDEBINFO}
-                         -DCMAKE_MAKE_PROGRAM:FILEPATH=${CMake_TEST_NESTED_MAKE_PROGRAM}
-                         ${External_BUILD_TYPE}
-    VERBATIM
-    )
-  add_custom_target(ExternalTarget ALL DEPENDS ${testf_BINARY_DIR}/ExternalProject)
-
-  # Test module output directory if available.
-  if(CMAKE_Fortran_MODDIR_FLAG)
-    set(Library_MODDIR "${testf_BINARY_DIR}/Library/modules")
-  else()
-    set(Library_MODDIR "${testf_BINARY_DIR}/Library")
-  endif()
-
-  add_subdirectory(Library)
-  add_subdirectory(Subdir)
-  add_subdirectory(Executable)
-endif()
diff --git a/Tests/Fortran/External/CMakeLists.txt b/Tests/Fortran/External/CMakeLists.txt
deleted file mode 100644
index 0eb1cfe..0000000
--- a/Tests/Fortran/External/CMakeLists.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-project(ExtFort Fortran)
-
-add_library(myext a.f90)
-
diff --git a/Tests/FortranModules/CMakeLists.txt b/Tests/FortranModules/CMakeLists.txt
new file mode 100644
index 0000000..3996600
--- /dev/null
+++ b/Tests/FortranModules/CMakeLists.txt
@@ -0,0 +1,111 @@
+cmake_minimum_required (VERSION 3.1)
+project(FortranModules Fortran)
+
+if(NOT DEFINED CMake_TEST_NESTED_MAKE_PROGRAM AND NOT CMAKE_GENERATOR MATCHES "Visual Studio")
+  set(CMake_TEST_NESTED_MAKE_PROGRAM "${CMAKE_MAKE_PROGRAM}")
+endif()
+
+if("x${CMake_TEST_Fortran_SUBMODULES}" STREQUAL "x"
+    AND NOT CMAKE_VERSION VERSION_LESS 3.6.20160923 # for CheckFortranSourceCompiles SRC_EXT
+    )
+  include(CheckFortranSourceCompiles)
+  CHECK_Fortran_SOURCE_COMPILES([[
+module parent
+  interface
+    module function id(x)
+       real, intent(in) :: x
+       real :: id
+    end function id
+  end interface
+end module parent
+submodule ( parent ) child
+contains
+  module procedure id
+    f = x
+  end procedure id
+end submodule child
+program main
+end program
+]] HAVE_SUBMODULES SRC_EXT F90)
+  set(CMake_TEST_Fortran_SUBMODULES ${HAVE_SUBMODULES})
+elseif(CMake_TEST_Fortran_SUBMODULES)
+  message(STATUS "Enabling Fortran submodule tests by explicit request.")
+endif()
+
+add_executable(test_module
+  test_module_main.f90
+  test_module_implementation.f90
+  test_module_interface.f90)
+
+add_executable(test_use_in_comment_fixedform
+  test_use_in_comment_fixedform.f)
+set_property(SOURCE test_use_in_comment_fixedform.f PROPERTY Fortran_FORMAT FIXED)
+add_executable(test_use_in_comment_freeform
+  test_use_in_comment_freeform.f90)
+set_property(SOURCE test_use_in_comment_freeform.f90 PROPERTY Fortran_FORMAT FREE)
+
+add_executable(test_in_interface
+  in_interface/main.f90
+  in_interface/module.f90)
+
+add_definitions(-DFOO -DBAR=1)
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
+add_executable(test_preprocess test_preprocess.F90 test_preprocess_module.F90)
+
+add_executable(test_non_pp_include test_non_pp_include_main.f90)
+
+# Build the external project separately using a custom target.
+# Make sure it uses the same build configuration as this test.
+if(CMAKE_CONFIGURATION_TYPES)
+  set(External_CONFIG_TYPE -C "${CMAKE_CFG_INTDIR}")
+  set(External_BUILD_TYPE)
+else()
+  set(External_CONFIG_TYPE)
+  set(External_BUILD_TYPE -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE})
+endif()
+set(External_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/External")
+set(External_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/External")
+if("${CMAKE_CURRENT_BINARY_DIR}" MATCHES " ")
+  # Our build tree has a space, so the build tool supports spaces.
+  # Test using modules from a path with spaces.
+  string(APPEND External_BINARY_DIR " Build")
+endif()
+add_custom_command(
+  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ExternalProject
+  COMMAND ${CMAKE_CTEST_COMMAND}
+  ARGS ${External_CONFIG_TYPE}
+       --build-and-test
+       ${External_SOURCE_DIR}
+       ${External_BINARY_DIR}
+       --build-noclean
+       --build-two-config
+       --build-project ExtFort
+       --build-generator ${CMAKE_GENERATOR}
+       --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
+       --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
+       --build-options -DCMAKE_Fortran_COMPILER:STRING=${CMAKE_Fortran_COMPILER}
+                       -DCMAKE_Fortran_FLAGS:STRING=${CMAKE_Fortran_FLAGS}
+                       -DCMAKE_Fortran_FLAGS_DEBUG:STRING=${CMAKE_Fortran_FLAGS_DEBUG}
+                       -DCMAKE_Fortran_FLAGS_RELEASE:STRING=${CMAKE_Fortran_FLAGS_RELEASE}
+                       -DCMAKE_Fortran_FLAGS_MINSIZEREL:STRING=${CMAKE_Fortran_FLAGS_MINSIZEREL}
+                       -DCMAKE_Fortran_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_Fortran_FLAGS_RELWITHDEBINFO}
+                       -DCMAKE_MAKE_PROGRAM:FILEPATH=${CMake_TEST_NESTED_MAKE_PROGRAM}
+                       ${External_BUILD_TYPE}
+  VERBATIM
+  )
+add_custom_target(ExternalTarget ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ExternalProject)
+
+# Test module output directory if available.
+if(CMAKE_Fortran_MODDIR_FLAG)
+  set(Library_MODDIR "${CMAKE_CURRENT_BINARY_DIR}/Library/modules")
+else()
+  set(Library_MODDIR "${CMAKE_CURRENT_BINARY_DIR}/Library")
+endif()
+
+add_subdirectory(Library)
+add_subdirectory(Subdir)
+add_subdirectory(Executable)
+
+if(CMake_TEST_Fortran_SUBMODULES)
+  add_subdirectory(Submodules)
+endif()
diff --git a/Tests/Fortran/Executable/CMakeLists.txt b/Tests/FortranModules/Executable/CMakeLists.txt
similarity index 100%
rename from Tests/Fortran/Executable/CMakeLists.txt
rename to Tests/FortranModules/Executable/CMakeLists.txt
diff --git a/Tests/Fortran/Executable/main.f90 b/Tests/FortranModules/Executable/main.f90
similarity index 100%
rename from Tests/Fortran/Executable/main.f90
rename to Tests/FortranModules/Executable/main.f90
diff --git a/Tests/FortranModules/External/CMakeLists.txt b/Tests/FortranModules/External/CMakeLists.txt
new file mode 100644
index 0000000..c90a0ffb
--- /dev/null
+++ b/Tests/FortranModules/External/CMakeLists.txt
@@ -0,0 +1,3 @@
+project(ExtFort Fortran)
+
+add_library(myext a.f90)
diff --git a/Tests/Fortran/External/a.f90 b/Tests/FortranModules/External/a.f90
similarity index 100%
rename from Tests/Fortran/External/a.f90
rename to Tests/FortranModules/External/a.f90
diff --git a/Tests/Fortran/Library/CMakeLists.txt b/Tests/FortranModules/Library/CMakeLists.txt
similarity index 100%
rename from Tests/Fortran/Library/CMakeLists.txt
rename to Tests/FortranModules/Library/CMakeLists.txt
diff --git a/Tests/Fortran/Library/a.f90 b/Tests/FortranModules/Library/a.f90
similarity index 100%
rename from Tests/Fortran/Library/a.f90
rename to Tests/FortranModules/Library/a.f90
diff --git a/Tests/Fortran/Library/b.f90 b/Tests/FortranModules/Library/b.f90
similarity index 100%
rename from Tests/Fortran/Library/b.f90
rename to Tests/FortranModules/Library/b.f90
diff --git a/Tests/Fortran/Library/main.f90 b/Tests/FortranModules/Library/main.f90
similarity index 100%
rename from Tests/Fortran/Library/main.f90
rename to Tests/FortranModules/Library/main.f90
diff --git a/Tests/Fortran/Subdir/CMakeLists.txt b/Tests/FortranModules/Subdir/CMakeLists.txt
similarity index 100%
rename from Tests/Fortran/Subdir/CMakeLists.txt
rename to Tests/FortranModules/Subdir/CMakeLists.txt
diff --git a/Tests/Fortran/Subdir/subdir.f90 b/Tests/FortranModules/Subdir/subdir.f90
similarity index 100%
rename from Tests/Fortran/Subdir/subdir.f90
rename to Tests/FortranModules/Subdir/subdir.f90
diff --git a/Tests/FortranModules/Submodules/CMakeLists.txt b/Tests/FortranModules/Submodules/CMakeLists.txt
new file mode 100644
index 0000000..bf0152f
--- /dev/null
+++ b/Tests/FortranModules/Submodules/CMakeLists.txt
@@ -0,0 +1 @@
+add_executable(submod main.f90 provide.f90)
diff --git a/Tests/FortranModules/Submodules/main.f90 b/Tests/FortranModules/Submodules/main.f90
new file mode 100644
index 0000000..3c750ce
--- /dev/null
+++ b/Tests/FortranModules/Submodules/main.f90
@@ -0,0 +1,5 @@
+program main
+  use parent, only : child_function,grandchild_subroutine
+  implicit none
+  if (child_function()) call grandchild_subroutine
+end program
diff --git a/Tests/FortranModules/Submodules/provide.f90 b/Tests/FortranModules/Submodules/provide.f90
new file mode 100644
index 0000000..0ad216a
--- /dev/null
+++ b/Tests/FortranModules/Submodules/provide.f90
@@ -0,0 +1,57 @@
+! The program units in this file consist of a
+! module/submodule tree represented by the following
+! graph:
+!
+!        parent
+!          |
+!         / \
+!        /   \
+!    child   sibling
+!      |
+!  grandchild
+!
+! where the parent node is a module and all other
+! nodes are submodules.
+
+module parent
+  implicit none
+
+  interface
+
+    ! Test Fortran 2008 "module function" syntax
+    module function child_function() result(child_stuff)
+      logical :: child_stuff
+    end function
+
+    ! Test Fortran 2008 "module subroutine" syntax
+    module subroutine grandchild_subroutine()
+    end subroutine
+
+  end interface
+
+end module parent
+
+! 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
+
+! Empty submodule for checking disambiguation of
+! nodes at the same vertical level in the tree
+submodule ( parent ) sibling
+end submodule sibling
+
+! 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/Fortran/in_interface/main.f90 b/Tests/FortranModules/in_interface/main.f90
similarity index 100%
rename from Tests/Fortran/in_interface/main.f90
rename to Tests/FortranModules/in_interface/main.f90
diff --git a/Tests/Fortran/in_interface/module.f90 b/Tests/FortranModules/in_interface/module.f90
similarity index 100%
rename from Tests/Fortran/in_interface/module.f90
rename to Tests/FortranModules/in_interface/module.f90
diff --git a/Tests/Fortran/include/test_preprocess.h b/Tests/FortranModules/include/test_preprocess.h
similarity index 100%
rename from Tests/Fortran/include/test_preprocess.h
rename to Tests/FortranModules/include/test_preprocess.h
diff --git a/Tests/FortranModules/non_pp_include.f90 b/Tests/FortranModules/non_pp_include.f90
new file mode 100644
index 0000000..7eb1725
--- /dev/null
+++ b/Tests/FortranModules/non_pp_include.f90
@@ -0,0 +1,3 @@
+SUBROUTINE NON_PP_INCLUDE_SUBROUTINE
+   PRINT *, "Hello World!"
+END SUBROUTINE NON_PP_INCLUDE_SUBROUTINE
diff --git a/Tests/Fortran/test_module_implementation.f90 b/Tests/FortranModules/test_module_implementation.f90
similarity index 100%
rename from Tests/Fortran/test_module_implementation.f90
rename to Tests/FortranModules/test_module_implementation.f90
diff --git a/Tests/Fortran/test_module_interface.f90 b/Tests/FortranModules/test_module_interface.f90
similarity index 100%
rename from Tests/Fortran/test_module_interface.f90
rename to Tests/FortranModules/test_module_interface.f90
diff --git a/Tests/Fortran/test_module_main.f90 b/Tests/FortranModules/test_module_main.f90
similarity index 100%
rename from Tests/Fortran/test_module_main.f90
rename to Tests/FortranModules/test_module_main.f90
diff --git a/Tests/FortranModules/test_non_pp_include_main.f90 b/Tests/FortranModules/test_non_pp_include_main.f90
new file mode 100644
index 0000000..8a04fbd
--- /dev/null
+++ b/Tests/FortranModules/test_non_pp_include_main.f90
@@ -0,0 +1,5 @@
+INCLUDE "non_pp_include.f90"
+
+PROGRAM MAINF90
+   CALL NON_PP_INCLUDE_SUBROUTINE
+END PROGRAM MAINF90
diff --git a/Tests/Fortran/test_preprocess.F90 b/Tests/FortranModules/test_preprocess.F90
similarity index 100%
rename from Tests/Fortran/test_preprocess.F90
rename to Tests/FortranModules/test_preprocess.F90
diff --git a/Tests/Fortran/test_preprocess_module.F90 b/Tests/FortranModules/test_preprocess_module.F90
similarity index 100%
rename from Tests/Fortran/test_preprocess_module.F90
rename to Tests/FortranModules/test_preprocess_module.F90
diff --git a/Tests/Fortran/test_use_in_comment_fixedform.f b/Tests/FortranModules/test_use_in_comment_fixedform.f
similarity index 100%
rename from Tests/Fortran/test_use_in_comment_fixedform.f
rename to Tests/FortranModules/test_use_in_comment_fixedform.f
diff --git a/Tests/Fortran/test_use_in_comment_freeform.f90 b/Tests/FortranModules/test_use_in_comment_freeform.f90
similarity index 100%
rename from Tests/Fortran/test_use_in_comment_freeform.f90
rename to Tests/FortranModules/test_use_in_comment_freeform.f90
diff --git a/Tests/Framework/CMakeLists.txt b/Tests/Framework/CMakeLists.txt
index 29f9838..271aaf1 100644
--- a/Tests/Framework/CMakeLists.txt
+++ b/Tests/Framework/CMakeLists.txt
@@ -51,6 +51,11 @@ install(TARGETS foo bar
   # duplicate install rules for the pieces of the framework.
 )
 
+# test that framework post-build commands run
+add_custom_command(TARGET foo POST_BUILD COMMAND ${CMAKE_COMMAND} -E touch foo-post-build)
+add_custom_target(fooCustom ALL COMMAND ${CMAKE_COMMAND} -E copy foo-post-build foo-custom)
+add_dependencies(fooCustom foo)
+
 # Make a static library and apply the framework properties to it to verify
 # that everything still builds correctly, but it will not actually produce
 # a framework... The framework properties only apply when the library type
diff --git a/Tests/IncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/CMakeLists.txt
index 523c4f7..db18462 100644
--- a/Tests/IncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/CMakeLists.txt
@@ -3,7 +3,9 @@ project(IncludeDirectories)
 
 if (((CMAKE_C_COMPILER_ID STREQUAL GNU AND CMAKE_C_COMPILER_VERSION VERSION_GREATER 4.4)
     OR CMAKE_C_COMPILER_ID STREQUAL Clang OR CMAKE_C_COMPILER_ID STREQUAL AppleClang)
-    AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles" OR CMAKE_GENERATOR STREQUAL "Ninja"))
+    AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles"
+      OR CMAKE_GENERATOR STREQUAL "Ninja"
+      OR (CMAKE_GENERATOR STREQUAL "Xcode" AND NOT XCODE_VERSION VERSION_LESS 6.0)))
   include(CheckCXXCompilerFlag)
   check_cxx_compiler_flag(-Wunused-variable run_sys_includes_test)
   if(run_sys_includes_test)
@@ -39,9 +41,9 @@ if(WATCOM OR MSVC60)
   set(USE_FULLPATH FALSE)
 endif()
 if(USE_FULLPATH)
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} \"-I${CMAKE_BINARY_DIR}/Flags\"")
+  string(APPEND CMAKE_CXX_FLAGS " \"-I${CMAKE_BINARY_DIR}/Flags\"")
 else()
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -IFlags")
+  string(APPEND CMAKE_CXX_FLAGS " -IFlags")
 endif()
 
 include_directories(${CMAKE_BINARY_DIR}/IncDir)
diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
index dcee85e..5078f30 100644
--- a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
@@ -15,10 +15,17 @@ target_include_directories(upstream SYSTEM PUBLIC
 )
 
 add_library(config_specific INTERFACE)
-set(testConfig ${CMAKE_BUILD_TYPE})
-target_include_directories(config_specific SYSTEM INTERFACE
-  "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
-)
+if(CMAKE_GENERATOR STREQUAL "Xcode")
+  # CMAKE_BUILD_TYPE does not work here for multi-config generators
+  target_include_directories(config_specific SYSTEM INTERFACE
+    "${CMAKE_CURRENT_SOURCE_DIR}/config_specific"
+  )
+else()
+  set(testConfig ${CMAKE_BUILD_TYPE})
+  target_include_directories(config_specific SYSTEM INTERFACE
+    "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
+  )
+endif()
 
 add_library(consumer consumer.cpp)
 target_link_libraries(consumer upstream config_specific)
diff --git a/Tests/Java/A.java b/Tests/Java/A.java
index 403a7f8..b7fdb49 100644
--- a/Tests/Java/A.java
+++ b/Tests/Java/A.java
@@ -1,11 +1,11 @@
 class A
 {
   public A()
-    {
-    }
+  {
+  }
 
   public void printName()
-    {
-      System.out.println("A");
-    }
+  {
+    System.out.println("A");
+  }
 }
diff --git a/Tests/Java/HelloWorld.java b/Tests/Java/HelloWorld.java
index 378e371..995ee48 100644
--- a/Tests/Java/HelloWorld.java
+++ b/Tests/Java/HelloWorld.java
@@ -1,11 +1,11 @@
 class HelloWorld
 {
-    public static void main(String args[])
-    {
-        A a;
-        a = new A();
-        a.printName();
-        System.out.println("Hello World!");
-    }
+  public static void main(String args[])
+  {
+    A a;
+    a = new A();
+    a.printName();
+    System.out.println("Hello World!");
+  }
 }
 
diff --git a/Tests/JavaExportImport/BuildExport/CMakeLists.txt b/Tests/JavaExportImport/BuildExport/CMakeLists.txt
new file mode 100644
index 0000000..953f9d0
--- /dev/null
+++ b/Tests/JavaExportImport/BuildExport/CMakeLists.txt
@@ -0,0 +1,10 @@
+project(foo Java)
+
+cmake_minimum_required (VERSION 3.5)
+set(CMAKE_VERBOSE_MAKEFILE 1)
+
+find_package(Java COMPONENTS Development)
+include(UseJava)
+
+add_jar(${PROJECT_NAME} Foo.java)
+export_jars(TARGETS ${PROJECT_NAME} FILE JavaBuildExportTestConfig.cmake)
diff --git a/Tests/JavaExportImport/BuildExport/Foo.java b/Tests/JavaExportImport/BuildExport/Foo.java
new file mode 100644
index 0000000..20815ba
--- /dev/null
+++ b/Tests/JavaExportImport/BuildExport/Foo.java
@@ -0,0 +1,11 @@
+class Foo
+{
+  public Foo()
+  {
+  }
+
+  public void printName()
+  {
+    System.out.println("Foo");
+  }
+}
diff --git a/Tests/JavaExportImport/CMakeLists.txt b/Tests/JavaExportImport/CMakeLists.txt
new file mode 100644
index 0000000..a075301
--- /dev/null
+++ b/Tests/JavaExportImport/CMakeLists.txt
@@ -0,0 +1,104 @@
+cmake_minimum_required (VERSION 3.5)
+project(JavaExportImport)
+if(NOT DEFINED CMake_TEST_NESTED_MAKE_PROGRAM AND NOT CMAKE_GENERATOR MATCHES "Visual Studio")
+  set(CMake_TEST_NESTED_MAKE_PROGRAM "${CMAKE_MAKE_PROGRAM}")
+endif()
+
+find_package(Java COMPONENTS Development)
+
+# Wipe out the install tree to make sure the exporter works.
+add_custom_command(
+  OUTPUT ${JavaExportImport_BINARY_DIR}/CleanupProject
+  COMMAND ${CMAKE_COMMAND} -E remove_directory ${JavaExportImport_BINARY_DIR}/Root
+  )
+add_custom_target(CleanupTarget ALL DEPENDS ${JavaExportImport_BINARY_DIR}/CleanupProject)
+set_property(
+  SOURCE ${JavaExportImport_BINARY_DIR}/CleanupProject
+  PROPERTY SYMBOLIC 1
+  )
+
+if(CMAKE_CONFIGURATION_TYPES)
+  set(NESTED_CONFIG_TYPE -C "${CMAKE_CFG_INTDIR}")
+else()
+  if(CMAKE_BUILD_TYPE)
+    set(NESTED_CONFIG_TYPE -C "${CMAKE_BUILD_TYPE}")
+  else()
+    set(NESTED_CONFIG_TYPE)
+  endif()
+endif()
+
+configure_file(${JavaExportImport_SOURCE_DIR}/InitialCache.cmake.in
+               ${JavaExportImport_BINARY_DIR}/InitialCache.cmake @ONLY)
+
+# Build the build exporter.
+add_custom_command(
+  OUTPUT ${JavaExportImport_BINARY_DIR}/BuildExportProject
+  COMMAND ${CMAKE_CTEST_COMMAND} ${NESTED_CONFIG_TYPE}
+    --build-and-test
+    ${JavaExportImport_SOURCE_DIR}/BuildExport
+    ${JavaExportImport_BINARY_DIR}/BuildExport
+    --build-noclean
+    --build-project BuildExport
+    --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
+    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
+    --build-options -C${JavaExportImport_BINARY_DIR}/InitialCache.cmake
+  VERBATIM
+  )
+add_custom_target(BuildExportTarget ALL DEPENDS ${JavaExportImport_BINARY_DIR}/BuildExportProject)
+add_dependencies(BuildExportTarget CleanupTarget)
+set_property(
+  SOURCE ${JavaExportImport_BINARY_DIR}/BuildExportProject
+  PROPERTY SYMBOLIC 1
+  )
+
+# Build and install the install exporter.
+add_custom_command(
+  OUTPUT ${JavaExportImport_BINARY_DIR}/InstallExportProject
+  COMMAND ${CMAKE_CTEST_COMMAND} ${NESTED_CONFIG_TYPE}
+    --build-and-test
+    ${JavaExportImport_SOURCE_DIR}/InstallExport
+    ${JavaExportImport_BINARY_DIR}/InstallExport
+    --build-noclean
+    --build-project InstallExport
+    --build-target install
+    --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
+    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
+    --build-options -C${JavaExportImport_BINARY_DIR}/InitialCache.cmake
+  VERBATIM
+  )
+add_custom_target(InstallExportTarget ALL DEPENDS ${JavaExportImport_BINARY_DIR}/InstallExportProject)
+add_dependencies(InstallExportTarget CleanupTarget)
+set_property(
+  SOURCE ${JavaExportImport_BINARY_DIR}/InstallExportProject
+  PROPERTY SYMBOLIC 1
+  )
+
+# Build and install the importer.
+add_custom_command(
+  OUTPUT ${JavaExportImport_BINARY_DIR}/ImportProject
+  COMMAND ${CMAKE_CTEST_COMMAND} ${NESTED_CONFIG_TYPE}
+    --build-and-test
+    ${JavaExportImport_SOURCE_DIR}/Import
+    ${JavaExportImport_BINARY_DIR}/Import
+    --build-noclean
+    --build-project Import
+    --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
+    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
+    --build-options
+      -C${JavaExportImport_BINARY_DIR}/InitialCache.cmake
+      -DJavaBuildExportTest_DIR:PATH=${JavaExportImport_BINARY_DIR}/BuildExport
+      -DJavaInstallExportTest_DIR:PATH=${JavaExportImport_BINARY_DIR}/Root/share/cmake
+  VERBATIM
+  )
+add_custom_target(ImportTarget ALL DEPENDS ${JavaExportImport_BINARY_DIR}/ImportProject)
+add_dependencies(ImportTarget BuildExportTarget InstallExportTarget)
+set_property(
+  SOURCE ${JavaExportImport_BINARY_DIR}/ImportProject
+  PROPERTY SYMBOLIC 1
+  )
+
+add_executable(JavaExportImport main.c)
+add_dependencies(JavaExportImport ImportTarget)
diff --git a/Tests/JavaExportImport/Import/CMakeLists.txt b/Tests/JavaExportImport/Import/CMakeLists.txt
new file mode 100644
index 0000000..79a1447
--- /dev/null
+++ b/Tests/JavaExportImport/Import/CMakeLists.txt
@@ -0,0 +1,14 @@
+project(import Java)
+
+cmake_minimum_required (VERSION 3.5)
+set(CMAKE_VERBOSE_MAKEFILE 1)
+
+find_package(Java COMPONENTS Development)
+include(UseJava)
+
+find_package(JavaBuildExportTest REQUIRED)
+find_package(JavaInstallExportTest REQUIRED)
+
+add_jar(${PROJECT_NAME}
+  SOURCES Import.java
+  INCLUDE_JARS foo bar)
diff --git a/Tests/JavaExportImport/Import/Import.java b/Tests/JavaExportImport/Import/Import.java
new file mode 100644
index 0000000..08eb03f
--- /dev/null
+++ b/Tests/JavaExportImport/Import/Import.java
@@ -0,0 +1,10 @@
+class Import
+{
+  public static void main(String args[])
+  {
+    Foo foo = new Foo();
+    Bar bar = new Bar();
+    foo.printName();
+    bar.printName();
+  }
+}
diff --git a/Tests/JavaExportImport/InitialCache.cmake.in b/Tests/JavaExportImport/InitialCache.cmake.in
new file mode 100644
index 0000000..d15e6d1
--- /dev/null
+++ b/Tests/JavaExportImport/InitialCache.cmake.in
@@ -0,0 +1,5 @@
+set(CMAKE_MAKE_PROGRAM "@CMake_TEST_NESTED_MAKE_PROGRAM@" CACHE FILEPATH "Make Program")
+set(Java_JAVA_EXECUTABLE "@Java_JAVA_EXECUTABLE@" CACHE STRING "Java Interpreter")
+set(Java_JAVAC_EXECUTABLE "@Java_JAVAC_EXECUTABLE@" CACHE STRING "Java Compiler")
+set(Java_JAR_EXECUTABLE "@Java_JAR_EXECUTABLE@" CACHE STRING "Java Archive Tool")
+set(CMAKE_INSTALL_PREFIX "@JavaExportImport_BINARY_DIR@/Root" CACHE STRING "Installation Prefix")
diff --git a/Tests/JavaExportImport/InstallExport/Bar.java b/Tests/JavaExportImport/InstallExport/Bar.java
new file mode 100644
index 0000000..a1068a8
--- /dev/null
+++ b/Tests/JavaExportImport/InstallExport/Bar.java
@@ -0,0 +1,11 @@
+class Bar
+{
+  public Bar()
+  {
+  }
+
+  public void printName()
+  {
+    System.out.println("Bar");
+  }
+}
diff --git a/Tests/JavaExportImport/InstallExport/CMakeLists.txt b/Tests/JavaExportImport/InstallExport/CMakeLists.txt
new file mode 100644
index 0000000..0a9afd9
--- /dev/null
+++ b/Tests/JavaExportImport/InstallExport/CMakeLists.txt
@@ -0,0 +1,14 @@
+project(bar Java)
+
+cmake_minimum_required (VERSION 3.5)
+set(CMAKE_VERBOSE_MAKEFILE 1)
+
+find_package(Java COMPONENTS Development)
+include(UseJava)
+
+add_jar(${PROJECT_NAME} Bar.java)
+install_jar(${PROJECT_NAME} DESTINATION share/java)
+install_jar_exports(
+  TARGETS ${PROJECT_NAME}
+  FILE JavaInstallExportTestConfig.cmake
+  DESTINATION share/cmake)
diff --git a/Tests/JavaExportImport/main.c b/Tests/JavaExportImport/main.c
new file mode 100644
index 0000000..f8b643a
--- /dev/null
+++ b/Tests/JavaExportImport/main.c
@@ -0,0 +1,4 @@
+int main()
+{
+  return 0;
+}
diff --git a/Tests/MakeClean/CMakeLists.txt b/Tests/MakeClean/CMakeLists.txt
index 8ac624a..fbd4995 100644
--- a/Tests/MakeClean/CMakeLists.txt
+++ b/Tests/MakeClean/CMakeLists.txt
@@ -34,7 +34,7 @@ endforeach()
 # Configure an executable to check that all the files are missing.
 set(CHECK_FILES)
 foreach(f ${TOCLEAN_FILES})
-  set(CHECK_FILES "${CHECK_FILES}      \"${f}\",\n")
+  string(APPEND CHECK_FILES "      \"${f}\",\n")
 endforeach()
 configure_file(${MakeClean_SOURCE_DIR}/check_clean.c.in
                ${MakeClean_BINARY_DIR}/check_clean.c @ONLY)
diff --git a/Tests/MathTest/CMakeLists.txt b/Tests/MathTest/CMakeLists.txt
index 34beaa0..ed2c7d4 100644
--- a/Tests/MathTest/CMakeLists.txt
+++ b/Tests/MathTest/CMakeLists.txt
@@ -16,7 +16,7 @@ set(FILE_EXPRESSIONS "")
 foreach(expression
     ${expressions})
   math(EXPR expr "${expression}")
-  set(FILE_EXPRESSIONS "${FILE_EXPRESSIONS}TEST_EXPRESSION(${expression}, ${expr})\n")
+  string(APPEND FILE_EXPRESSIONS "TEST_EXPRESSION(${expression}, ${expr})\n")
 endforeach()
 
 configure_file(
diff --git a/Tests/Module/ExternalData/CMakeLists.txt b/Tests/Module/ExternalData/CMakeLists.txt
index f07ab71..1018dd8 100644
--- a/Tests/Module/ExternalData/CMakeLists.txt
+++ b/Tests/Module/ExternalData/CMakeLists.txt
@@ -53,4 +53,5 @@ ExternalData_Add_Target(Data1)
 add_subdirectory(Data2)
 add_subdirectory(Data3)
 add_subdirectory(Data4)
+add_subdirectory(Data5)
 add_subdirectory(DataNoSymlinks)
diff --git a/Tests/Module/ExternalData/Data5/CMakeLists.txt b/Tests/Module/ExternalData/Data5/CMakeLists.txt
new file mode 100644
index 0000000..13c7fab
--- /dev/null
+++ b/Tests/Module/ExternalData/Data5/CMakeLists.txt
@@ -0,0 +1,22 @@
+# Test adding the same data file in multiple tests
+ExternalData_Add_Test(Data5.A
+  NAME Data5Check.A
+  COMMAND ${CMAKE_COMMAND}
+    -D Data5=DATA{../Data.dat}
+    -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake
+  )
+ExternalData_Add_Target(Data5.A)
+ExternalData_Add_Test(Data5.B
+  NAME Data5Check.B
+  COMMAND ${CMAKE_COMMAND}
+    -D Data5=DATA{../Data.dat}
+    -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake
+  )
+ExternalData_Add_Target(Data5.B)
+ExternalData_Add_Test(Data5.C
+  NAME Data5Check.C
+  COMMAND ${CMAKE_COMMAND}
+    -D Data5=DATA{../Data.dat}
+    -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake
+  )
+ExternalData_Add_Target(Data5.C)
diff --git a/Tests/Module/ExternalData/Data5/Data5Check.cmake b/Tests/Module/ExternalData/Data5/Data5Check.cmake
new file mode 100644
index 0000000..4dea9a4
--- /dev/null
+++ b/Tests/Module/ExternalData/Data5/Data5Check.cmake
@@ -0,0 +1,4 @@
+file(STRINGS "${Data5}" lines LIMIT_INPUT 1024)
+if(NOT "x${lines}" STREQUAL "xInput file already transformed.")
+  message(SEND_ERROR "Input file:\n  ${Data5}\ndoes not have expected content, but [[${lines}]]")
+endif()
diff --git a/Tests/Module/GenerateExportHeader/CMakeLists.txt b/Tests/Module/GenerateExportHeader/CMakeLists.txt
deleted file mode 100644
index 8b94ca7..0000000
--- a/Tests/Module/GenerateExportHeader/CMakeLists.txt
+++ /dev/null
@@ -1,139 +0,0 @@
-cmake_minimum_required(VERSION 2.8.5 FATAL_ERROR)
-cmake_policy(SET CMP0054 NEW)
-
-project(GenerateExportHeader)
-
-# Prevent timeout on Watcom by not running the tests.
-if ("${CMAKE_CXX_COMPILER_ID}" MATCHES Watcom)
-  file(WRITE
-    "${CMAKE_CURRENT_BINARY_DIR}/main.cxx"
-    "int main() { return 0; }
-  "
-  )
-
-  add_executable(
-    GenerateExportHeader
-    "${CMAKE_CURRENT_BINARY_DIR}/main.cxx"
-  )
-  return()
-endif()
-
-include(CheckCXXCompilerFlag)
-
-set( CMAKE_INCLUDE_CURRENT_DIR ON )
-
-macro(TEST_FAIL value msg)
-  if (${value})
-    message (SEND_ERROR "Test fail:" "${msg}\n" ${Out} )
-  endif ()
-endmacro()
-
-macro(TEST_PASS value msg)
-  if (NOT ${value})
-    message (SEND_ERROR "Test fail:" "${msg}\n" ${Out} )
-  endif ()
-endmacro()
-
-check_cxx_compiler_flag(-Werror HAS_WERROR_FLAG)
-
-if(HAS_WERROR_FLAG)
-  set(ERROR_FLAG "-Werror")
-else()
-  # MSVC
-  # And intel on windows?
-  # http://software.intel.com/en-us/articles/how-to-handle-warnings-message-in-compiler/?wapkw=%28compiler+warning+message%29
-  check_cxx_compiler_flag("/WX" HAS_WX_FLAG)
-  if(HAS_WX_FLAG)
-    set(ERROR_FLAG "/WX")
-  else()
-    # Sun CC
-    # http://www.acsu.buffalo.edu/~charngda/sunstudio.html
-    check_cxx_compiler_flag("-errwarn=%all" HAS_ERRWARN_ALL)
-    if (HAS_ERRWARN_ALL)
-      set(ERROR_FLAG "-errwarn=%all")
-    else()
-    endif()
-  endif()
-endif()
-
-include(GenerateExportHeader)
-
-set(CMAKE_CXX_STANDARD 98)
-
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
-    CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA")
-endif ()
-
-# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
-if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
-    CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
-  set(CMAKE_CXX_STANDARD 11)
-endif()
-
-add_subdirectory(lib_shared_and_static)
-
-add_compiler_export_flags()
-
-set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
-
-message("#### COMPILER_HAS_DEPRECATED: " ${COMPILER_HAS_DEPRECATED})
-message("#### COMPILER_HAS_HIDDEN_VISIBILITY: " ${COMPILER_HAS_HIDDEN_VISIBILITY})
-message("#### WIN32: " ${WIN32})
-message("#### HAS_WERROR_FLAG: " ${HAS_WERROR_FLAG})
-
-set(link_libraries)
-macro(macro_add_test_library name)
-  add_subdirectory(${name})
-  include_directories(${name}
-            ${${name}_BINARY_DIR} # For the export header.
-  )
-  list(APPEND link_libraries ${name})
-endmacro()
-
-macro_add_test_library(libshared)
-macro_add_test_library(libstatic)
-
-add_subdirectory(nodeprecated)
-if(NOT BORLAND)
-  add_subdirectory(c_identifier)
-endif()
-
-if (CMAKE_COMPILER_IS_GNUCXX OR (${CMAKE_CXX_COMPILER_ID} MATCHES Clang))
-  # No need to clutter the test output with warnings.
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations")
-endif()
-
-if(MSVC AND COMPILER_HAS_DEPRECATED)
-  add_definitions(/wd4996)
-endif()
-
-add_executable(GenerateExportHeader exportheader_test.cpp)
-
-target_link_libraries(GenerateExportHeader ${link_libraries})
-if (WIN32 OR CYGWIN)
-  if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
-    CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
-    set(_platform Win32-Clang)
-  elseif(MSVC AND COMPILER_HAS_DEPRECATED)
-    set(_platform Win32)
-  elseif((MINGW OR CYGWIN) AND COMPILER_HAS_DEPRECATED)
-    set(_platform MinGW)
-  else()
-    set(_platform WinEmpty)
-  endif()
-elseif(COMPILER_HAS_HIDDEN_VISIBILITY AND USE_COMPILER_HIDDEN_VISIBILITY)
-  set(_platform UNIX)
-elseif(COMPILER_HAS_DEPRECATED)
-  set(_platform UNIX_DeprecatedOnly)
-else()
-  set(_platform Empty)
-endif()
-message("#### Testing reference: ${_platform}")
-target_compile_definitions(GenerateExportHeader
-  PRIVATE
-    "SRC_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/reference/${_platform}\""
-    "BIN_DIR=\"${CMAKE_CURRENT_BINARY_DIR}\""
-)
diff --git a/Tests/Module/GenerateExportHeader/c_identifier/CMakeLists.txt b/Tests/Module/GenerateExportHeader/c_identifier/CMakeLists.txt
deleted file mode 100644
index 9f8c8ef..0000000
--- a/Tests/Module/GenerateExportHeader/c_identifier/CMakeLists.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-project(c_identifier)
-
-set(c_identifier_lib_SRCS
-  c_identifier_class.cpp
-)
-
-add_library(7c-identifier-lib++ SHARED c_identifier_class.cpp)
-
-generate_export_header(7c-identifier-lib++)
-
-add_executable(c_identifier_exe main.cpp)
-
-target_link_libraries(c_identifier_exe 7c-identifier-lib++)
diff --git a/Tests/Module/GenerateExportHeader/c_identifier/main.cpp b/Tests/Module/GenerateExportHeader/c_identifier/main.cpp
deleted file mode 100644
index 891bc42..0000000
--- a/Tests/Module/GenerateExportHeader/c_identifier/main.cpp
+++ /dev/null
@@ -1,8 +0,0 @@
-
-#include "c_identifier_class.h"
-
-int main(int argc, char** argv)
-{
-  CIdentifierClass cic;
-  return cic.someMethod();
-}
diff --git a/Tests/Module/GenerateExportHeader/exportheader_test.cpp b/Tests/Module/GenerateExportHeader/exportheader_test.cpp
deleted file mode 100644
index 26bea7e..0000000
--- a/Tests/Module/GenerateExportHeader/exportheader_test.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-
-#include "libshared.h"
-
-#include "libstatic.h"
-
-// #define BUILD_FAIL
-
-#ifndef BUILD_FAIL
-#define DOES_NOT_BUILD(function)
-#else
-#define DOES_NOT_BUILD(function) function
-#endif
-
-#include <fstream>
-#include <iostream>
-#include <stdlib.h>
-#include <string>
-
-void compare(const char* refName, const char* testName)
-{
-  std::ifstream ref;
-  ref.open(refName);
-  if (!ref.is_open()) {
-    std::cout << "Could not open \"" << refName << "\"." << std::endl;
-    exit(1);
-  }
-  std::ifstream test;
-  test.open(testName);
-  if (!test.is_open()) {
-    std::cout << "Could not open \"" << testName << "\"." << std::endl;
-    exit(1);
-  }
-
-  while (!ref.eof() && !test.eof()) {
-    std::string refLine;
-    std::string testLine;
-    std::getline(ref, refLine);
-    std::getline(test, testLine);
-    // Some very old Borland runtimes (C++ Builder 5 WITHOUT Update 1) add a
-    // trailing null to the string that we need to strip before testing for a
-    // trailing space.
-    if (refLine.size() && refLine[refLine.size() - 1] == 0) {
-      refLine = refLine.substr(0, refLine.size() - 1);
-    }
-    if (testLine.size() && testLine[testLine.size() - 1] == 0) {
-      testLine = testLine.substr(0, testLine.size() - 1);
-    }
-    // The reference files never have trailing spaces:
-    if (testLine.size() && testLine[testLine.size() - 1] == ' ') {
-      testLine = testLine.substr(0, testLine.size() - 1);
-    }
-    if (refLine != testLine) {
-      std::cout << "Ref and test are not the same:\n  Ref:  \"" << refLine
-                << "\"\n  Test: \"" << testLine << "\"\n";
-      exit(1);
-    }
-  }
-  if (!ref.eof() || !test.eof()) {
-    std::cout << "Ref and test have differing numbers of lines.";
-    exit(1);
-  }
-}
-
-int main()
-{
-  {
-    Libshared l;
-    l.libshared();
-    l.libshared_exported();
-    l.libshared_deprecated();
-    l.libshared_not_exported();
-
-    DOES_NOT_BUILD(l.libshared_excluded();)
-  }
-
-  {
-    LibsharedNotExported l;
-    DOES_NOT_BUILD(l.libshared();)
-    l.libshared_exported();
-    l.libshared_deprecated();
-    DOES_NOT_BUILD(l.libshared_not_exported();)
-    DOES_NOT_BUILD(l.libshared_excluded();)
-  }
-
-  {
-    LibsharedExcluded l;
-    DOES_NOT_BUILD(l.libshared();)
-    l.libshared_exported();
-    l.libshared_deprecated();
-    DOES_NOT_BUILD(l.libshared_not_exported();)
-    DOES_NOT_BUILD(l.libshared_excluded();)
-  }
-
-  libshared_exported();
-  libshared_deprecated();
-  DOES_NOT_BUILD(libshared_not_exported();)
-  DOES_NOT_BUILD(libshared_excluded();)
-
-  {
-    Libstatic l;
-    l.libstatic();
-    l.libstatic_exported();
-    l.libstatic_deprecated();
-    l.libstatic_not_exported();
-    l.libstatic_excluded();
-  }
-
-  {
-    LibstaticNotExported l;
-    l.libstatic();
-    l.libstatic_exported();
-    l.libstatic_deprecated();
-    l.libstatic_not_exported();
-    l.libstatic_excluded();
-  }
-
-  {
-    LibstaticExcluded l;
-    l.libstatic();
-    l.libstatic_exported();
-    l.libstatic_deprecated();
-    l.libstatic_not_exported();
-    l.libstatic_excluded();
-  }
-
-  libstatic_exported();
-  libstatic_deprecated();
-  libstatic_not_exported();
-  libstatic_excluded();
-
-  compare(SRC_DIR "/libshared_export.h",
-          BIN_DIR "/libshared/libshared_export.h");
-  compare(SRC_DIR "/libstatic_export.h",
-          BIN_DIR "/libstatic/libstatic_export.h");
-
-  return 0;
-}
diff --git a/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt b/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt
deleted file mode 100644
index c1be125..0000000
--- a/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-
-cmake_minimum_required(VERSION 2.8)
-
-project(lib_shared_and_static)
-
-include(GenerateExportHeader)
-
-set(CMAKE_CXX_VISIBILITY_PRESET hidden)
-set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
-
-if (CMAKE_CXX_FLAGS MATCHES "-fvisibility=hidden")
-  message(SEND_ERROR "Do not use add_compiler_export_flags before adding this directory")
-endif()
-if (CMAKE_CXX_FLAGS MATCHES "-fvisibility-inlines-hidden")
-  message(SEND_ERROR "Do not use add_compiler_export_flags before adding this directory")
-endif()
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-set(lib_SRCS
-  libshared_and_static.cpp
-)
-
-add_library(shared_variant SHARED ${lib_SRCS})
-set_target_properties(shared_variant PROPERTIES DEFINE_SYMBOL SHARED_VARIANT_MAKEDLL)
-add_library(static_variant ${lib_SRCS})
-
-generate_export_header(shared_variant
-  BASE_NAME libshared_and_static
-  PREFIX_NAME MYPREFIX_
-)
-
-set_target_properties(static_variant PROPERTIES COMPILE_FLAGS -DLIBSHARED_AND_STATIC_STATIC_DEFINE)
-
-export(TARGETS shared_variant static_variant FILE Targets.cmake)
diff --git a/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp b/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp
deleted file mode 100644
index 2764905..0000000
--- a/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-
-#include "libshared_and_static.h"
-
-int LibsharedAndStatic::libshared_and_static() const
-{
-  return 0;
-}
-
-int LibsharedAndStatic::libshared_and_static_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStatic::libshared_and_static_deprecated() const
-{
-  return 0;
-}
-
-int LibsharedAndStatic::libshared_and_static_not_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStatic::libshared_and_static_excluded() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticNotExported::libshared_and_static() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticNotExported::libshared_and_static_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticNotExported::libshared_and_static_deprecated() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticNotExported::libshared_and_static_not_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticNotExported::libshared_and_static_excluded() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticExcluded::libshared_and_static() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticExcluded::libshared_and_static_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticExcluded::libshared_and_static_deprecated() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticExcluded::libshared_and_static_not_exported() const
-{
-  return 0;
-}
-
-int LibsharedAndStaticExcluded::libshared_and_static_excluded() const
-{
-  return 0;
-}
-
-int libshared_and_static()
-{
-  return 0;
-}
-
-int libshared_and_static_exported()
-{
-  return 0;
-}
-
-int libshared_and_static_deprecated()
-{
-  return 0;
-}
-
-int libshared_and_static_not_exported()
-{
-  return 0;
-}
-
-int libshared_and_static_excluded()
-{
-  return 0;
-}
diff --git a/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h b/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h
deleted file mode 100644
index ea672fe..0000000
--- a/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h
+++ /dev/null
@@ -1,66 +0,0 @@
-
-#ifndef SHARED_AND_STATIC_H
-#define SHARED_AND_STATIC_H
-
-#include "libshared_and_static_export.h"
-
-class MYPREFIX_LIBSHARED_AND_STATIC_EXPORT LibsharedAndStatic
-{
-public:
-  int libshared_and_static() const;
-
-  int libshared_and_static_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED
-  libshared_and_static_deprecated() const;
-
-  int libshared_and_static_not_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT
-  libshared_and_static_excluded() const;
-};
-
-class LibsharedAndStaticNotExported
-{
-public:
-  int libshared_and_static() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT
-  libshared_and_static_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED
-  libshared_and_static_deprecated() const;
-
-  int libshared_and_static_not_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT
-  libshared_and_static_excluded() const;
-};
-
-class MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT LibsharedAndStaticExcluded
-{
-public:
-  int libshared_and_static() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT
-  libshared_and_static_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED
-  libshared_and_static_deprecated() const;
-
-  int libshared_and_static_not_exported() const;
-
-  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT
-  libshared_and_static_excluded() const;
-};
-
-MYPREFIX_LIBSHARED_AND_STATIC_EXPORT int libshared_and_static_exported();
-
-MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT int
-libshared_and_static_deprecated();
-
-int libshared_and_static_not_exported();
-
-int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT libshared_and_static_excluded();
-
-#endif
diff --git a/Tests/Module/GenerateExportHeader/libshared/CMakeLists.txt b/Tests/Module/GenerateExportHeader/libshared/CMakeLists.txt
deleted file mode 100644
index e20adb1..0000000
--- a/Tests/Module/GenerateExportHeader/libshared/CMakeLists.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-
-cmake_minimum_required(VERSION 2.8)
-
-project(libshared)
-
-include(GenerateExportHeader)
-
-add_compiler_export_flags()
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-add_library(libshared SHARED libshared.cpp)
-
-generate_export_header(libshared)
-
-export(TARGETS libshared FILE Targets.cmake)
diff --git a/Tests/Module/GenerateExportHeader/libshared/libshared.cpp b/Tests/Module/GenerateExportHeader/libshared/libshared.cpp
deleted file mode 100644
index ad6d356..0000000
--- a/Tests/Module/GenerateExportHeader/libshared/libshared.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-
-#include "libshared.h"
-
-int Libshared::libshared() const
-{
-  return 0;
-}
-
-int Libshared::libshared_exported() const
-{
-  return 0;
-}
-
-int Libshared::libshared_deprecated() const
-{
-  return 0;
-}
-
-int Libshared::libshared_not_exported() const
-{
-  return 0;
-}
-
-int Libshared::libshared_excluded() const
-{
-  return 0;
-}
-
-int LibsharedNotExported::libshared() const
-{
-  return 0;
-}
-
-int LibsharedNotExported::libshared_exported() const
-{
-  return 0;
-}
-
-int LibsharedNotExported::libshared_deprecated() const
-{
-  return 0;
-}
-
-int LibsharedNotExported::libshared_not_exported() const
-{
-  return 0;
-}
-
-int LibsharedNotExported::libshared_excluded() const
-{
-  return 0;
-}
-
-int LibsharedExcluded::libshared() const
-{
-  return 0;
-}
-
-int LibsharedExcluded::libshared_exported() const
-{
-  return 0;
-}
-
-int LibsharedExcluded::libshared_deprecated() const
-{
-  return 0;
-}
-
-int LibsharedExcluded::libshared_not_exported() const
-{
-  return 0;
-}
-
-int LibsharedExcluded::libshared_excluded() const
-{
-  return 0;
-}
-
-int libshared()
-{
-  return 0;
-}
-
-int libshared_exported()
-{
-  return 0;
-}
-
-int libshared_deprecated()
-{
-  return 0;
-}
-
-int libshared_not_exported()
-{
-  return 0;
-}
-
-int libshared_excluded()
-{
-  return 0;
-}
diff --git a/Tests/Module/GenerateExportHeader/libshared/libshared.h b/Tests/Module/GenerateExportHeader/libshared/libshared.h
deleted file mode 100644
index bd9f2e3..0000000
--- a/Tests/Module/GenerateExportHeader/libshared/libshared.h
+++ /dev/null
@@ -1,57 +0,0 @@
-
-#ifndef LIBSHARED_H
-#define LIBSHARED_H
-
-#include "libshared_export.h"
-
-class LIBSHARED_EXPORT Libshared
-{
-public:
-  int libshared() const;
-
-  int libshared_exported() const;
-
-  int LIBSHARED_DEPRECATED libshared_deprecated() const;
-
-  int libshared_not_exported() const;
-
-  int LIBSHARED_NO_EXPORT libshared_excluded() const;
-};
-
-class LibsharedNotExported
-{
-public:
-  int libshared() const;
-
-  int LIBSHARED_EXPORT libshared_exported() const;
-
-  int LIBSHARED_DEPRECATED_EXPORT libshared_deprecated() const;
-
-  int libshared_not_exported() const;
-
-  int LIBSHARED_NO_EXPORT libshared_excluded() const;
-};
-
-class LIBSHARED_NO_EXPORT LibsharedExcluded
-{
-public:
-  int libshared() const;
-
-  int LIBSHARED_EXPORT libshared_exported() const;
-
-  int LIBSHARED_DEPRECATED_EXPORT libshared_deprecated() const;
-
-  int libshared_not_exported() const;
-
-  int LIBSHARED_NO_EXPORT libshared_excluded() const;
-};
-
-LIBSHARED_EXPORT int libshared_exported();
-
-LIBSHARED_DEPRECATED_EXPORT int libshared_deprecated();
-
-int libshared_not_exported();
-
-int LIBSHARED_NO_EXPORT libshared_excluded();
-
-#endif
diff --git a/Tests/Module/GenerateExportHeader/libstatic/CMakeLists.txt b/Tests/Module/GenerateExportHeader/libstatic/CMakeLists.txt
deleted file mode 100644
index b2db3ea..0000000
--- a/Tests/Module/GenerateExportHeader/libstatic/CMakeLists.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-
-cmake_minimum_required(VERSION 2.8)
-
-project(libstatic)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-include(GenerateExportHeader)
-
-add_compiler_export_flags()
-
-# Show that the export header has no effect on a static library.
-
-add_library(libstatic STATIC libstatic.cpp)
-
-generate_export_header(libstatic)
-
-export(TARGETS libstatic FILE Targets.cmake)
diff --git a/Tests/Module/GenerateExportHeader/libstatic/libstatic.cpp b/Tests/Module/GenerateExportHeader/libstatic/libstatic.cpp
deleted file mode 100644
index 89381af..0000000
--- a/Tests/Module/GenerateExportHeader/libstatic/libstatic.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-
-#include "libstatic.h"
-
-int Libstatic::libstatic() const
-{
-  return 0;
-}
-
-int Libstatic::libstatic_exported() const
-{
-  return 0;
-}
-
-int Libstatic::libstatic_deprecated() const
-{
-  return 0;
-}
-
-int Libstatic::libstatic_not_exported() const
-{
-  return 0;
-}
-
-int Libstatic::libstatic_excluded() const
-{
-  return 0;
-}
-
-int LibstaticNotExported::libstatic() const
-{
-  return 0;
-}
-
-int LibstaticNotExported::libstatic_exported() const
-{
-  return 0;
-}
-
-int LibstaticNotExported::libstatic_deprecated() const
-{
-  return 0;
-}
-
-int LibstaticNotExported::libstatic_not_exported() const
-{
-  return 0;
-}
-
-int LibstaticNotExported::libstatic_excluded() const
-{
-  return 0;
-}
-
-int LibstaticExcluded::libstatic() const
-{
-  return 0;
-}
-
-int LibstaticExcluded::libstatic_exported() const
-{
-  return 0;
-}
-
-int LibstaticExcluded::libstatic_deprecated() const
-{
-  return 0;
-}
-
-int LibstaticExcluded::libstatic_not_exported() const
-{
-  return 0;
-}
-
-int LibstaticExcluded::libstatic_excluded() const
-{
-  return 0;
-}
-
-int libstatic_exported()
-{
-  return 0;
-}
-
-int libstatic_deprecated()
-{
-  return 0;
-}
-
-int libstatic_not_exported()
-{
-  return 0;
-}
-
-int libstatic_excluded()
-{
-  return 0;
-}
diff --git a/Tests/Module/GenerateExportHeader/libstatic/libstatic.h b/Tests/Module/GenerateExportHeader/libstatic/libstatic.h
deleted file mode 100644
index 6072d9b..0000000
--- a/Tests/Module/GenerateExportHeader/libstatic/libstatic.h
+++ /dev/null
@@ -1,57 +0,0 @@
-
-#ifndef LIBSTATIC_H
-#define LIBSTATIC_H
-
-#include "libstatic_export.h"
-
-class LIBSTATIC_EXPORT Libstatic
-{
-public:
-  int libstatic() const;
-
-  int libstatic_exported() const;
-
-  int LIBSTATIC_DEPRECATED libstatic_deprecated() const;
-
-  int libstatic_not_exported() const;
-
-  int LIBSTATIC_NO_EXPORT libstatic_excluded() const;
-};
-
-class LibstaticNotExported
-{
-public:
-  int libstatic() const;
-
-  int LIBSTATIC_EXPORT libstatic_exported() const;
-
-  int LIBSTATIC_DEPRECATED libstatic_deprecated() const;
-
-  int libstatic_not_exported() const;
-
-  int LIBSTATIC_NO_EXPORT libstatic_excluded() const;
-};
-
-class LIBSTATIC_NO_EXPORT LibstaticExcluded
-{
-public:
-  int libstatic() const;
-
-  int LIBSTATIC_EXPORT libstatic_exported() const;
-
-  int LIBSTATIC_DEPRECATED libstatic_deprecated() const;
-
-  int libstatic_not_exported() const;
-
-  int LIBSTATIC_NO_EXPORT libstatic_excluded() const;
-};
-
-LIBSTATIC_EXPORT int libstatic_exported();
-
-LIBSTATIC_DEPRECATED_EXPORT int libstatic_deprecated();
-
-int libstatic_not_exported();
-
-int LIBSTATIC_NO_EXPORT libstatic_excluded();
-
-#endif
diff --git a/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt b/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt
deleted file mode 100644
index aeeb13a..0000000
--- a/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-cmake_minimum_required(VERSION 2.8)
-
-project(nodeprecated)
-
-execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined)
-execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined)
-
-configure_file(CMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined/CMakeLists.txt)
-set(DEFINE_NO_DEPRECATED DEFINE_NO_DEPRECATED)
-configure_file(CMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined/CMakeLists.txt)
-
-try_compile(Result ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined_build
-  ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined
-  nodeprecated_test
-  OUTPUT_VARIABLE Out
-)
-
-test_pass(Result "Failed to build without no-deprecated define")
-
-try_compile(Result ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined_build
-  ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined
-  nodeprecated_test
-  OUTPUT_VARIABLE Out
-)
-
-test_fail(Result "Built even with no-deprecated define")
\ No newline at end of file
diff --git a/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt.in b/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt.in
deleted file mode 100644
index d8dc482..0000000
--- a/Tests/Module/GenerateExportHeader/nodeprecated/CMakeLists.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-cmake_minimum_required(VERSION 2.8)
-
-project(nodeprecated_test)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-include(GenerateExportHeader)
-
-add_library(nodeprecatedlib SHARED someclass.cpp)
-
-generate_export_header(nodeprecatedlib @DEFINE_NO_DEPRECATED@)
-
-add_executable(nodeprecatedconsumer main.cpp)
-
-target_link_libraries(nodeprecatedconsumer nodeprecatedlib)
diff --git a/Tests/Module/GenerateExportHeader/nodeprecated/src/main.cpp b/Tests/Module/GenerateExportHeader/nodeprecated/src/main.cpp
deleted file mode 100644
index eec46d3..0000000
--- a/Tests/Module/GenerateExportHeader/nodeprecated/src/main.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-
-#include "someclass.h"
-
-int main(int, char**)
-{
-  SomeClass sc;
-  sc.someMethod();
-  return 0;
-}
diff --git a/Tests/Plugin/CMakeLists.txt b/Tests/Plugin/CMakeLists.txt
index 49ff317..f52b479 100644
--- a/Tests/Plugin/CMakeLists.txt
+++ b/Tests/Plugin/CMakeLists.txt
@@ -32,7 +32,7 @@ set(CMAKE_CXX_STANDARD 98)
 # template support also need a flag to use the newer C++ library.
 if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
     CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA")
+  string(APPEND CMAKE_CXX_FLAGS " -AA")
 endif ()
 
 # Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
diff --git a/Tests/Plugin/src/example_exe.cxx b/Tests/Plugin/src/example_exe.cxx
index 857ad54..017fbf6 100644
--- a/Tests/Plugin/src/example_exe.cxx
+++ b/Tests/Plugin/src/example_exe.cxx
@@ -31,6 +31,7 @@ int main()
   kwsys::DynamicLoader::LibraryHandle handle =
     kwsys::DynamicLoader::OpenLibrary(libName.c_str());
   if (!handle) {
+    // Leave the .c_str() on this one.  It is needed on OpenWatcom.
     std::cerr << "Could not open plugin \"" << libName.c_str() << "\"!"
               << std::endl;
     return 1;
diff --git a/Tests/Preprocess/CMakeLists.txt b/Tests/Preprocess/CMakeLists.txt
index b930f56..15f0338 100644
--- a/Tests/Preprocess/CMakeLists.txt
+++ b/Tests/Preprocess/CMakeLists.txt
@@ -57,7 +57,7 @@ if(NOT BORLAND AND NOT PP_VS70)
   set(SEMICOLON "\;")
 endif()
 
-set(STRING_EXTRA "${STRING_EXTRA} ")
+string(APPEND STRING_EXTRA " ")
 
 if(NOT PP_BORLAND AND NOT PP_WATCOM)
   # Borland, WMake: multiple spaces
@@ -65,7 +65,7 @@ if(NOT PP_BORLAND AND NOT PP_WATCOM)
   # quoted strings when passing to the compiler.  It does not have
   # trouble passing to other tools, and the compiler may be directly
   # invoked from the command line.
-  set(STRING_EXTRA "${STRING_EXTRA} ")
+  string(APPEND STRING_EXTRA " ")
 endif()
 
 if(NOT PP_VS)
@@ -73,21 +73,21 @@ if(NOT PP_VS)
   # Visual Studio will not accept a comma in the value of a definition.
   # The comma-separated list of PreprocessorDefinitions in the project
   # file seems to be parsed before the content of entries is examined.
-  set(STRING_EXTRA "${STRING_EXTRA},")
+  string(APPEND STRING_EXTRA ",")
 endif()
 
 if(NOT PP_MINGW)
   # MinGW: &
   # When inside -D"FOO=\"a & b\"" MinGW make wants -D"FOO=\"a "&" b\""
   # but it does not like quoted ampersand elsewhere.
-  set(STRING_EXTRA "${STRING_EXTRA}&")
+  string(APPEND STRING_EXTRA "&")
 endif()
 
 if(NOT PP_MINGW)
   # MinGW: |
   # When inside -D"FOO=\"a | b\"" MinGW make wants -D"FOO=\"a "|" b\""
   # but it does not like quoted pipe elsewhere.
-  set(STRING_EXTRA "${STRING_EXTRA}|")
+  string(APPEND STRING_EXTRA "|")
 endif()
 
 if(NOT PP_BORLAND AND NOT PP_MINGW AND NOT PP_NMAKE)
@@ -95,13 +95,13 @@ if(NOT PP_BORLAND AND NOT PP_MINGW AND NOT PP_NMAKE)
   # When inside -D"FOO=\"a ^ b\"" the make tools want -D"FOO=\"a "^" b\""
   # but do not like quoted carrot elsewhere.  In NMake the non-quoted
   # syntax works when the flags are not in a make variable.
-  set(STRING_EXTRA "${STRING_EXTRA}^")
+  string(APPEND STRING_EXTRA "^")
 endif()
 
 if(NOT PP_BORLAND AND NOT PP_MINGW AND NOT PP_NMAKE)
   # Borland, MinGW: < >
   # Angle-brackets have funny behavior that is hard to escape.
-  set(STRING_EXTRA "${STRING_EXTRA}<>")
+  string(APPEND STRING_EXTRA "<>")
 endif()
 
 set(EXPR_OP1 "/")
@@ -122,7 +122,7 @@ if((NOT MSVC OR PP_NMAKE) AND
   # be written just '%'.  However nmake requires '%%' except when using
   # response files.  Currently we have no way to affect escaping based
   # on whether flags go in a response file, so we just have to skip it.
-  set(STRING_EXTRA "${STRING_EXTRA}%")
+  string(APPEND STRING_EXTRA "%")
   set(EXPR_OP1 "%")
 endif()
 
@@ -130,9 +130,9 @@ endif()
 # The XL compiler cannot pass unbalanced parens correctly to a tool
 # it launches internally.
 if(CMAKE_C_COMPILER_ID STREQUAL "XL")
-  set(STRING_EXTRA "${STRING_EXTRA}()")
+  string(APPEND STRING_EXTRA "()")
 else()
-  set(STRING_EXTRA "${STRING_EXTRA})(")
+  string(APPEND STRING_EXTRA ")(")
 endif()
 
 # General: \"
@@ -146,7 +146,7 @@ endif()
 #    internal tool to do preprocessing .
 if((PP_NMAKE OR PP_UMAKE) AND
     NOT CMAKE_C_COMPILER_ID STREQUAL "XL")
-  set(STRING_EXTRA "${STRING_EXTRA}\\\"")
+  string(APPEND STRING_EXTRA "\\\"")
 endif()
 
 # General: #
@@ -183,15 +183,15 @@ set(EXPR "x*y+!(x==(y+1*2))*f(x${EXPR_OP1}2)")
 
 if(NOT WATCOM)
   # Watcom does not support - or / because it parses them as options.
-  set(EXPR "${EXPR} + y/x-x")
+  string(APPEND EXPR " + y/x-x")
 endif()
 
 #-----------------------------------------------------------------------------
 
 # Inform the test if the debug configuration is getting built.
 # The NDEBUG definition takes care of this for release.
-set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DPREPROCESS_DEBUG")
-set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DPREPROCESS_DEBUG")
+string(APPEND CMAKE_C_FLAGS_DEBUG " -DPREPROCESS_DEBUG")
+string(APPEND CMAKE_CXX_FLAGS_DEBUG " -DPREPROCESS_DEBUG")
 
 # Inform the test if it built from Xcode.
 if(PP_XCODE)
@@ -265,7 +265,7 @@ add_custom_target(drive COMMAND Preprocess)
 
 # Configure the header file with the desired string value.
 if(SEMICOLON)
-  set(STRING_VALUE "${STRING_VALUE};")
+  string(APPEND STRING_VALUE ";")
 endif()
 configure_file(${Preprocess_SOURCE_DIR}/preprocess.h.in
                ${Preprocess_BINARY_DIR}/preprocess.h)
diff --git a/Tests/QtAutogen/CMakeLists.txt b/Tests/QtAutogen/CMakeLists.txt
index d5aca55..c713d1c 100644
--- a/Tests/QtAutogen/CMakeLists.txt
+++ b/Tests/QtAutogen/CMakeLists.txt
@@ -44,10 +44,16 @@ else()
 
 endif()
 
+# -- RCC only
 add_executable(rcconly rcconly.cpp second_resource.qrc)
 set_property(TARGET rcconly PROPERTY AUTORCC ON)
 target_link_libraries(rcconly ${QT_QTCORE_TARGET})
 
+# -- RCC empty
+add_executable(rcc_empty rcc_empty.cpp rcc_empty_resource.qrc)
+set_property(TARGET rcc_empty PROPERTY AUTORCC ON)
+target_link_libraries(rcc_empty ${QT_QTCORE_TARGET})
+
 include_directories(${CMAKE_CURRENT_BINARY_DIR})
 
 add_definitions(-DFOO -DSomeDefine="Barx")
@@ -110,6 +116,10 @@ set_target_properties(
   AUTOMOC TRUE
 )
 
+# Test AUTOMOC and AUTORCC on source files with the same name
+# but in different subdirectories
+add_subdirectory(sameName)
+
 include(GenerateExportHeader)
 # The order is relevant here. B depends on A, and B headers depend on A
 # headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
diff --git a/Tests/QtAutogen/abc.cpp b/Tests/QtAutogen/abc.cpp
index b19c2a1..2929b92 100644
--- a/Tests/QtAutogen/abc.cpp
+++ b/Tests/QtAutogen/abc.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "abc.h"
 #include "abc_p.h"
 
diff --git a/Tests/QtAutogen/abc.h b/Tests/QtAutogen/abc.h
index dc085b1..ec5f411 100644
--- a/Tests/QtAutogen/abc.h
+++ b/Tests/QtAutogen/abc.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef ABC_H
 #define ABC_H
 
diff --git a/Tests/QtAutogen/abc_p.h b/Tests/QtAutogen/abc_p.h
index c9139b7..be98487 100644
--- a/Tests/QtAutogen/abc_p.h
+++ b/Tests/QtAutogen/abc_p.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef ABC_P_H
 #define ABC_P_H
 
diff --git a/Tests/QtAutogen/bar.cpp b/Tests/QtAutogen/bar.cpp
index 2eefd08..734bd7a 100644
--- a/Tests/QtAutogen/bar.cpp
+++ b/Tests/QtAutogen/bar.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "sub/bar.h"
 
 #include <stdio.h>
diff --git a/Tests/QtAutogen/blub.cpp b/Tests/QtAutogen/blub.cpp
index bbebf08..1c497e0 100644
--- a/Tests/QtAutogen/blub.cpp
+++ b/Tests/QtAutogen/blub.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "blub.h"
 
 #include <stdio.h>
diff --git a/Tests/QtAutogen/blub.h b/Tests/QtAutogen/blub.h
index 7097b67..ff79878 100644
--- a/Tests/QtAutogen/blub.h
+++ b/Tests/QtAutogen/blub.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef BLUB_H
 #define BLUB_H
 
diff --git a/Tests/QtAutogen/foo.cpp b/Tests/QtAutogen/foo.cpp
index 23ecc30..f665eee 100644
--- a/Tests/QtAutogen/foo.cpp
+++ b/Tests/QtAutogen/foo.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "foo.h"
 
 #include <stdio.h>
diff --git a/Tests/QtAutogen/foo.h b/Tests/QtAutogen/foo.h
index 98f6292..3e03fe6 100644
--- a/Tests/QtAutogen/foo.h
+++ b/Tests/QtAutogen/foo.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef FOO_H
 #define FOO_H
 
diff --git a/Tests/QtAutogen/rcc_empty.cpp b/Tests/QtAutogen/rcc_empty.cpp
new file mode 100644
index 0000000..3f9f9a2
--- /dev/null
+++ b/Tests/QtAutogen/rcc_empty.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_rcc_empty_resource();
+
+int main(int, char**)
+{
+  // Fails to link if the symbol is not present.
+  qInitResources_rcc_empty_resource();
+  return 0;
+}
diff --git a/Tests/QtAutogen/rcc_empty_resource.qrc b/Tests/QtAutogen/rcc_empty_resource.qrc
new file mode 100644
index 0000000..4ca9cd5
--- /dev/null
+++ b/Tests/QtAutogen/rcc_empty_resource.qrc
@@ -0,0 +1,4 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/sameName/CMakeLists.txt b/Tests/QtAutogen/sameName/CMakeLists.txt
new file mode 100644
index 0000000..ed045fb
--- /dev/null
+++ b/Tests/QtAutogen/sameName/CMakeLists.txt
@@ -0,0 +1,21 @@
+# 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
+  data.qrc
+  main.cpp
+)
+target_include_directories(sameName PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries(sameName ${QT_LIBRARIES})
+set_target_properties( sameName PROPERTIES AUTOMOC TRUE AUTORCC TRUE )
diff --git a/Tests/QtAutogen/sameName/aaa/bbb/data.qrc b/Tests/QtAutogen/sameName/aaa/bbb/data.qrc
new file mode 100644
index 0000000..0ea3537
--- /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 0000000..20d0044
--- /dev/null
+++ b/Tests/QtAutogen/sameName/aaa/bbb/item.cpp
@@ -0,0 +1,10 @@
+#include "item.hpp"
+
+namespace aaa {
+namespace bbb {
+
+void Item::go()
+{
+}
+}
+}
diff --git a/Tests/QtAutogen/sameName/aaa/bbb/item.hpp b/Tests/QtAutogen/sameName/aaa/bbb/item.hpp
new file mode 100644
index 0000000..0855043
--- /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 0000000..379af60
--- /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 0000000..95dd3b6
--- /dev/null
+++ b/Tests/QtAutogen/sameName/aaa/item.cpp
@@ -0,0 +1,8 @@
+#include "item.hpp"
+
+namespace aaa {
+
+void Item::go()
+{
+}
+}
diff --git a/Tests/QtAutogen/sameName/aaa/item.hpp b/Tests/QtAutogen/sameName/aaa/item.hpp
new file mode 100644
index 0000000..b63466f
--- /dev/null
+++ b/Tests/QtAutogen/sameName/aaa/item.hpp
@@ -0,0 +1,16 @@
+#ifndef AAA_ITEM_HPP
+#define AAA_ITEM_HPP
+
+#include <QObject>
+
+namespace aaa {
+
+class Item : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/sameName/bbb/aaa/data.qrc b/Tests/QtAutogen/sameName/bbb/aaa/data.qrc
new file mode 100644
index 0000000..da98009
--- /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 0000000..ac4b2c2
--- /dev/null
+++ b/Tests/QtAutogen/sameName/bbb/aaa/item.cpp
@@ -0,0 +1,10 @@
+#include "item.hpp"
+
+namespace bbb {
+namespace aaa {
+
+void Item::go()
+{
+}
+}
+}
diff --git a/Tests/QtAutogen/sameName/bbb/aaa/item.hpp b/Tests/QtAutogen/sameName/bbb/aaa/item.hpp
new file mode 100644
index 0000000..be07ca8
--- /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 0000000..5b080f5
--- /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 0000000..f97a143
--- /dev/null
+++ b/Tests/QtAutogen/sameName/bbb/item.cpp
@@ -0,0 +1,8 @@
+#include "item.hpp"
+
+namespace bbb {
+
+void Item::go()
+{
+}
+}
diff --git a/Tests/QtAutogen/sameName/bbb/item.hpp b/Tests/QtAutogen/sameName/bbb/item.hpp
new file mode 100644
index 0000000..5b7f985
--- /dev/null
+++ b/Tests/QtAutogen/sameName/bbb/item.hpp
@@ -0,0 +1,16 @@
+#ifndef BBB_ITEM_HPP
+#define BBB_ITEM_HPP
+
+#include <QObject>
+
+namespace bbb {
+
+class Item : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/sameName/ccc/data.qrc b/Tests/QtAutogen/sameName/ccc/data.qrc
new file mode 100644
index 0000000..f934c39
--- /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 0000000..d90b2b8
--- /dev/null
+++ b/Tests/QtAutogen/sameName/ccc/item.cpp
@@ -0,0 +1,23 @@
+#include "item.hpp"
+
+namespace ccc {
+
+void Item::go()
+{
+}
+
+class MocTest : public QObject
+{
+  Q_OBJECT;
+  Q_SLOT
+  void go();
+};
+
+void MocTest::go()
+{
+}
+}
+
+// Include own moc files
+#include "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 0000000..96fcc24
--- /dev/null
+++ b/Tests/QtAutogen/sameName/ccc/item.hpp
@@ -0,0 +1,16 @@
+#ifndef CCC_ITEM_HPP
+#define CCC_ITEM_HPP
+
+#include <QObject>
+
+namespace ccc {
+
+class Item : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/sameName/data.qrc b/Tests/QtAutogen/sameName/data.qrc
new file mode 100644
index 0000000..4ce0b4e
--- /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 0000000..e013cf3
--- /dev/null
+++ b/Tests/QtAutogen/sameName/item.cpp
@@ -0,0 +1,5 @@
+#include "item.hpp"
+
+void Item::go()
+{
+}
diff --git a/Tests/QtAutogen/sameName/item.hpp b/Tests/QtAutogen/sameName/item.hpp
new file mode 100644
index 0000000..91bba3b
--- /dev/null
+++ b/Tests/QtAutogen/sameName/item.hpp
@@ -0,0 +1,13 @@
+#ifndef ITEM_HPP
+#define ITEM_HPP
+
+#include <QObject>
+
+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 0000000..a4ffcb3
--- /dev/null
+++ b/Tests/QtAutogen/sameName/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/sub/bar.h b/Tests/QtAutogen/sub/bar.h
index c96e123..e4093f6 100644
--- a/Tests/QtAutogen/sub/bar.h
+++ b/Tests/QtAutogen/sub/bar.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef BAR_H
 #define BAR_H
 
diff --git a/Tests/QtAutogen/xyz.cpp b/Tests/QtAutogen/xyz.cpp
index c3c598e..e46c9d3 100644
--- a/Tests/QtAutogen/xyz.cpp
+++ b/Tests/QtAutogen/xyz.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "xyz.h"
 
 #include <stdio.h>
diff --git a/Tests/QtAutogen/xyz.h b/Tests/QtAutogen/xyz.h
index 1ba09a3..8b813fd 100644
--- a/Tests/QtAutogen/xyz.h
+++ b/Tests/QtAutogen/xyz.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef XYZ_H
 #define XYZ_H
 
diff --git a/Tests/QtAutogen/yaf.cpp b/Tests/QtAutogen/yaf.cpp
index 09335a9..70e26aa 100644
--- a/Tests/QtAutogen/yaf.cpp
+++ b/Tests/QtAutogen/yaf.cpp
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "yaf.h"
 #include "yaf_p.h"
 
diff --git a/Tests/QtAutogen/yaf.h b/Tests/QtAutogen/yaf.h
index 9755ca0..f271061 100644
--- a/Tests/QtAutogen/yaf.h
+++ b/Tests/QtAutogen/yaf.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef YAF_H
 #define YAF_H
 
diff --git a/Tests/QtAutogen/yaf_p.h b/Tests/QtAutogen/yaf_p.h
index cf317b8..ea5eed6 100644
--- a/Tests/QtAutogen/yaf_p.h
+++ b/Tests/QtAutogen/yaf_p.h
@@ -1,16 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2004-2011 Kitware, Inc.
-  Copyright 2011 Alexander Neundorf (neundorf at kde.org)
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef YAF_P_H
 #define YAF_P_H
 
diff --git a/Tests/RunCMake/Android/BadSYSROOT-result.txt b/Tests/RunCMake/Android/BadSYSROOT-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/BadSYSROOT-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/BadSYSROOT-stderr.txt b/Tests/RunCMake/Android/BadSYSROOT-stderr.txt
new file mode 100644
index 0000000..e17ca03
--- /dev/null
+++ b/Tests/RunCMake/Android/BadSYSROOT-stderr.txt
@@ -0,0 +1,20 @@
+^CMake Error at .*/Modules/Platform/Android-Determine.cmake:[0-9]+ \(message\):
+  The value of CMAKE_SYSROOT:
+
+    .*
+
+  does not match any of the forms:
+
+    <ndk>/platforms/android-<api>/arch-<arch>
+    <standalone-toolchain>/sysroot
+
+  where:
+
+    <ndk>  = Android NDK directory \(with forward slashes\)
+    <api>  = Android API version number \(decimal digits\)
+    <arch> = Android ARCH name \(lower case\)
+    <standalone-toolchain> = Path to standalone toolchain prefix
+
+Call Stack \(most recent call first\):
+  .*/Modules/CMakeDetermineSystem.cmake:[0-9]+ \(include\)
+  CMakeLists.txt:2 \(project\)$
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/BadSYSROOT.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/BadSYSROOT.cmake
diff --git a/Tests/RunCMake/Android/CMakeLists.txt b/Tests/RunCMake/Android/CMakeLists.txt
new file mode 100644
index 0000000..dc92486
--- /dev/null
+++ b/Tests/RunCMake/Android/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/Android/RunCMakeTest.cmake b/Tests/RunCMake/Android/RunCMakeTest.cmake
new file mode 100644
index 0000000..39b77cd
--- /dev/null
+++ b/Tests/RunCMake/Android/RunCMakeTest.cmake
@@ -0,0 +1,218 @@
+cmake_minimum_required(VERSION 3.6)
+
+include(RunCMake)
+foreach(v TEST_ANDROID_NDK TEST_ANDROID_STANDALONE_TOOLCHAIN)
+  string(REPLACE "|" ";" ${v} "${${v}}")
+endforeach()
+
+function(run_Android case)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    ${RunCMake_TEST_OPTIONS}
+    ${ARGN}
+    )
+
+  # Use a single build tree for a few tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${case}-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  run_cmake(${case})
+  run_cmake_command(${case}-build ${CMAKE_COMMAND} --build .)
+endfunction()
+
+set(RunCMake_TEST_OPTIONS
+  -DCMAKE_SYSTEM_NAME=Android
+  -DCMAKE_SYSROOT=${CMAKE_CURRENT_SOURCE_DIR}
+  )
+run_cmake(BadSYSROOT)
+unset(RunCMake_TEST_OPTIONS)
+
+foreach(ndk IN LISTS TEST_ANDROID_NDK)
+  # Load available toolchain versions and abis.
+  file(GLOB _config_mks
+    "${ndk}/build/core/toolchains/*/config.mk"
+    "${ndk}/toolchains/*/config.mk"
+    )
+  set(_versions "")
+  set(_latest_gcc 0)
+  set(_latest_clang "")
+  set(_latest_clang_vers 0)
+  foreach(config_mk IN LISTS _config_mks)
+    file(STRINGS "${config_mk}" _abis REGEX "^TOOLCHAIN_ABIS +:= +[^ ].*( |$)")
+    if(_abis AND "${config_mk}" MATCHES [[-((clang)?([0-9]\.[0-9]|))/config\.mk$]])
+      set(_version "${CMAKE_MATCH_1}")
+      set(_is_clang "${CMAKE_MATCH_2}")
+      set(_cur_vers "${CMAKE_MATCH_3}")
+      if(_is_clang)
+        if(_latest_clang_vers STREQUAL "")
+          # already the latest possible
+        elseif(_cur_vers STREQUAL "" OR _cur_vers VERSION_GREATER _latest_clang_vers)
+          set(_latest_clang_vers "${_cur_vers}")
+          set(_latest_clang "${_version}")
+        endif()
+      else()
+        if(_version VERSION_GREATER _latest_gcc)
+          set(_latest_gcc ${_version})
+        endif()
+      endif()
+      list(APPEND _versions "${_version}")
+      string(REGEX MATCHALL "[a-z][a-z0-9_-]+" _abis "${_abis}")
+      list(APPEND _abis_${_version} ${_abis})
+    endif()
+  endforeach()
+  set(_abis_ ${_abis_${_latest_gcc}})
+  set(_abis_clang ${_abis_${_latest_clang}})
+  if(_versions MATCHES "clang")
+    set(_versions "clang" ${_versions})
+  endif()
+  list(REMOVE_DUPLICATES _versions)
+  list(SORT _versions)
+  set(_versions ";${_versions}")
+  foreach(vers IN LISTS _versions)
+    list(REMOVE_DUPLICATES _abis_${vers})
+  endforeach()
+
+  # Test failure cases.
+  message(STATUS "ndk='${ndk}'")
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_ARCH_ABI=badabi
+    )
+  run_cmake(ndk-badabi)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_ARCH_ABI=x86
+    -DCMAKE_ANDROID_ARM_MODE=0
+    )
+  run_cmake(ndk-badarm)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_ARM_NEON=0
+    )
+  run_cmake(ndk-badneon)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=badver
+    )
+  run_cmake(ndk-badver)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=1.0
+    )
+  run_cmake(ndk-badvernum)
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_ANDROID_NDK=${ndk}
+    -DCMAKE_ANDROID_STL_TYPE=badstl
+    )
+  run_cmake(ndk-badstl)
+  unset(RunCMake_TEST_OPTIONS)
+
+  # Find a sysroot to test.
+  file(GLOB _sysroots "${ndk}/platforms/android-[0-9][0-9]/arch-arm")
+  if(_sysroots)
+    list(GET _sysroots 0 _sysroot)
+    set(RunCMake_TEST_OPTIONS
+      -DCMAKE_SYSTEM_NAME=Android
+      -DCMAKE_SYSROOT=${_sysroot}
+      )
+    run_cmake(ndk-sysroot-armeabi)
+    unset(RunCMake_TEST_OPTIONS)
+  endif()
+
+  # Find available STLs.
+  set(stl_types
+    none
+    system
+    gnustl_static
+    gnustl_shared
+    )
+
+  if(IS_DIRECTORY "${ndk}/sources/cxx-stl/gabi++/libs")
+    list(APPEND stl_types gabi++_static gabi++_shared)
+  endif()
+  if(IS_DIRECTORY "${ndk}/sources/cxx-stl/stlport/libs")
+    list(APPEND stl_types stlport_static stlport_shared)
+  endif()
+  if(IS_DIRECTORY "${ndk}/sources/cxx-stl/llvm-libc++/libs")
+    list(APPEND stl_types c++_static c++_shared)
+  endif()
+
+  # List possible ABIs.
+  set(abi_names
+    armeabi
+    armeabi-v6
+    armeabi-v7a
+    arm64-v8a
+    mips
+    mips64
+    x86
+    x86_64
+    )
+
+  # Test all combinations.
+  foreach(vers IN LISTS _versions)
+    foreach(stl IN LISTS stl_types)
+      foreach(config Release Debug)
+        # Test this combination for all available abis.
+        message(STATUS "ndk='${ndk}' vers='${vers}' stl='${stl}' config='${config}'")
+        set(RunCMake_TEST_OPTIONS
+          -DCMAKE_ANDROID_NDK=${ndk}
+          -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=${vers}
+          -DCMAKE_ANDROID_STL_TYPE=${stl}
+          -DCMAKE_BUILD_TYPE=${config}
+          )
+        foreach(abi IN LISTS abi_names)
+          # Skip ABIs not supported by this compiler.
+          if(NOT ";${_abis_${vers}};" MATCHES ";${abi};")
+            continue()
+          endif()
+
+          # Skip combinations that seem to be broken.
+          if("${stl};${abi}" MATCHES [[^c\+\+_static;armeabi]])
+            continue()
+          endif()
+
+          # Run the tests for this combination.
+          if("${abi}" STREQUAL "armeabi")
+            run_Android(ndk-armeabi-thumb) # default: -DCMAKE_ANDROID_ARCH_ABI=armeabi -DCMAKE_ANDROID_ARM_MODE=0
+            run_Android(ndk-armeabi-arm -DCMAKE_ANDROID_ARM_MODE=1) # default: -DCMAKE_ANDROID_ARCH_ABI=armeabi
+          else()
+            run_Android(ndk-${abi} -DCMAKE_ANDROID_ARCH_ABI=${abi})
+            if("${abi}" STREQUAL "armeabi-v7a")
+              run_Android(ndk-${abi}-neon -DCMAKE_ANDROID_ARCH_ABI=${abi} -DCMAKE_ANDROID_ARM_NEON=1)
+            endif()
+          endif()
+        endforeach()
+        unset(RunCMake_TEST_OPTIONS)
+      endforeach()
+    endforeach()
+  endforeach()
+endforeach()
+
+foreach(toolchain IN LISTS TEST_ANDROID_STANDALONE_TOOLCHAIN)
+  message(STATUS "toolchain='${toolchain}'")
+
+  set(RunCMake_TEST_OPTIONS
+    -DCMAKE_SYSTEM_NAME=Android
+    -DCMAKE_SYSROOT=${toolchain}/sysroot
+    )
+  run_cmake(standalone-sysroot)
+  unset(RunCMake_TEST_OPTIONS)
+
+  foreach(config Release Debug)
+    message(STATUS "toolchain='${toolchain}' config='${config}'")
+    set(RunCMake_TEST_OPTIONS
+      -DCMAKE_ANDROID_STANDALONE_TOOLCHAIN=${toolchain}
+      -DCMAKE_BUILD_TYPE=${config}
+      )
+    run_Android(standalone)
+    unset(RunCMake_TEST_OPTIONS)
+  endforeach()
+endforeach()
diff --git a/Tests/RunCMake/Android/android.c b/Tests/RunCMake/Android/android.c
new file mode 100644
index 0000000..30e8574
--- /dev/null
+++ b/Tests/RunCMake/Android/android.c
@@ -0,0 +1,6 @@
+#include "android.h"
+
+int main(void)
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/Android/android.cxx b/Tests/RunCMake/Android/android.cxx
new file mode 100644
index 0000000..2dee8f9
--- /dev/null
+++ b/Tests/RunCMake/Android/android.cxx
@@ -0,0 +1,48 @@
+#include "android.h"
+
+#ifndef STL_NONE
+#include <cmath>
+#include <cstdio>
+#ifndef STL_SYSTEM
+#include <exception>
+#include <typeinfo>
+#ifndef STL_STLPORT
+#include <cxxabi.h>
+#endif
+#ifndef STL_GABI
+#include <iostream>
+#include <string>
+#endif
+#endif
+#endif
+
+int main()
+{
+#if !defined(STL_NONE)
+  // Require -lm implied by linking as C++.
+  std::printf("%p\n", static_cast<double (*)(double)>(&std::sin));
+#endif
+#if defined(STL_NONE)
+  return 0;
+#elif defined(STL_SYSTEM)
+  return 0;
+#else
+  try {
+    delete (new int);
+  } catch (std::exception const& e) {
+#if defined(STL_GABI)
+    e.what();
+    typeid(e).name();
+#else
+    std::cerr << e.what() << std::endl;
+    std::cerr << typeid(e).name() << std::endl;
+#endif
+  }
+#if defined(STL_GABI)
+  return 0;
+#else
+  std::string s;
+  return static_cast<int>(s.size());
+#endif
+#endif
+}
diff --git a/Tests/RunCMake/Android/android.h b/Tests/RunCMake/Android/android.h
new file mode 100644
index 0000000..a5fd67e
--- /dev/null
+++ b/Tests/RunCMake/Android/android.h
@@ -0,0 +1,103 @@
+#ifndef __ANDROID__
+#error "__ANDROID__ not defined"
+#endif
+
+#include <android/api-level.h>
+
+#if API_LEVEL != __ANDROID_API__
+#error "API levels do not match"
+#endif
+
+#ifdef COMPILER_IS_CLANG
+#ifndef __clang__
+#error "COMPILER_IS_CLANG but __clang__ is not defined"
+#endif
+#else
+#ifdef __clang__
+#error "!COMPILER_IS_CLANG but __clang__ is defined"
+#endif
+#endif
+
+#ifdef ARM_MODE
+#if ARM_MODE == 1 && defined(__thumb__)
+#error "ARM_MODE==1 but __thumb__ is defined"
+#elif ARM_MODE == 0 && !defined(__thumb__)
+#error "ARM_MODE==0 but __thumb__ is not defined"
+#endif
+#endif
+
+#ifdef ARM_NEON
+#if ARM_NEON == 0 && defined(__ARM_NEON__)
+#error "ARM_NEON==0 but __ARM_NEON__ is defined"
+#elif ARM_NEON == 1 && !defined(__ARM_NEON__)
+#error "ARM_NEON==1 but __ARM_NEON__ is not defined"
+#endif
+#endif
+
+#ifdef ABI_armeabi
+#ifndef __ARM_EABI__
+#error "ABI_armeabi: __ARM_EABI__ not defined"
+#endif
+#if __ARM_ARCH != 5
+#error "ABI_armeabi: __ARM_ARCH is not 5"
+#endif
+#endif
+
+#ifdef ABI_armeabi_v6
+#ifndef __ARM_EABI__
+#error "ABI_armeabi_v6: __ARM_EABI__ not defined"
+#endif
+#if __ARM_ARCH != 6
+#error "ABI_armeabi_v6: __ARM_ARCH is not 6"
+#endif
+#endif
+
+#ifdef ABI_armeabi_v7a
+#ifndef __ARM_EABI__
+#error "ABI_armeabi_v7a: __ARM_EABI__ not defined"
+#endif
+#if __ARM_ARCH != 7
+#error "ABI_armeabi_v7a: __ARM_ARCH is not 7"
+#endif
+#endif
+
+#ifdef ABI_arm64_v8a
+#ifdef __ARM_EABI__
+#error "ABI_arm64_v8a: __ARM_EABI__ defined"
+#endif
+#ifndef __aarch64__
+#error "ABI_arm64_v8a: __aarch64__ not defined"
+#endif
+#endif
+
+#ifdef ABI_mips
+#if __mips != 32
+#error "ABI_mips: __mips != 32"
+#endif
+#ifndef _ABIO32
+#error "ABI_mips: _ABIO32 not defined"
+#endif
+#endif
+
+#ifdef ABI_mips64
+#if __mips != 64
+#error "ABI_mips64: __mips != 64"
+#endif
+#ifndef _ABI64
+#error "ABI_mips: _ABI64 not defined"
+#endif
+#endif
+
+#ifdef ABI_x86
+#ifndef __i686__
+#error "ABI_x86: __i686__ not defined"
+#endif
+#endif
+
+#ifdef ABI_x86_64
+#ifndef __x86_64__
+#error "ABI_x86_64: __x86_64__ not defined"
+#endif
+#endif
+
+#include <stddef.h>
diff --git a/Tests/RunCMake/Android/common.cmake b/Tests/RunCMake/Android/common.cmake
new file mode 100644
index 0000000..d803c98
--- /dev/null
+++ b/Tests/RunCMake/Android/common.cmake
@@ -0,0 +1,62 @@
+enable_language(C)
+enable_language(CXX)
+
+if(NOT ANDROID)
+  message(SEND_ERROR "CMake variable 'ANDROID' is not set to a true value.")
+endif()
+
+foreach(f
+    "${CMAKE_C_ANDROID_TOOLCHAIN_PREFIX}gcc${CMAKE_C_ANDROID_TOOLCHAIN_SUFFIX}"
+    "${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}g++${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}"
+    "${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}cpp${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}"
+    "${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}ar${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}"
+    "${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}ld${CMAKE_CXX_ANDROID_TOOLCHAIN_SUFFIX}"
+    )
+  if(NOT EXISTS "${f}")
+    message(SEND_ERROR "Expected file does not exist:\n \"${f}\"")
+  endif()
+endforeach()
+
+string(APPEND CMAKE_C_FLAGS " -Werror -Wno-attributes")
+string(APPEND CMAKE_CXX_FLAGS " -Werror -Wno-attributes")
+string(APPEND CMAKE_EXE_LINKER_FLAGS " -Wl,-no-undefined")
+
+if(CMAKE_ANDROID_NDK)
+  if(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION MATCHES "clang")
+    add_definitions(-DCOMPILER_IS_CLANG)
+  endif()
+elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
+  execute_process(
+    COMMAND ${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/clang --version
+    OUTPUT_VARIABLE _out
+    ERROR_VARIABLE _err
+    RESULT_VARIABLE _res
+    )
+  if(_res EQUAL 0)
+    add_definitions(-DCOMPILER_IS_CLANG)
+  endif()
+endif()
+
+if(CMAKE_ANDROID_STL_TYPE STREQUAL "none")
+  add_definitions(-DSTL_NONE)
+elseif(CMAKE_ANDROID_STL_TYPE STREQUAL "system")
+  add_definitions(-DSTL_SYSTEM)
+elseif(CMAKE_ANDROID_STL_TYPE MATCHES [[^gabi\+\+]])
+  add_definitions(-DSTL_GABI)
+elseif(CMAKE_ANDROID_STL_TYPE MATCHES [[^stlport]])
+  add_definitions(-DSTL_STLPORT)
+endif()
+
+string(REPLACE "-" "_" abi "${CMAKE_ANDROID_ARCH_ABI}")
+add_definitions(-DABI_${abi})
+add_definitions(-DAPI_LEVEL=${CMAKE_SYSTEM_VERSION})
+if(CMAKE_ANDROID_ARCH_ABI MATCHES "^armeabi")
+  add_definitions(-DARM_MODE=${CMAKE_ANDROID_ARM_MODE})
+  message(STATUS "CMAKE_ANDROID_ARM_MODE=${CMAKE_ANDROID_ARM_MODE}")
+endif()
+if(CMAKE_ANDROID_ARCH_ABI STREQUAL "armeabi-v7a")
+  add_definitions(-DARM_NEON=${CMAKE_ANDROID_ARM_NEON})
+  message(STATUS "CMAKE_ANDROID_ARM_NEON=${CMAKE_ANDROID_ARM_NEON}")
+endif()
+add_executable(android_c android.c)
+add_executable(android_cxx android.cxx)
diff --git a/Tests/RunCMake/Android/ndk-arm64-v8a-stdout.txt b/Tests/RunCMake/Android/ndk-arm64-v8a-stdout.txt
new file mode 100644
index 0000000..8d0bdc2
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-arm64-v8a-stdout.txt
@@ -0,0 +1,2 @@
+-- Android: Targeting API '[0-9]+' with architecture 'arm64', ABI 'arm64-v8a', and processor 'aarch64'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
diff --git a/Tests/RunCMake/Android/ndk-arm64-v8a.cmake b/Tests/RunCMake/Android/ndk-arm64-v8a.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-arm64-v8a.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-armeabi-arm-stdout.txt b/Tests/RunCMake/Android/ndk-armeabi-arm-stdout.txt
new file mode 100644
index 0000000..3741da3
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-arm-stdout.txt
@@ -0,0 +1,3 @@
+-- Android: Targeting API '[0-9]+' with architecture 'arm', ABI 'armeabi', and processor 'armv5te'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
+.*-- CMAKE_ANDROID_ARM_MODE=1
diff --git a/Tests/RunCMake/Android/ndk-armeabi-arm.cmake b/Tests/RunCMake/Android/ndk-armeabi-arm.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-arm.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-armeabi-thumb-stdout.txt b/Tests/RunCMake/Android/ndk-armeabi-thumb-stdout.txt
new file mode 100644
index 0000000..ce0dea2
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-thumb-stdout.txt
@@ -0,0 +1,3 @@
+-- Android: Targeting API '[0-9]+' with architecture 'arm', ABI 'armeabi', and processor 'armv5te'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
+.*-- CMAKE_ANDROID_ARM_MODE=0
diff --git a/Tests/RunCMake/Android/ndk-armeabi-thumb.cmake b/Tests/RunCMake/Android/ndk-armeabi-thumb.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-thumb.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-armeabi-v7a-neon-stdout.txt b/Tests/RunCMake/Android/ndk-armeabi-v7a-neon-stdout.txt
new file mode 100644
index 0000000..ac2bfd5
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-v7a-neon-stdout.txt
@@ -0,0 +1,3 @@
+-- Android: Targeting API '[0-9]+' with architecture 'arm', ABI 'armeabi-v7a', and processor 'armv7-a'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
+.*-- CMAKE_ANDROID_ARM_NEON=1
diff --git a/Tests/RunCMake/Android/ndk-armeabi-v7a-neon.cmake b/Tests/RunCMake/Android/ndk-armeabi-v7a-neon.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-v7a-neon.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-armeabi-v7a-stdout.txt b/Tests/RunCMake/Android/ndk-armeabi-v7a-stdout.txt
new file mode 100644
index 0000000..0edb4f7
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-v7a-stdout.txt
@@ -0,0 +1,3 @@
+-- Android: Targeting API '[0-9]+' with architecture 'arm', ABI 'armeabi-v7a', and processor 'armv7-a'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
+.*-- CMAKE_ANDROID_ARM_NEON=0
diff --git a/Tests/RunCMake/Android/ndk-armeabi-v7a.cmake b/Tests/RunCMake/Android/ndk-armeabi-v7a.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-armeabi-v7a.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-badabi-result.txt b/Tests/RunCMake/Android/ndk-badabi-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badabi-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badabi-stderr.txt b/Tests/RunCMake/Android/ndk-badabi-stderr.txt
new file mode 100644
index 0000000..c089235
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badabi-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at .*/Modules/Platform/Android-Determine.cmake:[0-9]+ \(message\):
+  Android: Unknown ABI CMAKE_ANDROID_ARCH_ABI='badabi'.
+Call Stack \(most recent call first\):
+  .*/Modules/CMakeDetermineSystem.cmake:[0-9]+ \(include\)
+  CMakeLists.txt:[0-9]+ \(project\)$
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/ndk-badabi.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/ndk-badabi.cmake
diff --git a/Tests/RunCMake/Android/ndk-badarm-result.txt b/Tests/RunCMake/Android/ndk-badarm-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badarm-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badarm-stderr.txt b/Tests/RunCMake/Android/ndk-badarm-stderr.txt
new file mode 100644
index 0000000..f62bfc4
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badarm-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at .*/Modules/Platform/Android-Determine.cmake:[0-9]+ \(message\):
+  Android: CMAKE_ANDROID_ARM_MODE is set but is valid only for 'armeabi'
+  architectures.
+Call Stack \(most recent call first\):
+  .*/Modules/CMakeDetermineSystem.cmake:[0-9]+ \(include\)
+  CMakeLists.txt:[0-9]+ \(project\)$
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/ndk-badarm.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/ndk-badarm.cmake
diff --git a/Tests/RunCMake/Android/ndk-badneon-result.txt b/Tests/RunCMake/Android/ndk-badneon-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badneon-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badneon-stderr.txt b/Tests/RunCMake/Android/ndk-badneon-stderr.txt
new file mode 100644
index 0000000..1f0bf00
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badneon-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at .*/Modules/Platform/Android-Determine.cmake:[0-9]+ \(message\):
+  Android: CMAKE_ANDROID_ARM_NEON is set but is valid only for 'armeabi-v7a'
+  architecture.
+Call Stack \(most recent call first\):
+  .*/Modules/CMakeDetermineSystem.cmake:[0-9]+ \(include\)
+  CMakeLists.txt:[0-9]+ \(project\)$
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/ndk-badneon.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/ndk-badneon.cmake
diff --git a/Tests/RunCMake/Android/ndk-badstl-result.txt b/Tests/RunCMake/Android/ndk-badstl-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badstl-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badstl-stderr.txt b/Tests/RunCMake/Android/ndk-badstl-stderr.txt
new file mode 100644
index 0000000..c61824e
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badstl-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at .*/Modules/Platform/Android-Common.cmake:[0-9]+ \(message\):
+  The CMAKE_ANDROID_STL_TYPE 'badstl' is not one of the allowed values:
+
+    .*
+
+Call Stack \(most recent call first\):
+.*
+  ndk-badstl.cmake:1 \(enable_language\)
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Android/ndk-badstl.cmake b/Tests/RunCMake/Android/ndk-badstl.cmake
new file mode 100644
index 0000000..fa2fc91
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badstl.cmake
@@ -0,0 +1 @@
+enable_language(CXX)
diff --git a/Tests/RunCMake/Android/ndk-badver-result.txt b/Tests/RunCMake/Android/ndk-badver-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badver-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badver-stderr.txt b/Tests/RunCMake/Android/ndk-badver-stderr.txt
new file mode 100644
index 0000000..df2c5e6
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badver-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Error at .*/Modules/Platform/Android/Determine-Compiler-NDK.cmake:[0-9]+ \(message\):
+  Android: The CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION value 'badver' is not one
+  of the allowed forms:
+
+    <major>.<minor>       = GCC of specified version
+    clang<major>.<minor>  = Clang of specified version
+    clang                 = Clang of most recent available version
+
+Call Stack \(most recent call first\):
+.*
+  ndk-badver.cmake:1 \(enable_language\)
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Android/ndk-badver.cmake b/Tests/RunCMake/Android/ndk-badver.cmake
new file mode 100644
index 0000000..c00af08
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badver.cmake
@@ -0,0 +1 @@
+enable_language(C)
diff --git a/Tests/RunCMake/Android/ndk-badvernum-result.txt b/Tests/RunCMake/Android/ndk-badvernum-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badvernum-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Android/ndk-badvernum-stderr.txt b/Tests/RunCMake/Android/ndk-badvernum-stderr.txt
new file mode 100644
index 0000000..25bbaf9
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badvernum-stderr.txt
@@ -0,0 +1,13 @@
+^CMake Error at .*/Modules/Platform/Android/Determine-Compiler-NDK.cmake:[0-9]+ \(message\):
+  Android: No toolchain for ABI 'armeabi' found in the NDK:
+
+    .*
+
+  of the version specified by CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION:
+
+    1\.0
+
+Call Stack \(most recent call first\):
+.*
+  ndk-badvernum.cmake:1 \(enable_language\)
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Android/ndk-badvernum.cmake b/Tests/RunCMake/Android/ndk-badvernum.cmake
new file mode 100644
index 0000000..c00af08
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-badvernum.cmake
@@ -0,0 +1 @@
+enable_language(C)
diff --git a/Tests/RunCMake/Android/ndk-mips-stdout.txt b/Tests/RunCMake/Android/ndk-mips-stdout.txt
new file mode 100644
index 0000000..c744683
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-mips-stdout.txt
@@ -0,0 +1,2 @@
+-- Android: Targeting API '[0-9]+' with architecture 'mips', ABI 'mips', and processor 'mips'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
diff --git a/Tests/RunCMake/Android/ndk-mips.cmake b/Tests/RunCMake/Android/ndk-mips.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-mips.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-mips64-stdout.txt b/Tests/RunCMake/Android/ndk-mips64-stdout.txt
new file mode 100644
index 0000000..839ddfd
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-mips64-stdout.txt
@@ -0,0 +1,2 @@
+-- Android: Targeting API '[0-9]+' with architecture 'mips64', ABI 'mips64', and processor 'mips64'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
diff --git a/Tests/RunCMake/Android/ndk-mips64.cmake b/Tests/RunCMake/Android/ndk-mips64.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-mips64.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-sysroot-armeabi-stdout.txt b/Tests/RunCMake/Android/ndk-sysroot-armeabi-stdout.txt
new file mode 100644
index 0000000..d309e72
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-sysroot-armeabi-stdout.txt
@@ -0,0 +1 @@
+-- Android: Targeting API '[0-9][0-9]' with architecture 'arm', ABI 'armeabi', and processor 'armv5te'
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/ndk-sysroot-armeabi.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/ndk-sysroot-armeabi.cmake
diff --git a/Tests/RunCMake/Android/ndk-x86-stdout.txt b/Tests/RunCMake/Android/ndk-x86-stdout.txt
new file mode 100644
index 0000000..2dbb2f0
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-x86-stdout.txt
@@ -0,0 +1,2 @@
+-- Android: Targeting API '[0-9]+' with architecture 'x86', ABI 'x86', and processor 'i686'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
diff --git a/Tests/RunCMake/Android/ndk-x86.cmake b/Tests/RunCMake/Android/ndk-x86.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-x86.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/ndk-x86_64-stdout.txt b/Tests/RunCMake/Android/ndk-x86_64-stdout.txt
new file mode 100644
index 0000000..a7ae91d
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-x86_64-stdout.txt
@@ -0,0 +1,2 @@
+-- Android: Targeting API '[0-9]+' with architecture 'x86_64', ABI 'x86_64', and processor 'x86_64'
+-- Android: Selected (Clang toolchain '[^']+' with )?GCC toolchain '[^']+'
diff --git a/Tests/RunCMake/Android/ndk-x86_64.cmake b/Tests/RunCMake/Android/ndk-x86_64.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/ndk-x86_64.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/Android/standalone-stdout.txt b/Tests/RunCMake/Android/standalone-stdout.txt
new file mode 100644
index 0000000..20b095c
--- /dev/null
+++ b/Tests/RunCMake/Android/standalone-stdout.txt
@@ -0,0 +1 @@
+-- Android: Targeting API '[0-9]+' with architecture '[a-z0-9_-]+', ABI '[a-z0-9_-]+', and processor '[a-z0-9_-]+'
diff --git a/Tests/RunCMake/Android/standalone-sysroot-stdout.txt b/Tests/RunCMake/Android/standalone-sysroot-stdout.txt
new file mode 100644
index 0000000..20b095c
--- /dev/null
+++ b/Tests/RunCMake/Android/standalone-sysroot-stdout.txt
@@ -0,0 +1 @@
+-- Android: Targeting API '[0-9]+' with architecture '[a-z0-9_-]+', ABI '[a-z0-9_-]+', and processor '[a-z0-9_-]+'
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/Android/standalone-sysroot.cmake
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/Android/standalone-sysroot.cmake
diff --git a/Tests/RunCMake/Android/standalone.cmake b/Tests/RunCMake/Android/standalone.cmake
new file mode 100644
index 0000000..a3185fe
--- /dev/null
+++ b/Tests/RunCMake/Android/standalone.cmake
@@ -0,0 +1 @@
+include(common.cmake)
diff --git a/Tests/RunCMake/AndroidMK/AndroidMK-check.cmake b/Tests/RunCMake/AndroidMK/AndroidMK-check.cmake
new file mode 100644
index 0000000..691e326
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/AndroidMK-check.cmake
@@ -0,0 +1,30 @@
+# This file does a regex file compare on the generated
+# Android.mk files from the AndroidMK test
+
+macro(compare_file_to_expected file expected_file)
+  file(READ "${file}" ANDROID_MK)
+  # clean up new lines
+  string(REGEX REPLACE "\r\n" "\n" ANDROID_MK "${ANDROID_MK}")
+  string(REGEX REPLACE "\n+$" "" ANDROID_MK "${ANDROID_MK}")
+  # read in the expected regex file
+  file(READ "${expected_file}" expected)
+  # clean up new lines
+  string(REGEX REPLACE "\r\n" "\n" expected "${expected}")
+  string(REGEX REPLACE "\n+$" "" expected "${expected}")
+  # compare the file to the expected regex and if there is not a match
+  # put an error message in RunCMake_TEST_FAILED
+  if(NOT "${ANDROID_MK}" MATCHES "${expected}")
+    set(RunCMake_TEST_FAILED
+      "${file} does not match ${expected_file}:
+
+Android.mk contents = [\n${ANDROID_MK}\n]
+Expected = [\n${expected}\n]")
+  endif()
+endmacro()
+
+compare_file_to_expected(
+"${RunCMake_BINARY_DIR}/AndroidMK-build/Android.mk"
+"${RunCMake_TEST_SOURCE_DIR}/expectedBuildAndroidMK.txt")
+compare_file_to_expected(
+"${RunCMake_BINARY_DIR}/AndroidMK-build/CMakeFiles/Export/share/ndk-modules/Android.mk"
+"${RunCMake_TEST_SOURCE_DIR}/expectedInstallAndroidMK.txt")
diff --git a/Tests/RunCMake/AndroidMK/AndroidMK.cmake b/Tests/RunCMake/AndroidMK/AndroidMK.cmake
new file mode 100644
index 0000000..2596e8c
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/AndroidMK.cmake
@@ -0,0 +1,11 @@
+project(build)
+set(CMAKE_BUILD_TYPE Debug)
+add_library(foo foo.cxx)
+add_library(car foo.cxx)
+add_library(bar bar.c)
+add_library(dog  foo.cxx)
+target_link_libraries(foo car bar dog debug -lm)
+export(TARGETS bar dog car foo  ANDROID_MK
+  ${build_BINARY_DIR}/Android.mk)
+install(TARGETS bar dog car foo DESTINATION lib EXPORT myexp)
+install(EXPORT_ANDROID_MK myexp DESTINATION share/ndk-modules)
diff --git a/Tests/RunCMake/AndroidMK/CMakeLists.txt b/Tests/RunCMake/AndroidMK/CMakeLists.txt
new file mode 100644
index 0000000..576787a
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.5)
+project(${RunCMake_TEST} NONE) # or languages needed
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/AndroidMK/RunCMakeTest.cmake b/Tests/RunCMake/AndroidMK/RunCMakeTest.cmake
new file mode 100644
index 0000000..786d45b
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/RunCMakeTest.cmake
@@ -0,0 +1,2 @@
+include(RunCMake)
+run_cmake(AndroidMK)
diff --git a/Tests/RunCMake/AndroidMK/bar.c b/Tests/RunCMake/AndroidMK/bar.c
new file mode 100644
index 0000000..e1f4df6
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/bar.c
@@ -0,0 +1,3 @@
+void bar(void)
+{
+}
diff --git a/Tests/RunCMake/AndroidMK/expectedBuildAndroidMK.txt b/Tests/RunCMake/AndroidMK/expectedBuildAndroidMK.txt
new file mode 100644
index 0000000..bbf67a5
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/expectedBuildAndroidMK.txt
@@ -0,0 +1,26 @@
+LOCAL_PATH.*call my-dir.*
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*bar
+LOCAL_SRC_FILES.*bar.*
+include.*PREBUILT_STATIC_LIBRARY.*
+.*
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*dog
+LOCAL_SRC_FILES.*.*dog.*
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
+.*
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*car
+LOCAL_SRC_FILES.*.*car.*
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
+.*
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*foo
+LOCAL_SRC_FILES.*.*foo.*
+LOCAL_CPP_FEATURES.*rtti exceptions
+LOCAL_STATIC_LIBRARIES.*car bar dog
+LOCAL_EXPORT_LDLIBS := -lm
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
diff --git a/Tests/RunCMake/AndroidMK/expectedInstallAndroidMK.txt b/Tests/RunCMake/AndroidMK/expectedInstallAndroidMK.txt
new file mode 100644
index 0000000..3515fb9
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/expectedInstallAndroidMK.txt
@@ -0,0 +1,28 @@
+LOCAL_PATH.*call my-dir.*
+_IMPORT_PREFIX.*LOCAL_PATH./../..
+
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*bar
+LOCAL_SRC_FILES.*_IMPORT_PREFIX./lib.*bar.*
+include.*PREBUILT_STATIC_LIBRARY.*
+
+include.*CLEAR_VARS.
+LOCAL_MODULE.*dog
+LOCAL_SRC_FILES.*_IMPORT_PREFIX./lib.*dog.*
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
+
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*car
+LOCAL_SRC_FILES.*_IMPORT_PREFIX./lib.*car.*
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
+
+include.*CLEAR_VARS.*
+LOCAL_MODULE.*foo
+LOCAL_SRC_FILES.*_IMPORT_PREFIX\)/lib.*foo.*
+LOCAL_CPP_FEATURES.*rtti exceptions
+LOCAL_STATIC_LIBRARIES.*car bar dog
+LOCAL_EXPORT_LDLIBS := -lm
+LOCAL_HAS_CPP := true
+include.*PREBUILT_STATIC_LIBRARY.*
diff --git a/Tests/RunCMake/AndroidMK/foo.cxx b/Tests/RunCMake/AndroidMK/foo.cxx
new file mode 100644
index 0000000..3695dc9
--- /dev/null
+++ b/Tests/RunCMake/AndroidMK/foo.cxx
@@ -0,0 +1,3 @@
+void foo()
+{
+}
diff --git a/Tests/RunCMake/AndroidTestUtilities/CMakeLists.txt b/Tests/RunCMake/AndroidTestUtilities/CMakeLists.txt
new file mode 100644
index 0000000..dc92486
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/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/AndroidTestUtilities/RunCMakeTest.cmake b/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake
new file mode 100644
index 0000000..f0ae24b
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake
@@ -0,0 +1,20 @@
+include(RunCMake)
+
+function(run_ATU case target)
+  # Use a single build tree for a few tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${case}-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  if(target)
+    set(build_args --target ${target})
+  else()
+    set(build_args)
+  endif()
+  run_cmake(${case})
+  run_cmake_command(${case}Build ${CMAKE_COMMAND} --build . --config Debug ${build_args})
+endfunction()
+
+run_ATU(SetupTest1 "")
+run_ATU(SetupTest2 "tests")
+run_ATU(SetupTest3 "tests")
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest1.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest1.cmake
new file mode 100644
index 0000000..1c9098b
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest1.cmake
@@ -0,0 +1,17 @@
+enable_testing()
+include(AndroidTestUtilities)
+
+find_program(adb_executable adb)
+
+set(ExternalData_URL_TEMPLATES
+  "https://data.kitware.com/api/v1/file/hashsum/%(algo)/%(hash)/download"
+  )
+
+set(test_files "data/a.txt")
+
+set(ANDROID 1)
+
+android_add_test_data(setup_test
+  FILES ${test_files}
+  DEVICE_TEST_DIR "/data/local/tests/example1"
+  DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA")
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest1Build-check.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest1Build-check.cmake
new file mode 100644
index 0000000..ef7569d
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest1Build-check.cmake
@@ -0,0 +1,5 @@
+include(${CMAKE_CURRENT_LIST_DIR}/check.cmake)
+compare_build_to_expected(FILES
+  "data/a.txt"
+  )
+check_for_setup_test()
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest2.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest2.cmake
new file mode 100644
index 0000000..cf4c764
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest2.cmake
@@ -0,0 +1,30 @@
+enable_testing()
+include(AndroidTestUtilities)
+
+add_custom_target(tests)
+find_program(adb_executable adb)
+
+set(ExternalData_URL_TEMPLATES
+  "https://data.kitware.com/api/v1/file/hashsum/%(algo)/%(hash)/download"
+  )
+set(test_files
+  "data/a.txt"
+  "data/subfolder/b.txt"
+  "data/subfolder/protobuffer.p"
+  )
+
+set(test_libs "data/subfolder/exampleLib.txt")
+
+set(ANDROID 1)
+
+android_add_test_data(setup_test
+  FILES ${test_files}
+  LIBS ${test_libs}
+  DEVICE_TEST_DIR "/data/local/tests/example2"
+  DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA"
+  NO_LINK_REGEX "\\.p$")
+
+set_property(
+  TARGET setup_test
+  PROPERTY EXCLUDE_FROM_ALL 1)
+add_dependencies(tests setup_test)
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest2Build-check.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest2Build-check.cmake
new file mode 100644
index 0000000..6adbd59
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest2Build-check.cmake
@@ -0,0 +1,7 @@
+include(${CMAKE_CURRENT_LIST_DIR}/check.cmake)
+compare_build_to_expected(FILES
+  "data/a.txt"
+  "data/subfolder/b.txt"
+  "data/subfolder/protobuffer.p"
+  )
+check_for_setup_test()
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest3.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest3.cmake
new file mode 100644
index 0000000..b32b6b1
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest3.cmake
@@ -0,0 +1,33 @@
+enable_testing()
+include(AndroidTestUtilities)
+
+add_custom_target(tests)
+find_program(adb_executable adb)
+
+set(ExternalData_URL_TEMPLATES
+  "https://data.kitware.com/api/v1/file/hashsum/%(algo)/%(hash)/download"
+  )
+set(test_dir "/data/local/tests/example3")
+set(test_files
+  "data/a.txt"
+  "data/subfolder/b.txt"
+  )
+set(test_libs "libs/exampleLib.txt")
+set(files_dest "${test_dir}/storage_folder")
+set(libs_dest "${test_dir}/lib/lib/lib")
+
+set(ANDROID 1)
+
+android_add_test_data(setup_test
+  FILES ${test_files}
+  LIBS ${test_libs}
+  FILES_DEST ${files_dest}
+  LIBS_DEST ${libs_dest}
+  DEVICE_TEST_DIR "/data/local/tests/example3"
+  DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA"
+  NO_LINK_REGEX "\\.p$")
+
+set_property(
+  TARGET setup_test
+  PROPERTY EXCLUDE_FROM_ALL 1)
+add_dependencies(tests setup_test)
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest3Build-check.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest3Build-check.cmake
new file mode 100644
index 0000000..3062cdc
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest3Build-check.cmake
@@ -0,0 +1,6 @@
+include(${CMAKE_CURRENT_LIST_DIR}/check.cmake)
+compare_build_to_expected(FILES
+  "data/a.txt"
+  "data/subfolder/b.txt"
+  )
+check_for_setup_test()
diff --git a/Tests/RunCMake/AndroidTestUtilities/check.cmake b/Tests/RunCMake/AndroidTestUtilities/check.cmake
new file mode 100644
index 0000000..ccd4d74
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/check.cmake
@@ -0,0 +1,20 @@
+function(compare_build_to_expected)
+  cmake_parse_arguments(_comp "" "" "FILES" ${ARGN})
+  set(missing)
+  foreach(file ${_comp_FILES})
+    if(NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/${file}")
+      list(APPEND missing "${file}")
+    endif()
+  endforeach()
+  if(missing)
+    string(APPEND RunCMake_TEST_FAILED "Missing files:\n ${missing}")
+    set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
+  endif()
+endfunction()
+
+function(check_for_setup_test)
+  file(STRINGS "${RunCMake_TEST_BINARY_DIR}/CTestTestfile.cmake" output_var REGEX "add_test\\(setup_test.*")
+  if(NOT output_var)
+    set(RunCMake_TEST_FAILED "Could not find the test: setup_test" PARENT_SCOPE)
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/AndroidTestUtilities/data/a.txt b/Tests/RunCMake/AndroidTestUtilities/data/a.txt
new file mode 100644
index 0000000..9d454fb
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/data/a.txt
@@ -0,0 +1 @@
+Here is a file to test.
diff --git a/Tests/RunCMake/AndroidTestUtilities/data/proto.proto b/Tests/RunCMake/AndroidTestUtilities/data/proto.proto
new file mode 100644
index 0000000..7402a3a
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/data/proto.proto
@@ -0,0 +1 @@
+proto.proto
diff --git a/Tests/RunCMake/AndroidTestUtilities/data/subfolder/b.txt b/Tests/RunCMake/AndroidTestUtilities/data/subfolder/b.txt
new file mode 100644
index 0000000..c8c6a89
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/data/subfolder/b.txt
@@ -0,0 +1 @@
+SetupTest2.cmake
diff --git a/Tests/RunCMake/AndroidTestUtilities/data/subfolder/protobuffer.p b/Tests/RunCMake/AndroidTestUtilities/data/subfolder/protobuffer.p
new file mode 100644
index 0000000..a5dc7d2
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/data/subfolder/protobuffer.p
@@ -0,0 +1 @@
+protobuffer.p
diff --git a/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.so b/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.so
new file mode 100644
index 0000000..f4cdf82
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.so
@@ -0,0 +1 @@
+here is a fake lib.
diff --git a/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.txt b/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.txt
new file mode 100644
index 0000000..308921a
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/libs/exampleLib.txt
@@ -0,0 +1 @@
+here is an example lib!
diff --git a/Tests/RunCMake/AutoExportDll/AutoExport.cmake b/Tests/RunCMake/AutoExportDll/AutoExport.cmake
index 3b2b2c5..d37e896 100644
--- a/Tests/RunCMake/AutoExportDll/AutoExport.cmake
+++ b/Tests/RunCMake/AutoExportDll/AutoExport.cmake
@@ -2,6 +2,14 @@ project(autoexport)
 set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${autoexport_BINARY_DIR}/bin)
 add_subdirectory(sub)
-add_library(autoexport SHARED hello.cxx world.cxx foo.c)
+add_library(objlib OBJECT objlib.c)
+set_property(TARGET objlib PROPERTY POSITION_INDEPENDENT_CODE 1)
+add_library(autoexport SHARED hello.cxx world.cxx foo.c $<TARGET_OBJECTS:objlib>)
+
 add_executable(say say.cxx)
+if(MSVC)
+  set_target_properties(say PROPERTIES ENABLE_EXPORTS ON)
+  add_library(autoexport_for_exec SHARED hello2.c)
+  target_link_libraries(autoexport_for_exec say)
+endif()
 target_link_libraries(say autoexport autoexport2)
diff --git a/Tests/RunCMake/AutoExportDll/hello2.c b/Tests/RunCMake/AutoExportDll/hello2.c
new file mode 100644
index 0000000..d4d6b72
--- /dev/null
+++ b/Tests/RunCMake/AutoExportDll/hello2.c
@@ -0,0 +1,8 @@
+#include <stdio.h>
+
+extern int own_auto_export_function(int i);
+
+void hello2()
+{
+  printf("hello exec:%i", own_auto_export_function(41));
+}
diff --git a/Tests/RunCMake/AutoExportDll/objlib.c b/Tests/RunCMake/AutoExportDll/objlib.c
new file mode 100644
index 0000000..54a9658
--- /dev/null
+++ b/Tests/RunCMake/AutoExportDll/objlib.c
@@ -0,0 +1,4 @@
+int objlib()
+{
+  return 7;
+}
diff --git a/Tests/RunCMake/AutoExportDll/say.cxx b/Tests/RunCMake/AutoExportDll/say.cxx
index 0178688..e966b1f 100644
--- a/Tests/RunCMake/AutoExportDll/say.cxx
+++ b/Tests/RunCMake/AutoExportDll/say.cxx
@@ -11,6 +11,7 @@ extern "C" {
 int WINAPI foo();
 // test regular C
 int bar();
+int objlib();
 }
 
 // test c++ functions
@@ -18,6 +19,14 @@ int bar();
 void hello();
 void world();
 
+// test exports for executable target
+extern "C" {
+int own_auto_export_function(int i)
+{
+  return i + 1;
+}
+}
+
 int main()
 {
   // test static data (needs declspec to work)
@@ -31,6 +40,7 @@ int main()
   foo();
   printf("\n");
   bar();
+  objlib();
   printf("\n");
   return 0;
 }
diff --git a/Tests/RunCMake/BuildDepends/check.cmake b/Tests/RunCMake/BuildDepends/check.cmake
index 26a9eb6..c7b5c3d 100644
--- a/Tests/RunCMake/BuildDepends/check.cmake
+++ b/Tests/RunCMake/BuildDepends/check.cmake
@@ -6,7 +6,7 @@ if(EXISTS ${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
   foreach(exe IN LISTS check_exes)
     execute_process(COMMAND ${exe} RESULT_VARIABLE res)
     if(NOT res EQUAL ${check_step})
-      set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}
+      string(APPEND RunCMake_TEST_FAILED "
  '${exe}' returned '${res}' but expected '${check_step}'
 ")
     endif()
@@ -16,15 +16,15 @@ if(EXISTS ${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
       set(lhs "${CMAKE_MATCH_1}")
       set(rhs "${CMAKE_MATCH_2}")
       if(NOT EXISTS "${lhs}")
-        set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}
+        string(APPEND RunCMake_TEST_FAILED "
  '${lhs}' missing
 ")
       elseif(NOT EXISTS "${rhs}")
-        set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}
+        string(APPEND RunCMake_TEST_FAILED "
  '${rhs}' missing
 ")
       elseif(NOT "${lhs}" IS_NEWER_THAN "${rhs}")
-        set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}
+        string(APPEND RunCMake_TEST_FAILED "
  '${lhs}' is not newer than '${rhs}'
 ")
       endif()
diff --git a/Tests/RunCMake/CMP0040/CMP0040-NEW-existing-target.cmake b/Tests/RunCMake/CMP0040/CMP0040-NEW-existing-target.cmake
index f9c8afd..880b178 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-NEW-existing-target.cmake
+++ b/Tests/RunCMake/CMP0040/CMP0040-NEW-existing-target.cmake
@@ -3,5 +3,5 @@ cmake_policy(SET CMP0040 NEW)
 add_library(foobar empty.cpp)
 
 add_custom_command(TARGET foobar PRE_BUILD
-  COMMAND "${CMAKE_COMMAND} -E echo hello world"
+  COMMAND ${CMAKE_COMMAND} -E echo hello world
 )
diff --git a/Tests/RunCMake/CMP0040/CMP0040-NEW-missing-target.cmake b/Tests/RunCMake/CMP0040/CMP0040-NEW-missing-target.cmake
index 276863d..a9f764c 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-NEW-missing-target.cmake
+++ b/Tests/RunCMake/CMP0040/CMP0040-NEW-missing-target.cmake
@@ -1,5 +1,5 @@
 cmake_policy(SET CMP0040 NEW)
 
 add_custom_command(TARGET foobar PRE_BUILD
-  COMMAND "${CMAKE_COMMAND} -E hello world"
+  COMMAND ${CMAKE_COMMAND} -E hello world
 )
diff --git a/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target.cmake b/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target.cmake
index d7ec50d..7a9e91e 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target.cmake
+++ b/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target.cmake
@@ -3,5 +3,5 @@ cmake_policy(SET CMP0040 OLD)
 add_library(foobar empty.cpp)
 
 add_custom_command(TARGET foobar PRE_BUILD
-  COMMAND "${CMAKE_COMMAND} -E echo hello world"
+  COMMAND ${CMAKE_COMMAND} -E echo hello world
 )
diff --git a/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target.cmake b/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target.cmake
index ef7a0f7..0f5cd15 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target.cmake
+++ b/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target.cmake
@@ -1,5 +1,5 @@
 cmake_policy(SET CMP0040 OLD)
 
 add_custom_command(TARGET foobar PRE_BUILD
-  COMMAND "${CMAKE_COMMAND} -E echo hello world"
+  COMMAND ${CMAKE_COMMAND} -E echo hello world
 )
diff --git a/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target.cmake b/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target.cmake
index 2c3e401..4efeaae 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target.cmake
+++ b/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target.cmake
@@ -1,4 +1,4 @@
 
 add_custom_command(TARGET foobar PRE_BUILD
-  COMMAND "${CMAKE_COMMAND} -E hello world"
+  COMMAND ${CMAKE_COMMAND} -E hello world
 )
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake
index 2b22778..7fb836e 100644
--- a/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake
@@ -25,7 +25,7 @@ while(NOT LOOP_VAR STREQUAL "xx")
 
   cmake_policy(SET CMP0054 NEW)
 
-  set(LOOP_VAR "${LOOP_VAR}x")
+  string(APPEND LOOP_VAR "x")
 endwhile()
 
 while("FOO" STREQUAL BAR)
@@ -57,7 +57,7 @@ while(NOT LOOP_VAR STREQUAL "xx")
 
   cmake_policy(SET CMP0054 OLD)
 
-  set(LOOP_VAR "${LOOP_VAR}x")
+  string(APPEND LOOP_VAR "x")
 endwhile()
 
 if(NOT "FOO" STREQUAL BAR)
diff --git a/Tests/RunCMake/CMP0065/WARN-ON-stderr.txt b/Tests/RunCMake/CMP0065/WARN-ON-stderr.txt
index dda4fe5..c31ec38 100644
--- a/Tests/RunCMake/CMP0065/WARN-ON-stderr.txt
+++ b/Tests/RunCMake/CMP0065/WARN-ON-stderr.txt
@@ -5,6 +5,6 @@ CMake Warning \(dev\) in CMakeLists.txt:
   set the policy and suppress this warning.
 
   For compatibility with older versions of CMake, additional flags may be
-  added to export symbols on all executables regardless of thier
+  added to export symbols on all executables regardless of their
   ENABLE_EXPORTS property.
 This warning is for project developers.  Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index d16e5e7..9dc540f 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -131,6 +131,7 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
     )
 endif()
 
+add_RunCMake_test(AndroidTestUtilities)
 add_RunCMake_test(BuildDepends)
 if(UNIX AND "${CMAKE_GENERATOR}" MATCHES "Unix Makefiles|Ninja")
   add_RunCMake_test(CompilerChange)
@@ -141,6 +142,9 @@ add_RunCMake_test(DisallowedCommands)
 add_RunCMake_test(ExternalData)
 add_RunCMake_test(FeatureSummary)
 add_RunCMake_test(FPHSA)
+if(NOT CMAKE_C_COMPILER_ID MATCHES "Watcom")
+  add_RunCMake_test(GenerateExportHeader)
+endif()
 add_RunCMake_test(GeneratorExpression)
 add_RunCMake_test(GeneratorPlatform)
 add_RunCMake_test(GeneratorToolset)
@@ -181,6 +185,7 @@ add_RunCMake_test(cmake_minimum_required)
 add_RunCMake_test(cmake_parse_arguments)
 add_RunCMake_test(continue)
 add_RunCMake_test(ctest_build)
+add_RunCMake_test(ctest_cmake_error)
 add_RunCMake_test(ctest_configure)
 if(COVERAGE_COMMAND)
   add_RunCMake_test(ctest_coverage -DCOVERAGE_COMMAND=${COVERAGE_COMMAND})
@@ -189,6 +194,7 @@ add_RunCMake_test(ctest_start)
 add_RunCMake_test(ctest_submit)
 add_RunCMake_test(ctest_test)
 add_RunCMake_test(ctest_upload)
+add_RunCMake_test(ctest_fixtures)
 add_RunCMake_test(file)
 add_RunCMake_test(find_file)
 add_RunCMake_test(find_library)
@@ -202,7 +208,7 @@ add_RunCMake_test(include)
 add_RunCMake_test(include_directories)
 add_RunCMake_test(list)
 add_RunCMake_test(message)
-add_RunCMake_test(project)
+add_RunCMake_test(project -DCMake_TEST_RESOURCES=${CMake_TEST_RESOURCES})
 add_RunCMake_test(return)
 add_RunCMake_test(set_property)
 add_RunCMake_test(string)
@@ -307,6 +313,15 @@ if(CMAKE_OSX_ARCHITECTURES AND XCODE AND NOT "${XCODE_VERSION}" MATCHES "^[^12]"
 endif()
 
 if("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+  if(UNIX AND NOT CYGWIN)
+    execute_process(COMMAND ldd --help
+      OUTPUT_VARIABLE LDD_HELP
+      ERROR_VARIABLE LDD_ERR)
+    if("${LDD_HELP}" MATCHES
+        "(-r, --function-relocs.*process data and function relocations.*-u, --unused.*print unused direct dependencies)")
+      add_RunCMake_test(LinkWhatYouUse)
+    endif()
+  endif()
   add_executable(pseudo_tidy pseudo_tidy.c)
   add_executable(pseudo_iwyu pseudo_iwyu.c)
   add_RunCMake_test(ClangTidy -DPSEUDO_TIDY=$<TARGET_FILE:pseudo_tidy>)
@@ -318,3 +333,26 @@ add_RunCMake_test_group(CPack "DEB;RPM;TGZ")
 # add a test to make sure symbols are exported from a shared library
 # for MSVC compilers CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS property is used
 add_RunCMake_test(AutoExportDll)
+
+add_RunCMake_test(AndroidMK)
+
+if(CMake_TEST_ANDROID_NDK OR CMake_TEST_ANDROID_STANDALONE_TOOLCHAIN)
+  if(NOT "${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+    message(FATAL_ERROR "Android tests supported only by Makefile and Ninja generators")
+  endif()
+  foreach(v TEST_ANDROID_NDK TEST_ANDROID_STANDALONE_TOOLCHAIN)
+    if(CMake_${v})
+      string(REPLACE ";" "|" ${v} "${CMake_${v}}")
+      list(APPEND Android_ARGS "-D${v}=${${v}}")
+    endif()
+  endforeach()
+
+  add_RunCMake_test(Android)
+
+  # This test can take a very long time due to lots of combinations.
+  # Use a long default timeout and provide an option to customize it.
+  if(NOT DEFINED CMake_TEST_ANDROID_TIMEOUT)
+    set(CMake_TEST_ANDROID_TIMEOUT 3000)
+  endif()
+  set_property(TEST RunCMake.Android PROPERTY TIMEOUT ${CMake_TEST_ANDROID_TIMEOUT})
+endif()
diff --git a/Tests/RunCMake/CPack/CMakeLists.txt b/Tests/RunCMake/CPack/CMakeLists.txt
index 46f1367..e42e971 100644
--- a/Tests/RunCMake/CPack/CMakeLists.txt
+++ b/Tests/RunCMake/CPack/CMakeLists.txt
@@ -1,11 +1,11 @@
 cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
 
 project(${RunCMake_TEST} CXX)
-include(${RunCMake_TEST}.cmake)
+include(${RunCMake_TEST_FILE_PREFIX}.cmake)
 
 # include test generator specifics
-if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/${RunCMake_TEST}-specifics.cmake")
-  include("${GENERATOR_TYPE}/${RunCMake_TEST}-specifics.cmake")
+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
+  include("${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
 endif()
 
 set(CPACK_GENERATOR "${GENERATOR_TYPE}")
diff --git a/Tests/RunCMake/CPack/CPackTestHelpers.cmake b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
index 7bf42f9..7e6b4b1 100644
--- a/Tests/RunCMake/CPack/CPackTestHelpers.cmake
+++ b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
@@ -1,9 +1,15 @@
 cmake_policy(SET CMP0057 NEW)
 
-function(run_cpack_test TEST_NAME types build)
+function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
   if(TEST_TYPE IN_LIST types)
     set(RunCMake_TEST_NO_CLEAN TRUE)
     set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${TEST_NAME}-build")
+    set(full_test_name_ "${TEST_NAME}")
+
+    if(SUBTEST_SUFFIX)
+      set(RunCMake_TEST_BINARY_DIR "${RunCMake_TEST_BINARY_DIR}-${SUBTEST_SUFFIX}-subtest")
+      set(full_test_name_ "${full_test_name_}-${SUBTEST_SUFFIX}-subtest")
+    endif()
 
      # TODO this should be executed only once per ctest run (not per generator)
     file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
@@ -24,27 +30,48 @@ function(run_cpack_test TEST_NAME types build)
     endif()
 
     # execute cmake
-    set(RunCMake_TEST_OPTIONS "-DGENERATOR_TYPE=${TEST_TYPE}")
-    run_cmake(${TEST_NAME})
+    set(RunCMake_TEST_OPTIONS "-DGENERATOR_TYPE=${TEST_TYPE}"
+      "-DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}"
+      "-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}")
+    run_cmake(${full_test_name_})
 
     # execute optional build step
     if(build)
-      run_cmake_command(${TEST_NAME}-Build "${CMAKE_COMMAND}" --build "${RunCMake_TEST_BINARY_DIR}")
+      run_cmake_command(${full_test_name_}-Build "${CMAKE_COMMAND}" --build "${RunCMake_TEST_BINARY_DIR}")
+    endif()
+
+    if(source)
+      set(pack_params_ -G ${TEST_TYPE} --config ./CPackSourceConfig.cmake)
+      FILE(APPEND ${RunCMake_TEST_BINARY_DIR}/CPackSourceConfig.cmake
+        "\nset(CPACK_RPM_SOURCE_PKG_BUILD_PARAMS \"-DRunCMake_TEST:STRING=${full_test_name_}\ -DRunCMake_TEST_FILE_PREFIX:STRING=${TEST_NAME}\")")
+    else()
+      unset(pack_params_)
     endif()
 
     # execute cpack
     execute_process(
-      COMMAND "${CMAKE_CPACK_COMMAND}"
+      COMMAND ${CMAKE_CPACK_COMMAND} ${pack_params_}
       WORKING_DIRECTORY "${RunCMake_TEST_BINARY_DIR}"
+      RESULT_VARIABLE "result_"
       OUTPUT_FILE "${RunCMake_TEST_BINARY_DIR}/test_output.txt"
       ERROR_FILE "${RunCMake_TEST_BINARY_DIR}/test_error.txt"
       )
 
+    foreach(o out err)
+      if(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt)
+        set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt")
+      elseif(EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-std${o}.txt)
+        set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-std${o}.txt")
+      endif()
+    endforeach()
+
     # verify result
     run_cmake_command(
-      ${TEST_TYPE}/${TEST_NAME}
+      ${TEST_TYPE}/${full_test_name_}
       "${CMAKE_COMMAND}"
-        -DRunCMake_TEST=${TEST_NAME}
+        -DRunCMake_TEST=${full_test_name_}
+        -DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}
+        -DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}
         -DGENERATOR_TYPE=${TEST_TYPE}
         "-Dsrc_dir=${RunCMake_SOURCE_DIR}"
         "-Dbin_dir=${RunCMake_TEST_BINARY_DIR}"
@@ -53,3 +80,17 @@ function(run_cpack_test TEST_NAME types build)
       )
   endif()
 endfunction()
+
+function(run_cpack_test TEST_NAME types build)
+  run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" false)
+endfunction()
+
+function(run_cpack_source_test TEST_NAME types build)
+  run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" true)
+endfunction()
+
+function(run_cpack_test_subtests TEST_NAME SUBTEST_SUFFIXES types build)
+  foreach(suffix_ IN LISTS SUBTEST_SUFFIXES)
+    run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "${suffix_}" false)
+  endforeach()
+endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/Helpers.cmake b/Tests/RunCMake/CPack/DEB/Helpers.cmake
index d05f115..9b1be22 100644
--- a/Tests/RunCMake/CPack/DEB/Helpers.cmake
+++ b/Tests/RunCMake/CPack/DEB/Helpers.cmake
@@ -40,13 +40,13 @@ function(getMissingShlibsErrorExtra FILE RESULT_VAR)
       set(error_extra " Extra: install files '${deb_install_files}'")
 
       if(deb_install_files_errors)
-        set(error_extra "${error_extra}; errors \"${deb_install_files_errors}\"")
+        string(APPEND error_extra "; errors \"${deb_install_files_errors}\"")
       endif()
 
       find_program(READELF_EXECUTABLE NAMES readelf)
 
       if(READELF_EXECUTABLE)
-        set(error_extra "${error_extra}; readelf \"\n")
+        string(APPEND error_extra "; readelf \"\n")
 
         # Only dynamically linked ELF files are included
         # Extract only file name infront of ":"
@@ -61,13 +61,13 @@ function(getMissingShlibsErrorExtra FILE RESULT_VAR)
               ERROR_VARIABLE err_
               OUTPUT_STRIP_TRAILING_WHITESPACE)
 
-            set(error_extra "${error_extra} name '${CMAKE_MATCH_1}'\n result '${result}'\n output '${output}'\n error '${err_}'\n")
+            string(APPEND error_extra " name '${CMAKE_MATCH_1}'\n result '${result}'\n output '${output}'\n error '${err_}'\n")
           endif()
         endforeach()
 
-        set(error_extra "${error_extra}\"")
+        string(APPEND error_extra "\"")
       else()
-        set(error_extra "${error_extra}; error readelf missing")
+        string(APPEND error_extra "; error readelf missing")
       endif()
     endif()
 
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
new file mode 100644
index 0000000..dd72cf7
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
@@ -0,0 +1,5 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_1 "long_filenames_0.1.1-1_*.deb")
+set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
new file mode 100644
index 0000000..0c1d77e
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var)
+  find_program(FAKEROOT_EXECUTABLE NAMES fakeroot)
+
+  if(FAKEROOT_EXECUTABLE)
+    set(${found_var} true PARENT_SCOPE)
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake
new file mode 100644
index 0000000..0452343
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake
@@ -0,0 +1,26 @@
+# create structure required by non root dpkg install
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/root_dir")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir/updates")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir/info")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir/available" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir/status" "")
+
+# some programs used by fakeroot require sbin in path so we should not
+# leave this to chance (programs: ldconfig and start-stop-daemon)
+set(ENV{PATH} "$ENV{PATH}:/usr/local/sbin:/usr/sbin:/sbin")
+
+execute_process(COMMAND ${FAKEROOT_EXECUTABLE} ${DPKG_EXECUTABLE}
+      -i --force-not-root --root=${CMAKE_CURRENT_BINARY_DIR}/root_dir
+      --admindir=${CMAKE_CURRENT_BINARY_DIR}/root_dir/admindir
+      --log=${CMAKE_CURRENT_BINARY_DIR}/root_dir/dpkg.log
+      ${FOUND_FILE_1}
+    RESULT_VARIABLE install_result_
+    ERROR_VARIABLE install_error_
+    OUTPUT_QUIET
+  )
+
+if(install_result_)
+  message(FATAL_ERROR "LONG_FILENAMES package error -  result:"
+    " '${install_result_}'; text: '${install_error_}'")
+endif()
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
new file mode 100644
index 0000000..39a6be4
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
@@ -0,0 +1,3 @@
+set(CPACK_PACKAGE_CONTACT "someone")
+set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
diff --git a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
index 197b99d..cb9a277 100644
--- a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
+++ b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
@@ -5,4 +5,11 @@ function(get_test_prerequirements found_var config_file)
     file(WRITE "${config_file}" "set(DPKG_EXECUTABLE \"${DPKG_EXECUTABLE}\")")
     set(${found_var} true PARENT_SCOPE)
   endif()
+
+  # optional tool for some tests
+  find_program(FAKEROOT_EXECUTABLE fakeroot)
+  if(FAKEROOT_EXECUTABLE)
+    file(APPEND "${config_file}"
+      "\nset(FAKEROOT_EXECUTABLE \"${FAKEROOT_EXECUTABLE}\")")
+  endif()
 endfunction()
diff --git a/Tests/RunCMake/CPack/DEBUGINFO.cmake b/Tests/RunCMake/CPack/DEBUGINFO.cmake
new file mode 100644
index 0000000..d98b682
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEBUGINFO.cmake
@@ -0,0 +1,34 @@
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+# PGI compiler doesn't add build id to binaries by default
+if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
+  string(APPEND CMAKE_EXE_LINKER_FLAGS "-Wl,--build-id")
+  string(APPEND CMAKE_SHARED_LINKER_FLAGS "-Wl,--build-id")
+endif()
+
+set(CPACK_RPM_COMPONENT_INSTALL "ON")
+
+set(CMAKE_BUILD_TYPE Debug)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+target_link_libraries(test_prog test_lib)
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+install(TARGETS test_lib DESTINATION bas COMPONENT libs)
+
+set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
+set(CPACK_RPM_APPLICATIONS_DEBUGINFO_PACKAGE ON)
+set(CPACK_RPM_LIBS_DEBUGINFO_PACKAGE ON)
+
+set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
+
+set(CPACK_PACKAGE_NAME "debuginfo")
diff --git a/Tests/RunCMake/CPack/LONG_FILENAMES.cmake b/Tests/RunCMake/CPack/LONG_FILENAMES.cmake
new file mode 100644
index 0000000..3242aef
--- /dev/null
+++ b/Tests/RunCMake/CPack/LONG_FILENAMES.cmake
@@ -0,0 +1,10 @@
+set(LONG_FILENAME
+  "${CMAKE_CURRENT_BINARY_DIR}/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
+
+file(WRITE
+  "${LONG_FILENAME}"
+  "long_filename_test")
+
+install(FILES ${LONG_FILENAME} DESTINATION foo)
+
+set(CPACK_PACKAGE_NAME "long_filenames")
diff --git a/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake b/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake
new file mode 100644
index 0000000..5ca288c
--- /dev/null
+++ b/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake
@@ -0,0 +1,4 @@
+install(FILES CMakeLists.txt DESTINATION foo)
+
+set(CPACK_PACKAGE_NAME "package_checksum")
+set(CPACK_PACKAGE_CHECKSUM ${RunCMake_SUBTEST_SUFFIX})
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
new file mode 100644
index 0000000..a583e32
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
@@ -0,0 +1,14 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "5")
+set(EXPECTED_FILE_1 "debuginfo-applications-0*.rpm")
+set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
+set(EXPECTED_FILE_2 "debuginfo*-headers.rpm")
+set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
+set(EXPECTED_FILE_3 "debuginfo*-libs.rpm")
+set(EXPECTED_FILE_CONTENT_3 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
+
+set(EXPECTED_FILE_4 "debuginfo-applications-debuginfo*.rpm")
+set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
+set(EXPECTED_FILE_5 "debuginfo-libs-debuginfo*.rpm")
+set(EXPECTED_FILE_CONTENT_5 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/test_lib.cpp.*")
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt b/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
new file mode 100644
index 0000000..557ef3d
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
@@ -0,0 +1,3 @@
+^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-applications.spec
+CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-headers.spec
+CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-libs.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
new file mode 100644
index 0000000..d6811eb
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
@@ -0,0 +1,5 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_1 "source_package*.src.rpm")
+set(EXPECTED_FILE_CONTENT_1 "^source_package-0.1.1.tar.gz${whitespaces_}source_package.spec$")
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake
new file mode 100644
index 0000000..a84e296
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake
@@ -0,0 +1,63 @@
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILD")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILDROOT")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SOURCES")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SPECS")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SRPMS")
+
+# make sure that we are using the version of cmake and cpack that we are testing
+get_filename_component(cpack_path_ "${CMAKE_CPACK_COMMAND}" DIRECTORY)
+set(ENV{PATH} "${cpack_path_}:$ENV{PATH}")
+
+execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --define "_topdir ${CMAKE_CURRENT_BINARY_DIR}/test_rpm" --rebuild ${FOUND_FILE_1}
+      RESULT_VARIABLE result_
+      ERROR_VARIABLE  error_
+      OUTPUT_QUIET
+  )
+
+set(output_error_message_
+    "\n${RPMBUILD_EXECUTABLE} error: '${error_}';\nresult: '${result_}';\n${output_error_message}")
+
+set(EXPECTED_FILE_CONTENT_ "^/foo${whitespaces_}/foo/test_prog$")
+
+file(GLOB_RECURSE FOUND_FILE_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/*.rpm")
+list(APPEND foundFiles_ "${FOUND_FILE_}")
+list(LENGTH FOUND_FILE_ foundFilesCount_)
+
+if(foundFilesCount_ EQUAL 1)
+  unset(PACKAGE_CONTENT)
+  getPackageContent("${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/${FOUND_FILE_}" "PACKAGE_CONTENT")
+
+  string(REGEX MATCH "${EXPECTED_FILE_CONTENT_}"
+      expected_content_list "${PACKAGE_CONTENT}")
+
+  if(NOT expected_content_list)
+    message(FATAL_ERROR
+      "Unexpected file content!\n"
+      " Content: '${PACKAGE_CONTENT}'\n\n"
+      " Expected: '${EXPECTED_FILE_CONTENT_}'"
+      "${output_error_message_}")
+  endif()
+else()
+  message(FATAL_ERROR
+    "Found more than one file!"
+    " Found files count '${foundFilesCount_}'."
+    " Files: '${FOUND_FILE_}'"
+    "${output_error_message_}")
+endif()
+
+# check that there were no extra files generated
+foreach(all_files_glob_ IN LISTS ALL_FILES_GLOB)
+  file(GLOB foundAll_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${all_files_glob_}")
+  list(APPEND allFoundFiles_ "${foundAll_}")
+endforeach()
+
+list(LENGTH foundFiles_ foundFilesCount_)
+list(LENGTH allFoundFiles_ allFoundFilesCount_)
+
+if(NOT foundFilesCount_ EQUAL allFoundFilesCount_)
+  message(FATAL_ERROR
+      "Found more files than expected! Found files: '${allFoundFiles_}'"
+      "${output_error_message_}")
+endif()
diff --git a/Tests/RunCMake/CPack/RunCMakeTest.cmake b/Tests/RunCMake/CPack/RunCMakeTest.cmake
index 59c52f8..60d42ac 100644
--- a/Tests/RunCMake/CPack/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CPack/RunCMakeTest.cmake
@@ -5,6 +5,7 @@ include("${RunCMake_SOURCE_DIR}/CPackTestHelpers.cmake")
 
 # args: TEST_NAME "GENERATORS" RUN_CMAKE_BUILD_STEP
 run_cpack_test(MINIMAL "RPM;DEB;TGZ" false)
+run_cpack_source_test(SOURCE_PACKAGE "RPM" true)
 run_cpack_test(PARTIALLY_RELOCATABLE_WARNING "RPM" false)
 run_cpack_test(DEB_EXTRA "DEB" false)
 run_cpack_test(DEPENDENCIES "RPM;DEB" true)
@@ -16,3 +17,6 @@ run_cpack_test(RPM_DIST "RPM" false)
 run_cpack_test(INSTALL_SCRIPTS "RPM" false)
 run_cpack_test(DEB_GENERATE_SHLIBS "DEB" true)
 run_cpack_test(DEB_GENERATE_SHLIBS_LDCONFIG "DEB" true)
+run_cpack_test(DEBUGINFO "RPM" true)
+run_cpack_test(LONG_FILENAMES "DEB" false)
+run_cpack_test_subtests(PACKAGE_CHECKSUM "invalid;MD5;SHA1;SHA224;SHA256;SHA384;SHA512" "TGZ" false)
diff --git a/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake b/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake
new file mode 100644
index 0000000..946439d
--- /dev/null
+++ b/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake
@@ -0,0 +1,9 @@
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "int main() {return 0;}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+
+set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
+
+set(CPACK_PACKAGE_NAME "source_package")
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
new file mode 100644
index 0000000..205dcd8
--- /dev/null
+++ b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
@@ -0,0 +1,9 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "0")
+
+if (NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
+  set(EXPECTED_FILES_COUNT "1")
+  set(EXPECTED_FILE_1 "package_checksum*.tar.gz")
+  set(EXPECTED_FILE_CONTENT_1 "^[^\n]*package_checksum*-[^\n]*/foo/\n[^\n]*package_checksum-[^\n]*/foo/CMakeLists.txt$")
+endif()
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake
new file mode 100644
index 0000000..e9e65d6
--- /dev/null
+++ b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake
@@ -0,0 +1,14 @@
+if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
+  string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} EXTENSION)
+  file(GLOB PACKAGE RELATIVE ${bin_dir} "*.tar.gz")
+  file(GLOB CSUMFILE RELATIVE ${bin_dir} "*.${EXTENSION}")
+  file(STRINGS ${CSUMFILE} CHSUM_VALUE)
+  file(${RunCMake_SUBTEST_SUFFIX} ${PACKAGE} expected_value )
+  set(expected_value "${expected_value}  ${PACKAGE}")
+
+  if(NOT expected_value STREQUAL CHSUM_VALUE)
+    message(FATAL_ERROR "Generated checksum is not valid! Expected [${expected_value}] Got [${CHSUM_VALUE}]")
+  endif()
+else()
+  message(${error})
+endif()
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt
new file mode 100644
index 0000000..abf6d8c
--- /dev/null
+++ b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt
@@ -0,0 +1,2 @@
+^CPack Error: Cannot recognize algorithm: invalid
+CPack Error: Error when generating package: package_checksum$
diff --git a/Tests/RunCMake/CPack/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake
index 6eab531..8bc2a58 100644
--- a/Tests/RunCMake/CPack/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/VerifyResult.cmake
@@ -8,15 +8,15 @@ file(READ "${bin_dir}/test_error.txt" error)
 file(READ "${config_file}" config_file_content)
 
 set(output_error_message
-    "\nCPack output: '${output}'\nCPack error: '${error}';\nconfig file: '${config_file_content}'")
+    "\nCPack output: '${output}'\nCPack error: '${error}';\nCPack result: '${PACKAGING_RESULT}';\nconfig file: '${config_file_content}'")
 
 # check that expected generated files exist and contain expected content
-include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST}-ExpectedFiles.cmake")
+include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-ExpectedFiles.cmake")
 
 if(NOT EXPECTED_FILES_COUNT EQUAL 0)
   foreach(file_no_ RANGE 1 ${EXPECTED_FILES_COUNT})
     file(GLOB FOUND_FILE_${file_no_} RELATIVE "${bin_dir}" "${EXPECTED_FILE_${file_no_}}")
-    set(foundFiles_ "${foundFiles_};${FOUND_FILE_${file_no_}}")
+    list(APPEND foundFiles_ "${FOUND_FILE_${file_no_}}")
     list(LENGTH FOUND_FILE_${file_no_} foundFilesCount_)
 
     if(foundFilesCount_ EQUAL 1)
@@ -45,7 +45,7 @@ if(NOT EXPECTED_FILES_COUNT EQUAL 0)
   # check that there were no extra files generated
   foreach(all_files_glob_ IN LISTS ALL_FILES_GLOB)
     file(GLOB foundAll_ RELATIVE "${bin_dir}" "${all_files_glob_}")
-    set(allFoundFiles_ "${allFoundFiles_};${foundAll_}")
+    list(APPEND allFoundFiles_ "${foundAll_}")
   endforeach()
 
   list(LENGTH foundFiles_ foundFilesCount_)
@@ -82,8 +82,8 @@ else()
 endif()
 
 # handle additional result verifications
-if(EXISTS "${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST}-VerifyResult.cmake")
-  include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST}-VerifyResult.cmake")
+if(EXISTS "${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
+  include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
 else()
   # by default only print out output and error so that they can be compared by
   # regex
diff --git a/Tests/RunCMake/CTest/BeforeProject-stderr.txt b/Tests/RunCMake/CTest/BeforeProject-stderr.txt
index d61856c..cfbe4d2 100644
--- a/Tests/RunCMake/CTest/BeforeProject-stderr.txt
+++ b/Tests/RunCMake/CTest/BeforeProject-stderr.txt
@@ -1,6 +1,6 @@
-CMake Error at .*/Modules/CTestTargets.cmake:20 \(message\):
+CMake Error at .*/Modules/CTestTargets.cmake:[0-9]+ \(message\):
   Do not include\(CTest\) before calling project\(\).
 Call Stack \(most recent call first\):
   .*/Modules/CTest.cmake:[0-9]+ \(include\)
-  BeforeProject.cmake:1 \(include\)
-  CMakeLists.txt:5 \(include\)
+  BeforeProject.cmake:[0-9]+ \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/CommandLine/E_capabilities-arg-result.txt b/Tests/RunCMake/CommandLine/E_capabilities-arg-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_capabilities-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_capabilities-arg-stderr.txt b/Tests/RunCMake/CommandLine/E_capabilities-arg-stderr.txt
new file mode 100644
index 0000000..f74cebe
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_capabilities-arg-stderr.txt
@@ -0,0 +1 @@
+^-E capabilities accepts no additional arguments$
diff --git a/Tests/RunCMake/CommandLine/E_capabilities-stdout.txt b/Tests/RunCMake/CommandLine/E_capabilities-stdout.txt
new file mode 100644
index 0000000..6c5ea44
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_capabilities-stdout.txt
@@ -0,0 +1 @@
+^{.*}$
diff --git a/Tests/RunCMake/CommandLine/E_server-arg-result.txt b/Tests/RunCMake/CommandLine/E_server-arg-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_server-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_server-arg-stderr.txt b/Tests/RunCMake/CommandLine/E_server-arg-stderr.txt
new file mode 100644
index 0000000..4dcbab9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_server-arg-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: Unknown argument for server mode$
diff --git a/Tests/RunCMake/CommandLine/E_server-pipe-result.txt b/Tests/RunCMake/CommandLine/E_server-pipe-result.txt
new file mode 100644
index 0000000..0cfbf08
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_server-pipe-result.txt
@@ -0,0 +1 @@
+2
diff --git a/Tests/RunCMake/CommandLine/E_server-pipe-stderr.txt b/Tests/RunCMake/CommandLine/E_server-pipe-stderr.txt
new file mode 100644
index 0000000..7193ba6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_server-pipe-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: No pipe given after --pipe=$
diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
index f449f1d..0c4f71c 100644
--- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
@@ -8,8 +8,12 @@ run_cmake_command(lists-no-file ${CMAKE_COMMAND} nosuchsubdir/CMakeLists.txt)
 run_cmake_command(D-no-arg ${CMAKE_COMMAND} -D)
 run_cmake_command(U-no-arg ${CMAKE_COMMAND} -U)
 run_cmake_command(E-no-arg ${CMAKE_COMMAND} -E)
+run_cmake_command(E_capabilities ${CMAKE_COMMAND} -E capabilities)
+run_cmake_command(E_capabilities-arg ${CMAKE_COMMAND} -E capabilities --extra-arg)
 run_cmake_command(E_echo_append ${CMAKE_COMMAND} -E echo_append)
 run_cmake_command(E_rename-no-arg ${CMAKE_COMMAND} -E rename)
+run_cmake_command(E_server-arg ${CMAKE_COMMAND} -E server --extra-arg)
+run_cmake_command(E_server-pipe ${CMAKE_COMMAND} -E server --pipe=)
 run_cmake_command(E_touch_nocreate-no-arg ${CMAKE_COMMAND} -E touch_nocreate)
 
 run_cmake_command(E_time ${CMAKE_COMMAND} -E time ${CMAKE_COMMAND} -E echo "hello  world")
@@ -264,6 +268,10 @@ set(RunCMake_TEST_OPTIONS --trace-expand)
 run_cmake(trace-expand)
 unset(RunCMake_TEST_OPTIONS)
 
+set(RunCMake_TEST_OPTIONS --trace-source=trace-only-this-file.cmake)
+run_cmake(trace-source)
+unset(RunCMake_TEST_OPTIONS)
+
 set(RunCMake_TEST_OPTIONS --debug-trycompile)
 run_cmake(debug-trycompile)
 unset(RunCMake_TEST_OPTIONS)
diff --git a/Tests/RunCMake/CommandLine/trace-only-this-file.cmake b/Tests/RunCMake/CommandLine/trace-only-this-file.cmake
new file mode 100644
index 0000000..1450271
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/trace-only-this-file.cmake
@@ -0,0 +1 @@
+message(STATUS "trace particular file test passed")
diff --git a/Tests/RunCMake/CommandLine/trace-source-stderr.txt b/Tests/RunCMake/CommandLine/trace-source-stderr.txt
new file mode 100644
index 0000000..dc90c65
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/trace-source-stderr.txt
@@ -0,0 +1 @@
+^.*/trace-only-this-file.cmake\(1\):  message\(STATUS trace particular file test passed \)$
diff --git a/Tests/RunCMake/CommandLine/trace-source.cmake b/Tests/RunCMake/CommandLine/trace-source.cmake
new file mode 100644
index 0000000..5ac2d9d
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/trace-source.cmake
@@ -0,0 +1,3 @@
+message(STATUS "before include()")
+include("trace-only-this-file.cmake")
+message(STATUS "after include()")
diff --git a/Tests/RunCMake/Configure/ContinueAfterError-result.txt b/Tests/RunCMake/Configure/ContinueAfterError-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Configure/ContinueAfterError-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Configure/ContinueAfterError-stderr.txt b/Tests/RunCMake/Configure/ContinueAfterError-stderr.txt
new file mode 100644
index 0000000..f40a3ef
--- /dev/null
+++ b/Tests/RunCMake/Configure/ContinueAfterError-stderr.txt
@@ -0,0 +1,13 @@
+^CMake Error at ContinueAfterError.cmake:[0-9]+ \(message\):
+  error in loop body
+Call Stack \(most recent call first\):
+  ContinueAfterError.cmake:[0-9]+ \(m\)
+  ContinueAfterError.cmake:[0-9]+ \(f\)
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at ContinueAfterError.cmake:[0-9]+ \(message\):
+  error in loop body
+Call Stack \(most recent call first\):
+  ContinueAfterError.cmake:[0-9]+ \(m\)
+  ContinueAfterError.cmake:[0-9]+ \(f\)
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/Configure/ContinueAfterError-stdout.txt b/Tests/RunCMake/Configure/ContinueAfterError-stdout.txt
new file mode 100644
index 0000000..f03aa07
--- /dev/null
+++ b/Tests/RunCMake/Configure/ContinueAfterError-stdout.txt
@@ -0,0 +1,11 @@
+-- before f
+--  start f
+--   start m
+--    start loop body
+--    end loop body
+--    start loop body
+--    end loop body
+--   end m
+--  end f
+-- after f
+-- Configuring incomplete, errors occurred!
diff --git a/Tests/RunCMake/Configure/ContinueAfterError.cmake b/Tests/RunCMake/Configure/ContinueAfterError.cmake
new file mode 100644
index 0000000..d094390
--- /dev/null
+++ b/Tests/RunCMake/Configure/ContinueAfterError.cmake
@@ -0,0 +1,19 @@
+macro(m)
+  message(STATUS "  start m")
+  foreach(i 1 2)
+    message(STATUS "   start loop body")
+    message(SEND_ERROR "error in loop body")
+    message(STATUS "   end loop body")
+  endforeach()
+  message(STATUS "  end m")
+endmacro()
+
+function(f)
+  message(STATUS " start f")
+  m()
+  message(STATUS " end f")
+endfunction()
+
+message(STATUS "before f")
+f()
+message(STATUS "after f")
diff --git a/Tests/RunCMake/Configure/RunCMakeTest.cmake b/Tests/RunCMake/Configure/RunCMakeTest.cmake
index 58e1a2a..91adb4e 100644
--- a/Tests/RunCMake/Configure/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Configure/RunCMakeTest.cmake
@@ -1,5 +1,6 @@
 include(RunCMake)
 
+run_cmake(ContinueAfterError)
 run_cmake(CustomTargetAfterError)
 run_cmake(ErrorLogs)
 run_cmake(FailCopyFileABI)
diff --git a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS-check.cmake b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS-check.cmake
index c350a63..cb48be7 100644
--- a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS-check.cmake
+++ b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS-check.cmake
@@ -15,3 +15,12 @@ if(NOT "${CMAKE_MATCH_0}" MATCHES FORCE)
   set(RunCMake_TEST_FAILED "Expected forced FOO argument")
   return()
 endif()
+
+if(NOT "${_cache}" MATCHES "set\\(TEST_LIST \"A;B;C\".+\\)")
+  set(RunCMake_TEST_FAILED "Cannot find TEST_LIST argument in cache")
+  return()
+endif()
+if(NOT "${CMAKE_MATCH_0}" MATCHES FORCE)
+  set(RunCMake_TEST_FAILED "Expected forced TEST_LIST argument")
+  return()
+endif()
diff --git a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS.cmake b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS.cmake
index 62b1640..1f76fd0 100644
--- a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS.cmake
+++ b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_ARGS.cmake
@@ -5,4 +5,6 @@ include(ExternalProject)
 
 ExternalProject_Add(FOO TMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/tmp"
                         DOWNLOAD_COMMAND ""
-                        CMAKE_CACHE_ARGS "-DFOO:STRING=$<1:BAR>$<0:BAD>")
+                        CMAKE_CACHE_ARGS
+                            "-DFOO:STRING=$<1:BAR>$<0:BAD>"
+                            "-DTEST_LIST:STRING=A;B;C")
diff --git a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS-check.cmake b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS-check.cmake
index aeee11f..c84932d 100644
--- a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS-check.cmake
+++ b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS-check.cmake
@@ -15,3 +15,12 @@ if("${CMAKE_MATCH_0}" MATCHES FORCE)
   set(RunCMake_TEST_FAILED "Expected not forced FOO argument")
   return()
 endif()
+
+if(NOT "${_cache}" MATCHES "set\\(TEST_LIST \"A;B;C\".+\\)")
+  set(RunCMake_TEST_FAILED "Cannot find TEST_LIST argument in cache")
+  return()
+endif()
+if("${CMAKE_MATCH_0}" MATCHES FORCE)
+  set(RunCMake_TEST_FAILED "Expected not forced TEST_LIST argument")
+  return()
+endif()
diff --git a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS.cmake b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS.cmake
index 3a83dbe..1b619c8 100644
--- a/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS.cmake
+++ b/Tests/RunCMake/ExternalProject/CMAKE_CACHE_DEFAULT_ARGS.cmake
@@ -5,4 +5,6 @@ include(ExternalProject)
 
 ExternalProject_Add(FOO TMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/tmp"
                         DOWNLOAD_COMMAND ""
-                        CMAKE_CACHE_DEFAULT_ARGS "-DFOO:STRING=$<1:BAR>$<0:BAD>")
+                        CMAKE_CACHE_DEFAULT_ARGS
+                            "-DFOO:STRING=$<1:BAR>$<0:BAD>"
+                            "-DTEST_LIST:STRING=A;B;C")
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_APPBUNDLE_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_APPBUNDLE_PATH.cmake
index 9d4826f..4a41533 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_APPBUNDLE_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_APPBUNDLE_PATH.cmake
@@ -1,4 +1,4 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
 enable_language(C)
 
 # Prepare environment and variables
@@ -29,10 +29,15 @@ if(NOT DEFINED CMAKE_SYSTEM_NAME
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   else()
-    # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+    # not debian, check the FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS properties
+    get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
     get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-    if(uselib64)
+    if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    else()
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   endif()
 else()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_FRAMEWORK_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_FRAMEWORK_PATH.cmake
index d9943d4..b66d02f 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_FRAMEWORK_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMAKE_FRAMEWORK_PATH.cmake
@@ -1,4 +1,4 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
 enable_language(C)
 
 # Prepare environment and variables
@@ -29,10 +29,15 @@ if(NOT DEFINED CMAKE_SYSTEM_NAME
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   else()
-    # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+    # not debian, check the FIND_LIBRARY_USE_LIB64_PATHS and FIND_LIBRARY_USE_LIB64_PATHS properties
+    get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
     get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-    if(uselib64)
+    if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    else()
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   endif()
 else()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
index 89ce4c6..25a775d 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
@@ -1,6 +1,3 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
-enable_language(C)
-
 # Prepare environment and variables
 set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH FALSE)
 set(CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/pc-foo")
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
index c903279..bdecb8a 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
@@ -1,4 +1,4 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
 enable_language(C)
 
 # Prepare environment and variables
@@ -29,10 +29,15 @@ if(NOT DEFINED CMAKE_SYSTEM_NAME
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   else()
-    # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+    # not debian, check the FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS propertie
+    get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
     get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-    if(uselib64)
+    if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    else()
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   endif()
 else()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
index a52bcbf..df67235 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
@@ -1,4 +1,4 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
 enable_language(C)
 
 # Prepare environment and variables
@@ -29,10 +29,15 @@ if(NOT DEFINED CMAKE_SYSTEM_NAME
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig")
     endif()
   else()
-    # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+    # not debian, check the FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS properties
+    get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
     get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-    if(uselib64)
+    if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig")
+    elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig")
+    else()
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig")
     endif()
   endif()
 else()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
index 2fabe5b..1351b6f 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
@@ -1,4 +1,4 @@
-# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE and FIND_LIBRARY_USE_LIB64_PATHS
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
 enable_language(C)
 
 # Prepare environment and variables
@@ -29,10 +29,15 @@ if(NOT DEFINED CMAKE_SYSTEM_NAME
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   else()
-    # not debian, chech the FIND_LIBRARY_USE_LIB64_PATHS property
+    # not debian, check the FIND_LIBRARY_USE_LIB64_PATHS and FIND_LIBRARY_USE_LIB32_PATHS properties
+    get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
     get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
-    if(uselib64)
+    if(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+    else()
+      set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
     endif()
   endif()
 else()
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/FindPkgConfig/pc-bar/lib32/pkgconfig/.placeholder
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/FindPkgConfig/pc-bar/lib32/pkgconfig/.placeholder
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/FindPkgConfig/pc-foo/lib32/pkgconfig/.placeholder
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/FindPkgConfig/pc-foo/lib32/pkgconfig/.placeholder
diff --git a/Tests/RunCMake/Framework/RunCMakeTest.cmake b/Tests/RunCMake/Framework/RunCMakeTest.cmake
index d810283..eeea6f1 100644
--- a/Tests/RunCMake/Framework/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Framework/RunCMakeTest.cmake
@@ -20,7 +20,7 @@ unset(RunCMake_TEST_OPTIONS)
 
 set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/OSXFrameworkLayout-build)
 set(RunCMake_TEST_NO_CLEAN 1)
-set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/OSX.cmake")
+set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/osx.cmake")
 
 file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
 file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
diff --git a/Tests/RunCMake/GenerateExportHeader/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/CMakeLists.txt
new file mode 100644
index 0000000..dc92486
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/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/GenerateExportHeader/GEH-build-stderr.txt b/Tests/RunCMake/GenerateExportHeader/GEH-build-stderr.txt
new file mode 100644
index 0000000..8d98f9d
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/GEH-build-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/GenerateExportHeader/GEH-failures.cmake b/Tests/RunCMake/GenerateExportHeader/GEH-failures.cmake
new file mode 100644
index 0000000..7182cdf
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/GEH-failures.cmake
@@ -0,0 +1,67 @@
+set(failure_test_executables
+  ${CMAKE_CURRENT_BINARY_DIR}/failure_test_targets)
+file(WRITE ${failure_test_executables} "")
+
+# Check if we should do anything. If the compiler doesn't support hidden
+# visibility, the failure tests won't fail, so just write an empty targets
+# list and punt.
+if(NOT WIN32 AND NOT CYGWIN AND NOT COMPILER_HAS_HIDDEN_VISIBILITY)
+  return()
+endif()
+
+# Read the input source file
+file(READ ${CMAKE_CURRENT_SOURCE_DIR}/exportheader_test.cpp content_post)
+set(content_pre "")
+
+# Generate source files for failure test executables
+set(counter 0)
+while(1)
+  # Find first occurrence of link error marker in remaining content
+  string(REGEX MATCH "//([^;\n]+;) LINK ERROR( [(][^)]+[)])?\n(.*)"
+    match "${content_post}")
+  if(match STREQUAL "")
+    # No more matches
+    break()
+  endif()
+
+  # Shift content buffers and extract failing statement
+  string(LENGTH "${content_post}" content_post_length)
+  string(LENGTH "${match}" matched_length)
+  math(EXPR shift_length "${content_post_length} - ${matched_length}")
+
+  string(SUBSTRING "${content_post}" 0 ${shift_length} shift)
+  set(content_pre "${content_pre}${shift}")
+  set(content_post "${CMAKE_MATCH_3}")
+  set(content_active "//${CMAKE_MATCH_1} LINK ERROR${CMAKE_MATCH_2}")
+  set(statement "${CMAKE_MATCH_1}")
+
+  # Check if potential error is conditional, and evaluate condition if so
+  string(REGEX REPLACE " [(]([^)]+)[)]" "\\1" condition "${CMAKE_MATCH_2}")
+  if(NOT condition STREQUAL "")
+    string(REGEX REPLACE " +" ";" condition "${condition}")
+    if(${condition})
+    else()
+      message(STATUS "Not testing '${statement}'; "
+                     "condition (${condition}) is FALSE")
+      set(content_pre "${content_pre}// link error removed\n")
+      continue()
+    endif()
+  endif()
+
+  if(NOT skip)
+    message(STATUS "Creating failure test for '${statement}'")
+    math(EXPR counter "${counter} + 1")
+
+    # Write new source file
+    set(out ${CMAKE_CURRENT_BINARY_DIR}/exportheader_failtest-${counter}.cpp)
+    file(WRITE ${out} "${content_pre}${statement}\n${content_post}")
+
+    # Add executable for failure test
+    add_executable(GEH-fail-${counter} EXCLUDE_FROM_ALL ${out})
+    target_link_libraries(GEH-fail-${counter} ${link_libraries})
+    file(APPEND ${failure_test_executables} "GEH-fail-${counter}\n")
+  endif()
+
+  # Add placeholder where failing statement was removed
+  set(content_pre "${content_pre}${content_active}\n")
+endwhile()
diff --git a/Tests/RunCMake/GenerateExportHeader/GEH-link-error-result.txt b/Tests/RunCMake/GenerateExportHeader/GEH-link-error-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/GEH-link-error-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/GenerateExportHeader/GEH-link-error-stderr.txt b/Tests/RunCMake/GenerateExportHeader/GEH-link-error-stderr.txt
new file mode 100644
index 0000000..8d98f9d
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/GEH-link-error-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/GenerateExportHeader/GEH.cmake b/Tests/RunCMake/GenerateExportHeader/GEH.cmake
new file mode 100644
index 0000000..cddba29
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/GEH.cmake
@@ -0,0 +1,127 @@
+# Test add_compiler_export_flags without deprecation warning.
+set(CMAKE_WARN_DEPRECATED OFF)
+
+project(GenerateExportHeader)
+
+include(CheckCXXCompilerFlag)
+
+set( CMAKE_INCLUDE_CURRENT_DIR ON )
+
+macro(TEST_FAIL value msg)
+  if (${value})
+    message (SEND_ERROR "Test fail:" "${msg}\n" ${Out} )
+  endif ()
+endmacro()
+
+macro(TEST_PASS value msg)
+  if (NOT ${value})
+    message (SEND_ERROR "Test fail:" "${msg}\n" ${Out} )
+  endif ()
+endmacro()
+
+check_cxx_compiler_flag(-Werror HAS_WERROR_FLAG)
+
+if(HAS_WERROR_FLAG)
+  set(ERROR_FLAG "-Werror")
+else()
+  # MSVC
+  # And intel on windows?
+  # http://software.intel.com/en-us/articles/how-to-handle-warnings-message-in-compiler/?wapkw=%28compiler+warning+message%29
+  check_cxx_compiler_flag("/WX" HAS_WX_FLAG)
+  if(HAS_WX_FLAG)
+    set(ERROR_FLAG "/WX")
+  else()
+    # Sun CC
+    # http://www.acsu.buffalo.edu/~charngda/sunstudio.html
+    check_cxx_compiler_flag("-errwarn=%all" HAS_ERRWARN_ALL)
+    if (HAS_ERRWARN_ALL)
+      set(ERROR_FLAG "-errwarn=%all")
+    else()
+    endif()
+  endif()
+endif()
+
+include(GenerateExportHeader)
+
+set(CMAKE_CXX_STANDARD 98)
+
+# Those versions of the HP compiler that need a flag to get proper C++98
+# template support also need a flag to use the newer C++ library.
+if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
+    CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
+  string(APPEND CMAKE_CXX_FLAGS " -AA")
+endif ()
+
+# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
+if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
+    CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
+  set(CMAKE_CXX_STANDARD 11)
+endif()
+
+add_subdirectory(lib_shared_and_static)
+
+add_compiler_export_flags()
+
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_CURRENT_BINARY_DIR})
+
+message(STATUS "COMPILER_HAS_DEPRECATED: " ${COMPILER_HAS_DEPRECATED})
+message(STATUS "COMPILER_HAS_HIDDEN_VISIBILITY: " ${COMPILER_HAS_HIDDEN_VISIBILITY})
+message(STATUS "WIN32: " ${WIN32})
+message(STATUS "HAS_WERROR_FLAG: " ${HAS_WERROR_FLAG})
+
+set(link_libraries)
+macro(macro_add_test_library name)
+  add_subdirectory(${name})
+  include_directories(${name}
+    ${CMAKE_CURRENT_BINARY_DIR}/${name} # For the export header.
+  )
+  list(APPEND link_libraries ${name})
+endmacro()
+
+macro_add_test_library(libshared)
+macro_add_test_library(libstatic)
+
+add_subdirectory(nodeprecated)
+if(NOT BORLAND)
+  add_subdirectory(c_identifier)
+endif()
+
+if (CMAKE_COMPILER_IS_GNUCXX OR (${CMAKE_CXX_COMPILER_ID} MATCHES Clang))
+  # No need to clutter the test output with warnings.
+  string(APPEND CMAKE_CXX_FLAGS " -Wno-deprecated-declarations")
+endif()
+
+if(MSVC AND COMPILER_HAS_DEPRECATED)
+  add_definitions(/wd4996)
+endif()
+
+add_executable(GenerateExportHeader exportheader_test.cpp)
+
+target_link_libraries(GenerateExportHeader ${link_libraries})
+if (WIN32 OR CYGWIN)
+  if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
+    CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
+    set(_platform Win32-Clang)
+  elseif(MSVC AND COMPILER_HAS_DEPRECATED)
+    set(_platform Win32)
+  elseif((MINGW OR CYGWIN) AND COMPILER_HAS_DEPRECATED)
+    set(_platform MinGW)
+  else()
+    set(_platform WinEmpty)
+  endif()
+elseif(COMPILER_HAS_HIDDEN_VISIBILITY AND USE_COMPILER_HIDDEN_VISIBILITY)
+  set(_platform UNIX)
+elseif(COMPILER_HAS_DEPRECATED)
+  set(_platform UNIX_DeprecatedOnly)
+else()
+  set(_platform Empty)
+endif()
+message(STATUS "Testing reference: ${_platform}")
+target_compile_definitions(GenerateExportHeader
+  PRIVATE
+    "SRC_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/reference/${_platform}\""
+    "BIN_DIR=\"${CMAKE_CURRENT_BINARY_DIR}\""
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/GEH-failures.cmake)
diff --git a/Tests/RunCMake/GenerateExportHeader/RunCMakeTest.cmake b/Tests/RunCMake/GenerateExportHeader/RunCMakeTest.cmake
new file mode 100644
index 0000000..9423ef5
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/RunCMakeTest.cmake
@@ -0,0 +1,27 @@
+include(RunCMake)
+
+function(run_GEH)
+  # Use a single build tree for a few tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/GEH-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  if(RunCMake_GENERATOR MATCHES "Make|Ninja")
+    set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Debug)
+  endif()
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  run_cmake(GEH)
+  run_cmake_command(GEH-build ${CMAKE_COMMAND} --build . --config Debug)
+  run_cmake_command(GEH-run ${RunCMake_TEST_BINARY_DIR}/GenerateExportHeader)
+
+  file(STRINGS "${RunCMake_TEST_BINARY_DIR}/failure_test_targets"
+    failure_test_targets)
+
+  foreach(failure_test_target ${failure_test_targets})
+    run_cmake_command(GEH-link-error ${CMAKE_COMMAND}
+      --build .
+      --config Debug
+      --target ${failure_test_target})
+  endforeach()
+endfunction()
+
+run_GEH()
diff --git a/Tests/RunCMake/GenerateExportHeader/c_identifier/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/c_identifier/CMakeLists.txt
new file mode 100644
index 0000000..77c18e0
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/c_identifier/CMakeLists.txt
@@ -0,0 +1,11 @@
+set(c_identifier_lib_SRCS
+  c_identifier_class.cpp
+)
+
+add_library(7c-identifier-lib++ SHARED c_identifier_class.cpp)
+
+generate_export_header(7c-identifier-lib++)
+
+add_executable(c_identifier_exe main.cpp)
+
+target_link_libraries(c_identifier_exe 7c-identifier-lib++)
diff --git a/Tests/Module/GenerateExportHeader/c_identifier/c_identifier_class.cpp b/Tests/RunCMake/GenerateExportHeader/c_identifier/c_identifier_class.cpp
similarity index 100%
rename from Tests/Module/GenerateExportHeader/c_identifier/c_identifier_class.cpp
rename to Tests/RunCMake/GenerateExportHeader/c_identifier/c_identifier_class.cpp
diff --git a/Tests/Module/GenerateExportHeader/c_identifier/c_identifier_class.h b/Tests/RunCMake/GenerateExportHeader/c_identifier/c_identifier_class.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/c_identifier/c_identifier_class.h
rename to Tests/RunCMake/GenerateExportHeader/c_identifier/c_identifier_class.h
diff --git a/Tests/RunCMake/GenerateExportHeader/c_identifier/main.cpp b/Tests/RunCMake/GenerateExportHeader/c_identifier/main.cpp
new file mode 100644
index 0000000..887d777
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/c_identifier/main.cpp
@@ -0,0 +1,8 @@
+
+#include "c_identifier_class.h"
+
+int main()
+{
+  CIdentifierClass cic;
+  return cic.someMethod();
+}
diff --git a/Tests/RunCMake/GenerateExportHeader/exportheader_test.cpp b/Tests/RunCMake/GenerateExportHeader/exportheader_test.cpp
new file mode 100644
index 0000000..7e3e0e4
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/exportheader_test.cpp
@@ -0,0 +1,169 @@
+
+#include "libshared.h"
+
+#include "libstatic.h"
+
+#include <fstream>
+#include <iostream>
+#include <stdlib.h>
+#include <string>
+
+void compare(const char* refName, const char* testName)
+{
+  std::ifstream ref;
+  ref.open(refName);
+  if (!ref.is_open()) {
+    std::cout << "Could not open \"" << refName << "\"." << std::endl;
+    exit(1);
+  }
+  std::ifstream test;
+  test.open(testName);
+  if (!test.is_open()) {
+    std::cout << "Could not open \"" << testName << "\"." << std::endl;
+    exit(1);
+  }
+
+  while (!ref.eof() && !test.eof()) {
+    std::string refLine;
+    std::string testLine;
+    std::getline(ref, refLine);
+    std::getline(test, testLine);
+    // Some very old Borland runtimes (C++ Builder 5 WITHOUT Update 1) add a
+    // trailing null to the string that we need to strip before testing for a
+    // trailing space.
+    if (refLine.size() && refLine[refLine.size() - 1] == 0) {
+      refLine = refLine.substr(0, refLine.size() - 1);
+    }
+    if (testLine.size() && testLine[testLine.size() - 1] == 0) {
+      testLine = testLine.substr(0, testLine.size() - 1);
+    }
+    // The reference files never have trailing spaces:
+    if (testLine.size() && testLine[testLine.size() - 1] == ' ') {
+      testLine = testLine.substr(0, testLine.size() - 1);
+    }
+    if (refLine != testLine) {
+      std::cout << "Ref and test are not the same:\n  Ref:  \"" << refLine
+                << "\"\n  Test: \"" << testLine << "\"\n";
+      exit(1);
+    }
+  }
+  if (!ref.eof() || !test.eof()) {
+    std::cout << "Ref and test have differing numbers of lines.";
+    exit(1);
+  }
+}
+
+int main()
+{
+  {
+    libshared::Class l;
+    // l.method(); LINK ERROR
+    l.method_exported();
+    // l.method_deprecated(); LINK ERROR
+    l.method_deprecated_exported();
+    // l.method_excluded(); LINK ERROR
+
+    // use_int(l.data); LINK ERROR
+    use_int(l.data_exported);
+    // use_int(l.data_excluded); LINK ERROR
+  }
+
+  {
+    libshared::ExportedClass l;
+    l.method();
+    l.method_deprecated();
+#if defined(_WIN32) || defined(__CYGWIN__)
+    l.method_excluded();
+#else
+// l.method_excluded(); LINK ERROR (NOT WIN32 AND NOT CYGWIN)
+#endif
+
+    use_int(l.data);
+#if defined(_WIN32) || defined(__CYGWIN__)
+    use_int(l.data_excluded);
+#else
+// use_int(l.data_excluded); LINK ERROR (NOT WIN32 AND NOT CYGWIN)
+#endif
+  }
+
+  {
+    libshared::ExcludedClass l;
+    // l.method(); LINK ERROR
+    l.method_exported();
+    // l.method_deprecated(); LINK ERROR
+    l.method_deprecated_exported();
+    // l.method_excluded(); LINK ERROR
+
+    // use_int(l.data); LINK ERROR
+    use_int(l.data_exported);
+    // use_int(l.data_excluded); LINK ERROR
+  }
+
+  // libshared::function(); LINK ERROR
+  libshared::function_exported();
+  // libshared::function_deprecated(); LINK ERROR
+  libshared::function_deprecated_exported();
+  // libshared::function_excluded(); LINK ERROR
+
+  // use_int(libshared::data); LINK ERROR
+  use_int(libshared::data_exported);
+  // use_int(libshared::data_excluded); LINK ERROR
+
+  {
+    libstatic::Class l;
+    l.method();
+    l.method_exported();
+    l.method_deprecated();
+    l.method_deprecated_exported();
+    l.method_excluded();
+
+    use_int(l.data);
+    use_int(l.data_exported);
+    use_int(l.data_excluded);
+  }
+
+  {
+    libstatic::ExportedClass l;
+    l.method();
+    l.method_exported();
+    l.method_deprecated();
+    l.method_deprecated_exported();
+    l.method_excluded();
+
+    use_int(l.data);
+    use_int(l.data_exported);
+    use_int(l.data_excluded);
+  }
+
+  {
+    libstatic::ExcludedClass l;
+    l.method();
+    l.method_exported();
+    l.method_deprecated();
+    l.method_deprecated_exported();
+    l.method_excluded();
+
+    use_int(l.data);
+    use_int(l.data_exported);
+    use_int(l.data_excluded);
+  }
+
+  libstatic::function();
+  libstatic::function_exported();
+  libstatic::function_deprecated();
+  libstatic::function_deprecated_exported();
+  libstatic::function_excluded();
+
+  use_int(libstatic::data);
+  use_int(libstatic::data_exported);
+  use_int(libstatic::data_excluded);
+
+#if defined(SRC_DIR) && defined(BIN_DIR)
+  compare(SRC_DIR "/libshared_export.h",
+          BIN_DIR "/libshared/libshared_export.h");
+  compare(SRC_DIR "/libstatic_export.h",
+          BIN_DIR "/libstatic/libstatic_export.h");
+#endif
+
+  return 0;
+}
diff --git a/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt
new file mode 100644
index 0000000..ff81f35
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt
@@ -0,0 +1,33 @@
+include(GenerateExportHeader)
+
+set(CMAKE_CXX_VISIBILITY_PRESET hidden)
+set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
+
+if (CMAKE_CXX_FLAGS MATCHES "-fvisibility=hidden")
+  message(SEND_ERROR "Do not use add_compiler_export_flags before adding this directory")
+endif()
+if (CMAKE_CXX_FLAGS MATCHES "-fvisibility-inlines-hidden")
+  message(SEND_ERROR "Do not use add_compiler_export_flags before adding this directory")
+endif()
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+set(lib_SRCS
+  libshared_and_static.cpp
+)
+
+add_library(shared_variant SHARED ${lib_SRCS})
+set_target_properties(shared_variant PROPERTIES DEFINE_SYMBOL SHARED_VARIANT_MAKEDLL)
+add_library(static_variant ${lib_SRCS})
+
+set(MY_CUSTOM_CONTENT "#define MY_CUSTOM_CONTENT_ADDED")
+
+generate_export_header(shared_variant
+  BASE_NAME libshared_and_static
+  PREFIX_NAME MYPREFIX_
+  CUSTOM_CONTENT_FROM_VARIABLE MY_CUSTOM_CONTENT
+)
+
+target_compile_definitions(static_variant PUBLIC MYPREFIX_LIBSHARED_AND_STATIC_STATIC_DEFINE)
+
+export(TARGETS shared_variant static_variant FILE Targets.cmake)
diff --git a/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp
new file mode 100644
index 0000000..9ac8381
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp
@@ -0,0 +1,121 @@
+#include "libshared_and_static.h"
+
+#ifndef MY_CUSTOM_CONTENT_ADDED
+#error "MY_CUSTOM_CONTENT_ADDED not defined!"
+#endif
+
+int libshared_and_static::Class::method() const
+{
+  return 0;
+}
+
+int libshared_and_static::Class::method_exported() const
+{
+  return 0;
+}
+
+int libshared_and_static::Class::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared_and_static::Class::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libshared_and_static::Class::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared_and_static::Class::data = 1;
+
+int const libshared_and_static::Class::data_exported = 1;
+
+int const libshared_and_static::Class::data_excluded = 1;
+
+int libshared_and_static::ExportedClass::method() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExportedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExportedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared_and_static::ExportedClass::data = 1;
+
+int const libshared_and_static::ExportedClass::data_excluded = 1;
+
+int libshared_and_static::ExcludedClass::method() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExcludedClass::method_exported() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExcludedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExcludedClass::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libshared_and_static::ExcludedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared_and_static::ExcludedClass::data = 1;
+
+int const libshared_and_static::ExcludedClass::data_exported = 1;
+
+int const libshared_and_static::ExcludedClass::data_excluded = 1;
+
+int libshared_and_static::function()
+{
+  return 0;
+}
+
+int libshared_and_static::function_exported()
+{
+  return 0;
+}
+
+int libshared_and_static::function_deprecated()
+{
+  return 0;
+}
+
+int libshared_and_static::function_deprecated_exported()
+{
+  return 0;
+}
+
+int libshared_and_static::function_excluded()
+{
+  return 0;
+}
+
+int const libshared_and_static::data = 1;
+
+int const libshared_and_static::data_exported = 1;
+
+int const libshared_and_static::data_excluded = 1;
+
+void use_int(int)
+{
+}
diff --git a/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h
new file mode 100644
index 0000000..2c3fcfd
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/lib_shared_and_static/libshared_and_static.h
@@ -0,0 +1,83 @@
+#ifndef LIBSHARED_AND_STATIC_H
+#define LIBSHARED_AND_STATIC_H
+
+#include "libshared_and_static_export.h"
+
+namespace libshared_and_static {
+
+class Class
+{
+public:
+  int method() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT method_exported() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT
+  method_deprecated_exported() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported;
+
+  static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded;
+};
+
+class MYPREFIX_LIBSHARED_AND_STATIC_EXPORT ExportedClass
+{
+public:
+  int method() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded;
+};
+
+class MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT ExcludedClass
+{
+public:
+  int method() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT method_exported() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT
+  method_deprecated_exported() const;
+
+  int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported;
+
+  static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded;
+};
+
+int function();
+
+int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT function_exported();
+
+int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED function_deprecated();
+
+int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT
+function_deprecated_exported();
+
+int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT function_excluded();
+
+extern int const data;
+
+extern int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported;
+
+extern int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded;
+
+} // namespace libshared_and_static
+
+#endif
diff --git a/Tests/RunCMake/GenerateExportHeader/libshared/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/libshared/CMakeLists.txt
new file mode 100644
index 0000000..c4a761c
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libshared/CMakeLists.txt
@@ -0,0 +1,11 @@
+include(GenerateExportHeader)
+
+add_compiler_export_flags()
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+add_library(libshared SHARED libshared.cpp)
+
+generate_export_header(libshared)
+
+export(TARGETS libshared FILE Targets.cmake)
diff --git a/Tests/RunCMake/GenerateExportHeader/libshared/libshared.cpp b/Tests/RunCMake/GenerateExportHeader/libshared/libshared.cpp
new file mode 100644
index 0000000..328ef6f
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libshared/libshared.cpp
@@ -0,0 +1,117 @@
+#include "libshared.h"
+
+int libshared::Class::method() const
+{
+  return 0;
+}
+
+int libshared::Class::method_exported() const
+{
+  return 0;
+}
+
+int libshared::Class::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared::Class::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libshared::Class::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared::Class::data = 1;
+
+int const libshared::Class::data_exported = 1;
+
+int const libshared::Class::data_excluded = 1;
+
+int libshared::ExportedClass::method() const
+{
+  return 0;
+}
+
+int libshared::ExportedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared::ExportedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared::ExportedClass::data = 1;
+
+int const libshared::ExportedClass::data_excluded = 1;
+
+int libshared::ExcludedClass::method() const
+{
+  return 0;
+}
+
+int libshared::ExcludedClass::method_exported() const
+{
+  return 0;
+}
+
+int libshared::ExcludedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libshared::ExcludedClass::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libshared::ExcludedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libshared::ExcludedClass::data = 1;
+
+int const libshared::ExcludedClass::data_exported = 1;
+
+int const libshared::ExcludedClass::data_excluded = 1;
+
+int libshared::function()
+{
+  return 0;
+}
+
+int libshared::function_exported()
+{
+  return 0;
+}
+
+int libshared::function_deprecated()
+{
+  return 0;
+}
+
+int libshared::function_deprecated_exported()
+{
+  return 0;
+}
+
+int libshared::function_excluded()
+{
+  return 0;
+}
+
+int const libshared::data = 1;
+
+int const libshared::data_exported = 1;
+
+int const libshared::data_excluded = 1;
+
+void use_int(int)
+{
+}
diff --git a/Tests/RunCMake/GenerateExportHeader/libshared/libshared.h b/Tests/RunCMake/GenerateExportHeader/libshared/libshared.h
new file mode 100644
index 0000000..6574bd5
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libshared/libshared.h
@@ -0,0 +1,82 @@
+#ifndef LIBSHARED_H
+#define LIBSHARED_H
+
+#include "libshared_export.h"
+
+namespace libshared {
+
+class Class
+{
+public:
+  int method() const;
+
+  int LIBSHARED_EXPORT method_exported() const;
+
+  int LIBSHARED_DEPRECATED method_deprecated() const;
+
+  int LIBSHARED_DEPRECATED_EXPORT method_deprecated_exported() const;
+
+  int LIBSHARED_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSHARED_EXPORT data_exported;
+
+  static int const LIBSHARED_NO_EXPORT data_excluded;
+};
+
+class LIBSHARED_EXPORT ExportedClass
+{
+public:
+  int method() const;
+
+  int LIBSHARED_DEPRECATED method_deprecated() const;
+
+  int LIBSHARED_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSHARED_NO_EXPORT data_excluded;
+};
+
+class LIBSHARED_NO_EXPORT ExcludedClass
+{
+public:
+  int method() const;
+
+  int LIBSHARED_EXPORT method_exported() const;
+
+  int LIBSHARED_DEPRECATED method_deprecated() const;
+
+  int LIBSHARED_DEPRECATED_EXPORT method_deprecated_exported() const;
+
+  int LIBSHARED_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSHARED_EXPORT data_exported;
+
+  static int const LIBSHARED_NO_EXPORT data_excluded;
+};
+
+int function();
+
+int LIBSHARED_EXPORT function_exported();
+
+int LIBSHARED_DEPRECATED function_deprecated();
+
+int LIBSHARED_DEPRECATED_EXPORT function_deprecated_exported();
+
+int LIBSHARED_NO_EXPORT function_excluded();
+
+extern int const data;
+
+extern int const LIBSHARED_EXPORT data_exported;
+
+extern int const LIBSHARED_NO_EXPORT data_excluded;
+
+} // namespace libshared
+
+LIBSHARED_EXPORT void use_int(int);
+
+#endif
diff --git a/Tests/RunCMake/GenerateExportHeader/libstatic/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/libstatic/CMakeLists.txt
new file mode 100644
index 0000000..0fd136c
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libstatic/CMakeLists.txt
@@ -0,0 +1,13 @@
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+include(GenerateExportHeader)
+
+add_compiler_export_flags()
+
+# Show that the export header has no effect on a static library.
+
+add_library(libstatic STATIC libstatic.cpp)
+
+generate_export_header(libstatic)
+
+export(TARGETS libstatic FILE Targets.cmake)
diff --git a/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.cpp b/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.cpp
new file mode 100644
index 0000000..e1d1255
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.cpp
@@ -0,0 +1,125 @@
+#include "libstatic.h"
+
+int libstatic::Class::method() const
+{
+  return 0;
+}
+
+int libstatic::Class::method_exported() const
+{
+  return 0;
+}
+
+int libstatic::Class::method_deprecated() const
+{
+  return 0;
+}
+
+int libstatic::Class::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libstatic::Class::method_excluded() const
+{
+  return 0;
+}
+
+int const libstatic::Class::data = 1;
+
+int const libstatic::Class::data_exported = 1;
+
+int const libstatic::Class::data_excluded = 1;
+
+int libstatic::ExportedClass::method() const
+{
+  return 0;
+}
+
+int libstatic::ExportedClass::method_exported() const
+{
+  return 0;
+}
+
+int libstatic::ExportedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libstatic::ExportedClass::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libstatic::ExportedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libstatic::ExportedClass::data = 1;
+
+int const libstatic::ExportedClass::data_exported = 1;
+
+int const libstatic::ExportedClass::data_excluded = 1;
+
+int libstatic::ExcludedClass::method() const
+{
+  return 0;
+}
+
+int libstatic::ExcludedClass::method_exported() const
+{
+  return 0;
+}
+
+int libstatic::ExcludedClass::method_deprecated() const
+{
+  return 0;
+}
+
+int libstatic::ExcludedClass::method_deprecated_exported() const
+{
+  return 0;
+}
+
+int libstatic::ExcludedClass::method_excluded() const
+{
+  return 0;
+}
+
+int const libstatic::ExcludedClass::data = 1;
+
+int const libstatic::ExcludedClass::data_exported = 1;
+
+int const libstatic::ExcludedClass::data_excluded = 1;
+
+int libstatic::function()
+{
+  return 0;
+}
+
+int libstatic::function_exported()
+{
+  return 0;
+}
+
+int libstatic::function_deprecated()
+{
+  return 0;
+}
+
+int libstatic::function_deprecated_exported()
+{
+  return 0;
+}
+
+int libstatic::function_excluded()
+{
+  return 0;
+}
+
+int const libstatic::data = 1;
+
+int const libstatic::data_exported = 1;
+
+int const libstatic::data_excluded = 1;
diff --git a/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.h b/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.h
new file mode 100644
index 0000000..1017e12
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/libstatic/libstatic.h
@@ -0,0 +1,86 @@
+#ifndef LIBSTATIC_H
+#define LIBSTATIC_H
+
+#include "libstatic_export.h"
+
+namespace libstatic {
+
+class Class
+{
+public:
+  int method() const;
+
+  int LIBSTATIC_EXPORT method_exported() const;
+
+  int LIBSTATIC_DEPRECATED method_deprecated() const;
+
+  int LIBSTATIC_DEPRECATED_EXPORT method_deprecated_exported() const;
+
+  int LIBSTATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSTATIC_EXPORT data_exported;
+
+  static int const LIBSTATIC_NO_EXPORT data_excluded;
+};
+
+class LIBSTATIC_EXPORT ExportedClass
+{
+public:
+  int method() const;
+
+  int LIBSTATIC_EXPORT method_exported() const;
+
+  int LIBSTATIC_DEPRECATED method_deprecated() const;
+
+  int LIBSTATIC_DEPRECATED_EXPORT method_deprecated_exported() const;
+
+  int LIBSTATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSTATIC_EXPORT data_exported;
+
+  static int const LIBSTATIC_NO_EXPORT data_excluded;
+};
+
+class LIBSTATIC_NO_EXPORT ExcludedClass
+{
+public:
+  int method() const;
+
+  int LIBSTATIC_EXPORT method_exported() const;
+
+  int LIBSTATIC_DEPRECATED method_deprecated() const;
+
+  int LIBSTATIC_DEPRECATED_EXPORT method_deprecated_exported() const;
+
+  int LIBSTATIC_NO_EXPORT method_excluded() const;
+
+  static int const data;
+
+  static int const LIBSTATIC_EXPORT data_exported;
+
+  static int const LIBSTATIC_NO_EXPORT data_excluded;
+};
+
+int function();
+
+int LIBSTATIC_EXPORT function_exported();
+
+int LIBSTATIC_DEPRECATED function_deprecated();
+
+int LIBSTATIC_DEPRECATED_EXPORT function_deprecated_exported();
+
+int LIBSTATIC_NO_EXPORT function_excluded();
+
+extern int const data;
+
+extern int const LIBSTATIC_EXPORT data_exported;
+
+extern int const LIBSTATIC_NO_EXPORT data_excluded;
+
+} // namespace libstatic
+
+#endif
diff --git a/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt
new file mode 100644
index 0000000..7822d9c
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt
@@ -0,0 +1,22 @@
+execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined)
+execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined)
+
+configure_file(CMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined/CMakeLists.txt)
+set(DEFINE_NO_DEPRECATED DEFINE_NO_DEPRECATED)
+configure_file(CMakeLists.txt.in ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined/CMakeLists.txt)
+
+try_compile(Result ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined_build
+  ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_not_defined
+  nodeprecated_test
+  OUTPUT_VARIABLE Out
+)
+
+test_pass(Result "Failed to build without no-deprecated define")
+
+try_compile(Result ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined_build
+  ${CMAKE_CURRENT_BINARY_DIR}/nodeprecated_defined
+  nodeprecated_test
+  OUTPUT_VARIABLE Out
+)
+
+test_fail(Result "Built even with no-deprecated define")
diff --git a/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt.in b/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt.in
new file mode 100644
index 0000000..90cfa12
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/nodeprecated/CMakeLists.txt.in
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.6)
+
+project(nodeprecated_test)
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+include(GenerateExportHeader)
+
+add_library(nodeprecatedlib SHARED someclass.cpp)
+
+generate_export_header(nodeprecatedlib @DEFINE_NO_DEPRECATED@)
+
+add_executable(nodeprecatedconsumer main.cpp)
+
+target_link_libraries(nodeprecatedconsumer nodeprecatedlib)
diff --git a/Tests/RunCMake/GenerateExportHeader/nodeprecated/src/main.cpp b/Tests/RunCMake/GenerateExportHeader/nodeprecated/src/main.cpp
new file mode 100644
index 0000000..f90d098
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/nodeprecated/src/main.cpp
@@ -0,0 +1,9 @@
+
+#include "someclass.h"
+
+int main()
+{
+  SomeClass sc;
+  sc.someMethod();
+  return 0;
+}
diff --git a/Tests/Module/GenerateExportHeader/nodeprecated/src/someclass.cpp b/Tests/RunCMake/GenerateExportHeader/nodeprecated/src/someclass.cpp
similarity index 100%
rename from Tests/Module/GenerateExportHeader/nodeprecated/src/someclass.cpp
rename to Tests/RunCMake/GenerateExportHeader/nodeprecated/src/someclass.cpp
diff --git a/Tests/Module/GenerateExportHeader/nodeprecated/src/someclass.h b/Tests/RunCMake/GenerateExportHeader/nodeprecated/src/someclass.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/nodeprecated/src/someclass.h
rename to Tests/RunCMake/GenerateExportHeader/nodeprecated/src/someclass.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Empty/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Empty/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Empty/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Empty/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Empty/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Empty/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Empty/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Empty/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/MinGW/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/MinGW/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/MinGW/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/MinGW/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/MinGW/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/MinGW/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/MinGW/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/MinGW/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/UNIX/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/UNIX/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/UNIX/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/UNIX/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/UNIX/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/UNIX/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/UNIX/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/UNIX/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/UNIX_DeprecatedOnly/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Win32-Clang/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Win32-Clang/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Win32-Clang/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Win32-Clang/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Win32-Clang/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Win32-Clang/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Win32-Clang/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Win32-Clang/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Win32/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Win32/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Win32/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Win32/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/Win32/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/Win32/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/Win32/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/Win32/libstatic_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/WinEmpty/libshared_export.h b/Tests/RunCMake/GenerateExportHeader/reference/WinEmpty/libshared_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/WinEmpty/libshared_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/WinEmpty/libshared_export.h
diff --git a/Tests/Module/GenerateExportHeader/reference/WinEmpty/libstatic_export.h b/Tests/RunCMake/GenerateExportHeader/reference/WinEmpty/libstatic_export.h
similarity index 100%
rename from Tests/Module/GenerateExportHeader/reference/WinEmpty/libstatic_export.h
rename to Tests/RunCMake/GenerateExportHeader/reference/WinEmpty/libstatic_export.h
diff --git a/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-result.txt b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-stderr.txt b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-stderr.txt
new file mode 100644
index 0000000..cded130
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at LINK_ONLY-not-linking.cmake:1 \(add_custom_target\):
+  Error evaluating generator expression:
+
+    \$<LINK_ONLY:something>
+
+  \$<LINK_ONLY:...> may only be used for linking
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking.cmake b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking.cmake
new file mode 100644
index 0000000..16db0a2
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/LINK_ONLY-not-linking.cmake
@@ -0,0 +1 @@
+add_custom_target(Custom ALL COMMAND ${CMAKE_COMMAND} -E echo $<LINK_ONLY:something>)
diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
index 625bab2..f5584d5 100644
--- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
@@ -29,6 +29,7 @@ run_cmake(COMPILE_LANGUAGE-unknown-lang)
 run_cmake(TARGET_FILE-recursion)
 run_cmake(OUTPUT_NAME-recursion)
 run_cmake(TARGET_PROPERTY-LOCATION)
+run_cmake(LINK_ONLY-not-linking)
 
 run_cmake(ImportedTarget-TARGET_PDB_FILE)
 if(LINKER_SUPPORTS_PDB)
diff --git a/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake
index 4d0a0a1..27250cb 100644
--- a/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake
@@ -3,7 +3,7 @@ include(RunCMake)
 set(RunCMake_GENERATOR_PLATFORM "")
 run_cmake(NoPlatform)
 
-if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
+if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[01245])( 20[0-9][0-9])?$")
   set(RunCMake_GENERATOR_PLATFORM "x64")
   run_cmake(x64Platform)
 else()
@@ -17,7 +17,7 @@ set(RunCMake_TEST_OPTIONS -A "Extra Platform")
 run_cmake(TwoPlatforms)
 unset(RunCMake_TEST_OPTIONS)
 
-if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
+if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[01245])( 20[0-9][0-9])?$")
   set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/TestPlatform-toolchain.cmake)
   run_cmake(TestPlatformToolchain)
   unset(RunCMake_TEST_OPTIONS)
diff --git a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
index 6220657..283a2a0 100644
--- a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
@@ -3,7 +3,7 @@ include(RunCMake)
 set(RunCMake_GENERATOR_TOOLSET "")
 run_cmake(NoToolset)
 
-if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[0124]|Xcode" AND NOT XCODE_BELOW_3)
+if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[01245]|Xcode" AND NOT XCODE_BELOW_3)
   set(RunCMake_GENERATOR_TOOLSET "Test Toolset")
   run_cmake(TestToolset)
 else()
@@ -17,7 +17,7 @@ set(RunCMake_TEST_OPTIONS -T "Extra Toolset")
 run_cmake(TwoToolsets)
 unset(RunCMake_TEST_OPTIONS)
 
-if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[0124]|Xcode" AND NOT XCODE_BELOW_3)
+if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[01245]|Xcode" AND NOT XCODE_BELOW_3)
   set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/TestToolset-toolchain.cmake)
   run_cmake(TestToolsetToolchain)
   unset(RunCMake_TEST_OPTIONS)
diff --git a/Tests/RunCMake/LinkWhatYouUse/C-Build-stdout.txt b/Tests/RunCMake/LinkWhatYouUse/C-Build-stdout.txt
new file mode 100644
index 0000000..95eafad
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/C-Build-stdout.txt
@@ -0,0 +1,2 @@
+.*Warning: Unused direct dependencies.*
+.*libm.*
diff --git a/Tests/RunCMake/LinkWhatYouUse/C-launch-Build-stdout.txt b/Tests/RunCMake/LinkWhatYouUse/C-launch-Build-stdout.txt
new file mode 100644
index 0000000..95eafad
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/C-launch-Build-stdout.txt
@@ -0,0 +1,2 @@
+.*Warning: Unused direct dependencies.*
+.*libm.*
diff --git a/Tests/RunCMake/LinkWhatYouUse/C-launch.cmake b/Tests/RunCMake/LinkWhatYouUse/C-launch.cmake
new file mode 100644
index 0000000..e66ca20
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/C-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(C.cmake)
diff --git a/Tests/RunCMake/LinkWhatYouUse/C.cmake b/Tests/RunCMake/LinkWhatYouUse/C.cmake
new file mode 100644
index 0000000..4c3f428
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/C.cmake
@@ -0,0 +1,4 @@
+enable_language(C)
+set(CMAKE_LINK_WHAT_YOU_USE TRUE)
+add_executable(main main.c)
+target_link_libraries(main m)
diff --git a/Tests/RunCMake/LinkWhatYouUse/CMakeLists.txt b/Tests/RunCMake/LinkWhatYouUse/CMakeLists.txt
new file mode 100644
index 0000000..18dfd26
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.2)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/LinkWhatYouUse/CXX-Build-stdout.txt b/Tests/RunCMake/LinkWhatYouUse/CXX-Build-stdout.txt
new file mode 100644
index 0000000..95eafad
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/CXX-Build-stdout.txt
@@ -0,0 +1,2 @@
+.*Warning: Unused direct dependencies.*
+.*libm.*
diff --git a/Tests/RunCMake/LinkWhatYouUse/CXX-launch-Build-stdout.txt b/Tests/RunCMake/LinkWhatYouUse/CXX-launch-Build-stdout.txt
new file mode 100644
index 0000000..95eafad
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/CXX-launch-Build-stdout.txt
@@ -0,0 +1,2 @@
+.*Warning: Unused direct dependencies.*
+.*libm.*
diff --git a/Tests/RunCMake/LinkWhatYouUse/CXX-launch.cmake b/Tests/RunCMake/LinkWhatYouUse/CXX-launch.cmake
new file mode 100644
index 0000000..3002c9d
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/CXX-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CXX.cmake)
diff --git a/Tests/RunCMake/LinkWhatYouUse/CXX.cmake b/Tests/RunCMake/LinkWhatYouUse/CXX.cmake
new file mode 100644
index 0000000..9555832
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/CXX.cmake
@@ -0,0 +1,4 @@
+enable_language(CXX)
+set(CMAKE_LINK_WHAT_YOU_USE TRUE)
+add_executable(main main.cxx)
+target_link_libraries(main m)
diff --git a/Tests/RunCMake/LinkWhatYouUse/RunCMakeTest.cmake b/Tests/RunCMake/LinkWhatYouUse/RunCMakeTest.cmake
new file mode 100644
index 0000000..897f568
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/RunCMakeTest.cmake
@@ -0,0 +1,21 @@
+include(RunCMake)
+
+
+function(run_lwyu 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_lwyu(CXX)
+run_lwyu(C)
+if (NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
+  run_lwyu(C-launch)
+  run_lwyu(CXX-launch)
+endif()
diff --git a/Tests/RunCMake/try_compile/src.c b/Tests/RunCMake/LinkWhatYouUse/main.c
similarity index 100%
copy from Tests/RunCMake/try_compile/src.c
copy to Tests/RunCMake/LinkWhatYouUse/main.c
diff --git a/Tests/RunCMake/LinkWhatYouUse/main.cxx b/Tests/RunCMake/LinkWhatYouUse/main.cxx
new file mode 100644
index 0000000..f8b643a
--- /dev/null
+++ b/Tests/RunCMake/LinkWhatYouUse/main.cxx
@@ -0,0 +1,4 @@
+int main()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-result.txt b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-stderr.txt b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-stderr.txt
new file mode 100644
index 0000000..74d62a4
--- /dev/null
+++ b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at CustomCommandDepfile-ERROR.cmake:1 \(add_custom_command\):
+  add_custom_command Option DEPFILE not supported by [^
+]+
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/Make/CustomCommandDepfile-ERROR.cmake b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR.cmake
new file mode 100644
index 0000000..bad7955
--- /dev/null
+++ b/Tests/RunCMake/Make/CustomCommandDepfile-ERROR.cmake
@@ -0,0 +1,8 @@
+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}"
+  DEPFILE "test.d"
+  )
diff --git a/Tests/RunCMake/Make/RunCMakeTest.cmake b/Tests/RunCMake/Make/RunCMakeTest.cmake
index c6bbd03..869d11e 100644
--- a/Tests/RunCMake/Make/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Make/RunCMakeTest.cmake
@@ -15,3 +15,5 @@ run_TargetMessages(OFF)
 
 run_TargetMessages(VAR-ON -DCMAKE_TARGET_MESSAGES=ON)
 run_TargetMessages(VAR-OFF -DCMAKE_TARGET_MESSAGES=OFF)
+
+run_cmake(CustomCommandDepfile-ERROR)
diff --git a/Tests/RunCMake/Ninja/CustomCommandDepfile-check.cmake b/Tests/RunCMake/Ninja/CustomCommandDepfile-check.cmake
new file mode 100644
index 0000000..189de64
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CustomCommandDepfile-check.cmake
@@ -0,0 +1,5 @@
+set(log "${RunCMake_BINARY_DIR}/CustomCommandDepfile-build/build.ninja")
+file(READ "${log}" build_file)
+if(NOT "${build_file}" MATCHES "depfile = test\\.d")
+  set(RunCMake_TEST_FAILED "Log file:\n ${log}\ndoes not have expected line: depfile = test.d")
+endif()
diff --git a/Tests/RunCMake/Ninja/CustomCommandDepfile.cmake b/Tests/RunCMake/Ninja/CustomCommandDepfile.cmake
new file mode 100644
index 0000000..dbef2a5
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CustomCommandDepfile.cmake
@@ -0,0 +1,11 @@
+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}"
+  DEPFILE "test.d"
+  )
+add_custom_target(copy ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/hello.copy.c")
+
+include(CheckNoPrefixSubDir.cmake)
diff --git a/Tests/RunCMake/Ninja/RunCMakeTest.cmake b/Tests/RunCMake/Ninja/RunCMakeTest.cmake
index c73f852..778f2c1 100644
--- a/Tests/RunCMake/Ninja/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Ninja/RunCMakeTest.cmake
@@ -32,6 +32,8 @@ run_CMP0058(WARN-by)
 run_CMP0058(NEW-no)
 run_CMP0058(NEW-by)
 
+run_cmake(CustomCommandDepfile)
+
 function(run_SubDir)
   # Use a single build tree for a few tests without cleaning.
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/SubDir-build)
@@ -41,10 +43,16 @@ function(run_SubDir)
   run_cmake(SubDir)
   if(WIN32)
     set(SubDir_all [[SubDir\all]])
+    set(SubDir_test [[SubDir\test]])
+    set(SubDir_install [[SubDir\install]])
   else()
     set(SubDir_all [[SubDir/all]])
+    set(SubDir_test [[SubDir/test]])
+    set(SubDir_install [[SubDir/install]])
   endif()
   run_cmake_command(SubDir-build ${CMAKE_COMMAND} --build . --target ${SubDir_all})
+  run_cmake_command(SubDir-test ${CMAKE_COMMAND} --build . --target ${SubDir_test})
+  run_cmake_command(SubDir-install ${CMAKE_COMMAND} --build . --target ${SubDir_install})
 endfunction()
 run_SubDir()
 
diff --git a/Tests/RunCMake/Ninja/SubDir-install-stdout.txt b/Tests/RunCMake/Ninja/SubDir-install-stdout.txt
new file mode 100644
index 0000000..4261b0e
--- /dev/null
+++ b/Tests/RunCMake/Ninja/SubDir-install-stdout.txt
@@ -0,0 +1 @@
+-- Installing SubDir
diff --git a/Tests/RunCMake/Ninja/SubDir-test-stdout.txt b/Tests/RunCMake/Ninja/SubDir-test-stdout.txt
new file mode 100644
index 0000000..9c493ac
--- /dev/null
+++ b/Tests/RunCMake/Ninja/SubDir-test-stdout.txt
@@ -0,0 +1 @@
+1/1 Test #1: SubDirTest
diff --git a/Tests/RunCMake/Ninja/SubDir.cmake b/Tests/RunCMake/Ninja/SubDir.cmake
index 7224ec3..d227753 100644
--- a/Tests/RunCMake/Ninja/SubDir.cmake
+++ b/Tests/RunCMake/Ninja/SubDir.cmake
@@ -1,2 +1,7 @@
+include(CTest)
 add_subdirectory(SubDir)
 add_custom_target(TopFail ALL COMMAND does_not_exist)
+add_test(NAME TopTest COMMAND ${CMAKE_COMMAND} -E echo "Running TopTest")
+install(CODE [[
+  message(FATAL_ERROR "Installing Top")
+]])
diff --git a/Tests/RunCMake/Ninja/SubDir/CMakeLists.txt b/Tests/RunCMake/Ninja/SubDir/CMakeLists.txt
index 73ae431..456c1db 100644
--- a/Tests/RunCMake/Ninja/SubDir/CMakeLists.txt
+++ b/Tests/RunCMake/Ninja/SubDir/CMakeLists.txt
@@ -1,2 +1,6 @@
 add_custom_target(SubFail COMMAND does_not_exist)
 add_custom_target(InAll ALL COMMAND ${CMAKE_COMMAND} -E echo "Building InAll")
+add_test(NAME SubDirTest COMMAND ${CMAKE_COMMAND} -E echo "Running SubDirTest")
+install(CODE [[
+  message(STATUS "Installing SubDir")
+]])
diff --git a/Tests/RunCMake/RunCMake.cmake b/Tests/RunCMake/RunCMake.cmake
index fa0c980..247855a 100644
--- a/Tests/RunCMake/RunCMake.cmake
+++ b/Tests/RunCMake/RunCMake.cmake
@@ -95,7 +95,7 @@ function(run_cmake test)
   endif()
   set(msg "")
   if(NOT "${actual_result}" MATCHES "${expect_result}")
-    set(msg "${msg}Result is [${actual_result}], not [${expect_result}].\n")
+    string(APPEND msg "Result is [${actual_result}], not [${expect_result}].\n")
   endif()
   foreach(o out err)
     string(REGEX REPLACE "\r\n" "\n" actual_std${o} "${actual_std${o}}")
@@ -107,7 +107,7 @@ function(run_cmake test)
         string(REGEX REPLACE "\n" "\n expect-${o}> " expect_${o}
           " expect-${o}> ${expect_std${o}}")
         set(expect_${o} "Expected std${o} to match:\n${expect_${o}}\n")
-        set(msg "${msg}std${o} does not match that expected.\n")
+        string(APPEND msg "std${o} does not match that expected.\n")
       endif()
     endif()
   endforeach()
@@ -122,7 +122,7 @@ function(run_cmake test)
   endif()
   if(msg AND RunCMake_TEST_COMMAND)
     string(REPLACE ";" "\" \"" command "\"${RunCMake_TEST_COMMAND}\"")
-    set(msg "${msg}Command was:\n command> ${command}\n")
+    string(APPEND msg "Command was:\n command> ${command}\n")
   endif()
   if(msg)
     string(REGEX REPLACE "\n" "\n actual-out> " actual_out " actual-out> ${actual_stdout}")
diff --git a/Tests/RunCMake/Syntax/BOM-UTF-16-BE-stderr.txt b/Tests/RunCMake/Syntax/BOM-UTF-16-BE-stderr.txt
index a845ffb..f0b6783 100644
--- a/Tests/RunCMake/Syntax/BOM-UTF-16-BE-stderr.txt
+++ b/Tests/RunCMake/Syntax/BOM-UTF-16-BE-stderr.txt
@@ -1,8 +1,4 @@
 CMake Error in BOM-UTF-16-BE.cmake:
-  File
-
-    .*/Tests/RunCMake/Syntax/BOM-UTF-16-BE.cmake
-
-  starts with a Byte-Order-Mark that is not UTF-8.
+  File starts with a Byte-Order-Mark that is not UTF-8.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/BOM-UTF-16-LE-stderr.txt b/Tests/RunCMake/Syntax/BOM-UTF-16-LE-stderr.txt
index cc4244b..bcc9c38 100644
--- a/Tests/RunCMake/Syntax/BOM-UTF-16-LE-stderr.txt
+++ b/Tests/RunCMake/Syntax/BOM-UTF-16-LE-stderr.txt
@@ -1,8 +1,4 @@
 CMake Error in BOM-UTF-16-LE.cmake:
-  File
-
-    .*/Tests/RunCMake/Syntax/BOM-UTF-16-LE.cmake
-
-  starts with a Byte-Order-Mark that is not UTF-8.
+  File starts with a Byte-Order-Mark that is not UTF-8.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/BOM-UTF-32-BE-stderr.txt b/Tests/RunCMake/Syntax/BOM-UTF-32-BE-stderr.txt
index 5f851bf..7bd74c9 100644
--- a/Tests/RunCMake/Syntax/BOM-UTF-32-BE-stderr.txt
+++ b/Tests/RunCMake/Syntax/BOM-UTF-32-BE-stderr.txt
@@ -1,8 +1,4 @@
 CMake Error in BOM-UTF-32-BE.cmake:
-  File
-
-    .*/Tests/RunCMake/Syntax/BOM-UTF-32-BE.cmake
-
-  starts with a Byte-Order-Mark that is not UTF-8.
+  File starts with a Byte-Order-Mark that is not UTF-8.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/BOM-UTF-32-LE-stderr.txt b/Tests/RunCMake/Syntax/BOM-UTF-32-LE-stderr.txt
index d8fafd0..678013f 100644
--- a/Tests/RunCMake/Syntax/BOM-UTF-32-LE-stderr.txt
+++ b/Tests/RunCMake/Syntax/BOM-UTF-32-LE-stderr.txt
@@ -1,8 +1,4 @@
 CMake Error in BOM-UTF-32-LE.cmake:
-  File
-
-    .*/Tests/RunCMake/Syntax/BOM-UTF-32-LE.cmake
-
-  starts with a Byte-Order-Mark that is not UTF-8.
+  File starts with a Byte-Order-Mark that is not UTF-8.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/BracketComment4-stderr.txt b/Tests/RunCMake/Syntax/BracketComment4-stderr.txt
index 8ba32c2..6bbb980 100644
--- a/Tests/RunCMake/Syntax/BracketComment4-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketComment4-stderr.txt
@@ -1,7 +1,4 @@
-CMake Error: Error in cmake code at
-.*/Tests/RunCMake/Syntax/BracketComment4.cmake:3:
-Parse error.  Expected a newline, got identifier with text "message".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
-
-    BracketComment4.cmake
+CMake Error at BracketComment4.cmake:3:
+  Parse error.  Expected a newline, got identifier with text "message".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace0-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace0-stderr.txt
index a288280..0a52022 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace0-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace0-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace0.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace0.cmake:1:27
+CMake Error at BracketNoSpace0.cmake:1:
+  Syntax Error in cmake code at column 27
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace1-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace1-stderr.txt
index 391e11b..43bf995 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace1-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace1-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace1.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace1.cmake:1:24
+CMake Error at BracketNoSpace1.cmake:1:
+  Syntax Error in cmake code at column 24
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace2-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace2-stderr.txt
index acaf7fe..f78b4bd 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace2-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace2-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace2.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace2.cmake:1:44
+CMake Error at BracketNoSpace2.cmake:1:
+  Syntax Error in cmake code at column 44
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace3-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace3-stderr.txt
index f12b2e5..63ca600 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace3-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace3-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace3.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace3.cmake:1:45
+CMake Error at BracketNoSpace3.cmake:1:
+  Syntax Error in cmake code at column 45
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace4-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace4-stderr.txt
index 7157763..318b0e3 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace4-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace4-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace4.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace4.cmake:1:44
+CMake Error at BracketNoSpace4.cmake:1:
+  Syntax Error in cmake code at column 44
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/BracketNoSpace5-stderr.txt b/Tests/RunCMake/Syntax/BracketNoSpace5-stderr.txt
index c13969d..a68478a 100644
--- a/Tests/RunCMake/Syntax/BracketNoSpace5-stderr.txt
+++ b/Tests/RunCMake/Syntax/BracketNoSpace5-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error in BracketNoSpace5.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/BracketNoSpace5.cmake:1:45
+CMake Error at BracketNoSpace5.cmake:1:
+  Syntax Error in cmake code at column 45
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/CommandEOF-result.txt b/Tests/RunCMake/Syntax/CommandEOF-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CommandEOF-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Syntax/CommandEOF-stderr.txt b/Tests/RunCMake/Syntax/CommandEOF-stderr.txt
new file mode 100644
index 0000000..31cbc08
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CommandEOF-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error in CommandEOF.cmake:
+  Unexpected end of file.
+
+  Parse error.  Function missing opening "\(".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/Syntax/CommandEOF.cmake b/Tests/RunCMake/Syntax/CommandEOF.cmake
new file mode 100644
index 0000000..36ebb02
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CommandEOF.cmake
@@ -0,0 +1 @@
+message
\ No newline at end of file
diff --git a/Tests/RunCMake/Syntax/CommandError0-stderr.txt b/Tests/RunCMake/Syntax/CommandError0-stderr.txt
index 24d7997..e584fb0 100644
--- a/Tests/RunCMake/Syntax/CommandError0-stderr.txt
+++ b/Tests/RunCMake/Syntax/CommandError0-stderr.txt
@@ -1,8 +1,6 @@
-CMake Error: Error in cmake code at
-.*/Tests/RunCMake/Syntax/CommandError0.cmake:2:
-Parse error.  Expected "\(", got newline with text "
-".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
+CMake Error at CommandError0.cmake:2:
+  Parse error.  Expected "\(", got newline with text "
 
-    CommandError0.cmake
+  ".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/CommandError1-stderr.txt b/Tests/RunCMake/Syntax/CommandError1-stderr.txt
index 599f600..c3bf93c 100644
--- a/Tests/RunCMake/Syntax/CommandError1-stderr.txt
+++ b/Tests/RunCMake/Syntax/CommandError1-stderr.txt
@@ -1,7 +1,4 @@
-CMake Error: Error in cmake code at
-.*/Tests/RunCMake/Syntax/CommandError1.cmake:1:
-Parse error.  Expected a newline, got identifier with text "message".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
-
-    CommandError1.cmake
+CMake Error at CommandError1.cmake:1:
+  Parse error.  Expected a newline, got identifier with text "message".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/CommandError2-stderr.txt b/Tests/RunCMake/Syntax/CommandError2-stderr.txt
index f4dfc77..4fe28a9 100644
--- a/Tests/RunCMake/Syntax/CommandError2-stderr.txt
+++ b/Tests/RunCMake/Syntax/CommandError2-stderr.txt
@@ -1,7 +1,5 @@
-CMake Error: Error in cmake code at
-.*/Tests/RunCMake/Syntax/CommandError2.cmake:1:
-Parse error.  Expected a command name, got bracket argument with text "oops-not-a-comment".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
-
-    CommandError2.cmake
+CMake Error at CommandError2.cmake:1:
+  Parse error.  Expected a command name, got bracket argument with text
+  "oops-not-a-comment".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/ParenInENV-stderr.txt b/Tests/RunCMake/Syntax/ParenInENV-stderr.txt
index 37c5d6e..d7861e2 100644
--- a/Tests/RunCMake/Syntax/ParenInENV-stderr.txt
+++ b/Tests/RunCMake/Syntax/ParenInENV-stderr.txt
@@ -1,7 +1,5 @@
-CMake Warning \(dev\) in ParenInENV.cmake:
-  Syntax Warning in cmake code at
-
-    .*/Tests/RunCMake/Syntax/ParenInENV.cmake:2:21
+CMake Warning \(dev\) at ParenInENV.cmake:2:
+  Syntax Warning in cmake code at column 21
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
@@ -11,7 +9,7 @@ This warning is for project developers.  Use -Wno-dev to suppress it.
 CMake Error at ParenInENV.cmake:2 \(message\):
   Syntax error in cmake code at
 
-    .*/Tests/RunCMake/Syntax/ParenInENV.cmake:2
+    .*Tests/RunCMake/Syntax/ParenInENV.cmake:2
 
   when parsing string
 
diff --git a/Tests/RunCMake/Syntax/ParenNoSpace1-stderr.txt b/Tests/RunCMake/Syntax/ParenNoSpace1-stderr.txt
index 45b2e6a..7958249 100644
--- a/Tests/RunCMake/Syntax/ParenNoSpace1-stderr.txt
+++ b/Tests/RunCMake/Syntax/ParenNoSpace1-stderr.txt
@@ -1,27 +1,21 @@
-CMake Warning \(dev\) in ParenNoSpace1.cmake:
-  Syntax Warning in cmake code at
-
-    .*/Tests/RunCMake/Syntax/ParenNoSpace1.cmake:1:26
+CMake Warning \(dev\) at ParenNoSpace1.cmake:1:
+  Syntax Warning in cmake code at column 26
 
   Argument not separated from preceding token by whitespace.
 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\) in ParenNoSpace1.cmake:
-  Syntax Warning in cmake code at
-
-    .*/Tests/RunCMake/Syntax/ParenNoSpace1.cmake:2:26
+CMake Warning \(dev\) at ParenNoSpace1.cmake:2:
+  Syntax Warning in cmake code at column 26
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
 This warning is for project developers.  Use -Wno-dev to suppress it.
 
-CMake Error in ParenNoSpace1.cmake:
-  Syntax Error in cmake code at
-
-    .*/Tests/RunCMake/Syntax/ParenNoSpace1.cmake:3:29
+CMake Error at ParenNoSpace1.cmake:3:
+  Syntax Error in cmake code at column 29
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/RunCMakeTest.cmake b/Tests/RunCMake/Syntax/RunCMakeTest.cmake
index fd012b9..d1fbb16 100644
--- a/Tests/RunCMake/Syntax/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Syntax/RunCMakeTest.cmake
@@ -17,6 +17,7 @@ run_cmake(CommandSpaces)
 run_cmake(CommandTabs)
 run_cmake(CommandNewlines)
 run_cmake(CommandComments)
+run_cmake(CommandEOF)
 run_cmake(CommandError0)
 run_cmake(CommandError1)
 run_cmake(CommandError2)
diff --git a/Tests/RunCMake/Syntax/StringNoSpace-stderr.txt b/Tests/RunCMake/Syntax/StringNoSpace-stderr.txt
index a4ec6e7..817fcfa 100644
--- a/Tests/RunCMake/Syntax/StringNoSpace-stderr.txt
+++ b/Tests/RunCMake/Syntax/StringNoSpace-stderr.txt
@@ -1,17 +1,13 @@
-CMake Warning \(dev\) in StringNoSpace.cmake:
-  Syntax Warning in cmake code at
-
-    .*/Tests/RunCMake/Syntax/StringNoSpace.cmake:2:28
+CMake Warning \(dev\) at StringNoSpace.cmake:2:
+  Syntax Warning in cmake code at column 28
 
   Argument not separated from preceding token by whitespace.
 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\) in StringNoSpace.cmake:
-  Syntax Warning in cmake code at
-
-    .*/Tests/RunCMake/Syntax/StringNoSpace.cmake:2:31
+CMake Warning \(dev\) at StringNoSpace.cmake:2:
+  Syntax Warning in cmake code at column 31
 
   Argument not separated from preceding token by whitespace.
 Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/Syntax/UnterminatedBracket0-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedBracket0-stderr.txt
index 3559c18..de33f7d 100644
--- a/Tests/RunCMake/Syntax/UnterminatedBracket0-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedBracket0-stderr.txt
@@ -1,8 +1,7 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedBracket0.cmake:2:
-Parse error.  Function missing ending "\)".  Instead found unterminated bracket with text "\)
-".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
+CMake Error at UnterminatedBracket0.cmake:2:
+  Parse error.  Function missing ending "\)".  Instead found unterminated
+  bracket with text "\)
 
-    UnterminatedBracket0.cmake$
+  ".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/UnterminatedBracket1-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedBracket1-stderr.txt
index 55d458b..86bfa2a 100644
--- a/Tests/RunCMake/Syntax/UnterminatedBracket1-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedBracket1-stderr.txt
@@ -1,8 +1,7 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedBracket1.cmake:2:
-Parse error.  Function missing ending "\)".  Instead found unterminated bracket with text "\]\]\)
-".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
+CMake Error at UnterminatedBracket1.cmake:2:
+  Parse error.  Function missing ending "\)".  Instead found unterminated
+  bracket with text "]]\)
 
-    UnterminatedBracket1.cmake$
+  ".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/UnterminatedBracketComment-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedBracketComment-stderr.txt
index 0a799eb..4ec78a1 100644
--- a/Tests/RunCMake/Syntax/UnterminatedBracketComment-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedBracketComment-stderr.txt
@@ -1,8 +1,7 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedBracketComment.cmake:1:
-Parse error.  Expected a command name, got unterminated bracket with text "#\]\]
-".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
+CMake Error at UnterminatedBracketComment.cmake:3:
+  Parse error.  Expected a command name, got unterminated bracket with text
+  "#]]
 
-    UnterminatedBracketComment.cmake
+  ".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/UnterminatedCall1-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedCall1-stderr.txt
index 281ce0d..3f52244 100644
--- a/Tests/RunCMake/Syntax/UnterminatedCall1-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedCall1-stderr.txt
@@ -1,7 +1,4 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedCall1.cmake:2:
-Parse error.  Function missing ending "\)".  End of file reached.
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
-
-    UnterminatedCall1.cmake
+CMake Error at UnterminatedCall1.cmake:2:
+  Parse error.  Function missing ending "\)".  End of file reached.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/UnterminatedCall2-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedCall2-stderr.txt
index 065de30..18656f7 100644
--- a/Tests/RunCMake/Syntax/UnterminatedCall2-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedCall2-stderr.txt
@@ -1,7 +1,4 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedCall2.cmake:4:
-Parse error.  Function missing ending "\)".  End of file reached.
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
-
-    UnterminatedCall2.cmake
+CMake Error at UnterminatedCall2.cmake:4:
+  Parse error.  Function missing ending "\)".  End of file reached.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/UnterminatedString-stderr.txt b/Tests/RunCMake/Syntax/UnterminatedString-stderr.txt
index d925032..79c3fd2 100644
--- a/Tests/RunCMake/Syntax/UnterminatedString-stderr.txt
+++ b/Tests/RunCMake/Syntax/UnterminatedString-stderr.txt
@@ -1,8 +1,7 @@
-CMake Error: Error in cmake code at
-.*/Syntax/UnterminatedString.cmake:2:
-Parse error.  Function missing ending "\)".  Instead found unterminated string with text "\)
-".
-CMake Error at CMakeLists.txt:3 \(include\):
-  include could not find load file:
+CMake Error at UnterminatedString.cmake:2:
+  Parse error.  Function missing ending "\)".  Instead found unterminated
+  string with text "\)
 
-    UnterminatedString.cmake$
+  ".
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/ToolchainFile/FlagsInit-stdout.txt b/Tests/RunCMake/ToolchainFile/FlagsInit-stdout.txt
new file mode 100644
index 0000000..e18aa8c
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/FlagsInit-stdout.txt
@@ -0,0 +1,30 @@
+-- CMAKE_C_FLAGS='[^
+]*-DMY_FLAGS_INIT[^
+]*'
+-- CMAKE_C_FLAGS_DEBUG='[^
+]*-DMY_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_C_FLAGS_RELEASE='[^
+]*-DMY_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_C_FLAGS_MINSIZEREL='[^
+]*-DMY_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_C_FLAGS_RELWITHDEBINFO='[^
+]*-DMY_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
+-- CMAKE_CXX_FLAGS='[^
+]*-DMY_FLAGS_INIT[^
+]*'
+-- CMAKE_CXX_FLAGS_DEBUG='[^
+]*-DMY_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_CXX_FLAGS_RELEASE='[^
+]*-DMY_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_CXX_FLAGS_MINSIZEREL='[^
+]*-DMY_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_CXX_FLAGS_RELWITHDEBINFO='[^
+]*-DMY_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
diff --git a/Tests/RunCMake/ToolchainFile/FlagsInit-toolchain.cmake b/Tests/RunCMake/ToolchainFile/FlagsInit-toolchain.cmake
new file mode 100644
index 0000000..4c794b6
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/FlagsInit-toolchain.cmake
@@ -0,0 +1,7 @@
+foreach(lang C CXX)
+  set(CMAKE_${lang}_FLAGS_INIT -DMY_FLAGS_INIT)
+  set(CMAKE_${lang}_FLAGS_DEBUG_INIT -DMY_FLAGS_DEBUG_INIT)
+  set(CMAKE_${lang}_FLAGS_RELEASE_INIT -DMY_FLAGS_RELEASE_INIT)
+  set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT -DMY_FLAGS_MINSIZEREL_INIT)
+  set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT -DMY_FLAGS_RELWITHDEBINFO_INIT)
+endforeach()
diff --git a/Tests/RunCMake/ToolchainFile/FlagsInit.cmake b/Tests/RunCMake/ToolchainFile/FlagsInit.cmake
new file mode 100644
index 0000000..98873bf
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/FlagsInit.cmake
@@ -0,0 +1,7 @@
+enable_language(C)
+enable_language(CXX)
+foreach(lang C CXX)
+  foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+    message(STATUS "CMAKE_${lang}_FLAGS${c}='${CMAKE_${lang}_FLAGS${c}}'")
+  endforeach()
+endforeach()
diff --git a/Tests/RunCMake/ToolchainFile/LinkFlagsInit-stdout.txt b/Tests/RunCMake/ToolchainFile/LinkFlagsInit-stdout.txt
new file mode 100644
index 0000000..0ddf7d2
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/LinkFlagsInit-stdout.txt
@@ -0,0 +1,60 @@
+-- CMAKE_EXE_LINKER_FLAGS='[^
+]*MY_EXE_FLAGS_INIT[^
+]*'
+-- CMAKE_EXE_LINKER_FLAGS_DEBUG='[^
+]*MY_EXE_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_EXE_LINKER_FLAGS_RELEASE='[^
+]*MY_EXE_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_EXE_LINKER_FLAGS_MINSIZEREL='[^
+]*MY_EXE_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO='[^
+]*MY_EXE_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
+-- CMAKE_SHARED_LINKER_FLAGS='[^
+]*MY_SHARED_FLAGS_INIT[^
+]*'
+-- CMAKE_SHARED_LINKER_FLAGS_DEBUG='[^
+]*MY_SHARED_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_SHARED_LINKER_FLAGS_RELEASE='[^
+]*MY_SHARED_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL='[^
+]*MY_SHARED_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO='[^
+]*MY_SHARED_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
+-- CMAKE_MODULE_LINKER_FLAGS='[^
+]*MY_MODULE_FLAGS_INIT[^
+]*'
+-- CMAKE_MODULE_LINKER_FLAGS_DEBUG='[^
+]*MY_MODULE_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_MODULE_LINKER_FLAGS_RELEASE='[^
+]*MY_MODULE_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL='[^
+]*MY_MODULE_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO='[^
+]*MY_MODULE_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
+-- CMAKE_STATIC_LINKER_FLAGS='[^
+]*MY_STATIC_FLAGS_INIT[^
+]*'
+-- CMAKE_STATIC_LINKER_FLAGS_DEBUG='[^
+]*MY_STATIC_FLAGS_DEBUG_INIT[^
+]*'
+-- CMAKE_STATIC_LINKER_FLAGS_RELEASE='[^
+]*MY_STATIC_FLAGS_RELEASE_INIT[^
+]*'
+-- CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL='[^
+]*MY_STATIC_FLAGS_MINSIZEREL_INIT[^
+]*'
+-- CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO='[^
+]*MY_STATIC_FLAGS_RELWITHDEBINFO_INIT[^
+]*'
diff --git a/Tests/RunCMake/ToolchainFile/LinkFlagsInit-toolchain.cmake b/Tests/RunCMake/ToolchainFile/LinkFlagsInit-toolchain.cmake
new file mode 100644
index 0000000..ca908ae
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/LinkFlagsInit-toolchain.cmake
@@ -0,0 +1,5 @@
+foreach(t EXE SHARED MODULE STATIC)
+  foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+    set(CMAKE_${t}_LINKER_FLAGS${c}_INIT MY_${t}_FLAGS${c}_INIT)
+  endforeach()
+endforeach()
diff --git a/Tests/RunCMake/ToolchainFile/LinkFlagsInit.cmake b/Tests/RunCMake/ToolchainFile/LinkFlagsInit.cmake
new file mode 100644
index 0000000..069d741
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/LinkFlagsInit.cmake
@@ -0,0 +1,7 @@
+set(CMAKE_C_COMPILER_FORCED 1) # skip compiler test so we can check cached values
+enable_language(C)
+foreach(t EXE SHARED MODULE STATIC)
+  foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+    message(STATUS "CMAKE_${t}_LINKER_FLAGS${c}='${CMAKE_${t}_LINKER_FLAGS${c}}'")
+  endforeach()
+endforeach()
diff --git a/Tests/RunCMake/ToolchainFile/RunCMakeTest.cmake b/Tests/RunCMake/ToolchainFile/RunCMakeTest.cmake
index 75293e7..8a20200 100644
--- a/Tests/RunCMake/ToolchainFile/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ToolchainFile/RunCMakeTest.cmake
@@ -7,3 +7,5 @@ endfunction()
 
 run_cmake_toolchain(CallEnableLanguage)
 run_cmake_toolchain(CallProject)
+run_cmake_toolchain(FlagsInit)
+run_cmake_toolchain(LinkFlagsInit)
diff --git a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
index b77d5d4..d43c80d 100644
--- a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
+++ b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
@@ -1,6 +1,7 @@
 include(RunCMake)
 
 run_cmake(XcodeFileType)
+run_cmake(XcodeAttributeLocation)
 run_cmake(XcodeAttributeGenex)
 run_cmake(XcodeAttributeGenexError)
 run_cmake(XcodeObjectNeedsEscape)
@@ -31,13 +32,16 @@ if(NOT XCODE_VERSION VERSION_LESS 5)
 
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeBundlesOSX-build)
   set(RunCMake_TEST_NO_CLEAN 1)
-  set(RunCMake_TEST_OPTIONS "-DTEST_IOS=OFF")
+  set(RunCMake_TEST_OPTIONS
+    "-DTEST_IOS=OFF"
+    "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install")
 
   file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
   file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
 
   run_cmake(XcodeBundles)
   run_cmake_command(XcodeBundles-build ${CMAKE_COMMAND} --build .)
+  run_cmake_command(XcodeBundles-install ${CMAKE_COMMAND} --build . --target install)
 
   unset(RunCMake_TEST_BINARY_DIR)
   unset(RunCMake_TEST_NO_CLEAN)
@@ -45,13 +49,16 @@ if(NOT XCODE_VERSION VERSION_LESS 5)
 
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeBundlesIOS-build)
   set(RunCMake_TEST_NO_CLEAN 1)
-  set(RunCMake_TEST_OPTIONS "-DTEST_IOS=ON")
+  set(RunCMake_TEST_OPTIONS
+    "-DTEST_IOS=ON"
+    "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install")
 
   file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
   file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
 
   run_cmake(XcodeBundles)
   run_cmake_command(XcodeBundles-build ${CMAKE_COMMAND} --build .)
+  run_cmake_command(XcodeBundles-install ${CMAKE_COMMAND} --build . --target install)
 
   unset(RunCMake_TEST_BINARY_DIR)
   unset(RunCMake_TEST_NO_CLEAN)
@@ -61,13 +68,16 @@ endif()
 if(NOT XCODE_VERSION VERSION_LESS 7)
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeBundlesWatchOS-build)
   set(RunCMake_TEST_NO_CLEAN 1)
-  set(RunCMake_TEST_OPTIONS "-DTEST_WATCHOS=ON")
+  set(RunCMake_TEST_OPTIONS
+    "-DTEST_WATCHOS=ON"
+    "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install")
 
   file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
   file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
 
   run_cmake(XcodeBundles)
   run_cmake_command(XcodeBundles-build ${CMAKE_COMMAND} --build .)
+  run_cmake_command(XcodeBundles-install ${CMAKE_COMMAND} --build . --target install)
 
   unset(RunCMake_TEST_BINARY_DIR)
   unset(RunCMake_TEST_NO_CLEAN)
@@ -77,13 +87,16 @@ endif()
 if(NOT XCODE_VERSION VERSION_LESS 7.1)
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeBundlesTvOS-build)
   set(RunCMake_TEST_NO_CLEAN 1)
-  set(RunCMake_TEST_OPTIONS "-DTEST_TVOS=ON")
+  set(RunCMake_TEST_OPTIONS
+    "-DTEST_TVOS=ON"
+    "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install")
 
   file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
   file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
 
   run_cmake(XcodeBundles)
   run_cmake_command(XcodeBundles-build ${CMAKE_COMMAND} --build .)
+  run_cmake_command(XcodeBundles-install ${CMAKE_COMMAND} --build . --target install)
 
   unset(RunCMake_TEST_BINARY_DIR)
   unset(RunCMake_TEST_NO_CLEAN)
diff --git a/Tests/RunCMake/XcodeProject/XcodeAttributeLocation-check.cmake b/Tests/RunCMake/XcodeProject/XcodeAttributeLocation-check.cmake
new file mode 100644
index 0000000..2f55131
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeAttributeLocation-check.cmake
@@ -0,0 +1,7 @@
+set(expect "DEPLOYMENT_LOCATION = YES")
+file(STRINGS ${RunCMake_TEST_BINARY_DIR}/XcodeAttributeLocation.xcodeproj/project.pbxproj actual
+  REGEX "DEPLOYMENT_LOCATION = .*;" LIMIT_COUNT 1)
+if(NOT "${actual}" MATCHES "${expect}")
+  message(SEND_ERROR "The actual project contains the line:\n ${actual}\n"
+    "which does not match expected regex:\n ${expect}\n")
+endif()
diff --git a/Tests/RunCMake/XcodeProject/XcodeAttributeLocation.cmake b/Tests/RunCMake/XcodeProject/XcodeAttributeLocation.cmake
new file mode 100644
index 0000000..5ab5528
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeAttributeLocation.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(some main.c)
+set_property(TARGET some PROPERTY XCODE_ATTRIBUTE_DEPLOYMENT_LOCATION YES)
diff --git a/Tests/RunCMake/XcodeProject/XcodeBundles-install-check.cmake b/Tests/RunCMake/XcodeProject/XcodeBundles-install-check.cmake
new file mode 100644
index 0000000..758d730
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeBundles-install-check.cmake
@@ -0,0 +1,8 @@
+file(GLOB DIRECTORIES LIST_DIRECTORIES true
+  "${RunCMake_TEST_BINARY_DIR}/_install/FooExtension/*.*")
+
+foreach(DIRECTORY IN LISTS DIRECTORIES)
+  if(NOT DIRECTORY MATCHES "\\.foo$")
+    message(SEND_ERROR "Extension does not match ${DIRECTORY}")
+  endif()
+endforeach()
diff --git a/Tests/RunCMake/XcodeProject/XcodeBundles.cmake b/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
index 0fdc6af..ad4268d 100644
--- a/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
+++ b/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
@@ -36,6 +36,20 @@ add_custom_target(AppBundleTest ALL
 
 add_dependencies(AppBundleTest AppBundle)
 
+# with custom extension
+
+if (NOT TEST_IOS AND NOT TEST_WATCHOS AND NOT TEST_TVOS)
+  add_executable(AppBundleExt MACOSX_BUNDLE main.m)
+  set_target_properties(AppBundleExt PROPERTIES BUNDLE_EXTENSION "foo")
+  install(TARGETS AppBundleExt BUNDLE DESTINATION FooExtension)
+
+  add_custom_target(AppBundleExtTest ALL
+    COMMAND ${CMAKE_COMMAND} -E copy
+      "$<TARGET_FILE:AppBundleExt>" "$<TARGET_FILE:AppBundleExt>.old")
+
+  add_dependencies(AppBundleExtTest AppBundleExt)
+endif()
+
 # Framework (not supported for iOS on Xcode < 6)
 
 if(NOT TEST_IOS OR NOT XCODE_VERSION VERSION_LESS 6)
@@ -47,6 +61,19 @@ if(NOT TEST_IOS OR NOT XCODE_VERSION VERSION_LESS 6)
       "$<TARGET_FILE:Framework>" "$<TARGET_FILE:Framework>.old")
 
   add_dependencies(FrameworkTest Framework)
+
+  # with custom extension
+
+  add_library(FrameworkExt SHARED main.c)
+  set_target_properties(FrameworkExt PROPERTIES FRAMEWORK TRUE)
+  set_target_properties(FrameworkExt PROPERTIES BUNDLE_EXTENSION "foo")
+  install(TARGETS FrameworkExt FRAMEWORK DESTINATION FooExtension)
+
+  add_custom_target(FrameworkExtTest ALL
+    COMMAND ${CMAKE_COMMAND} -E copy
+      "$<TARGET_FILE:FrameworkExt>" "$<TARGET_FILE:FrameworkExt>.old")
+
+  add_dependencies(FrameworkExtTest FrameworkExt)
 endif()
 
 # Bundle
@@ -60,4 +87,17 @@ if(NOT CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE)
       "$<TARGET_FILE:Bundle>" "$<TARGET_FILE:Bundle>.old")
 
   add_dependencies(BundleTest Bundle)
+
+  # with custom extension
+
+  add_library(BundleExt MODULE main.c)
+  set_target_properties(BundleExt PROPERTIES BUNDLE TRUE)
+  set_target_properties(BundleExt PROPERTIES BUNDLE_EXTENSION "foo")
+  install(TARGETS BundleExt LIBRARY DESTINATION FooExtension)
+
+  add_custom_target(BundleExtTest ALL
+    COMMAND ${CMAKE_COMMAND} -E copy
+      "$<TARGET_FILE:BundleExt>" "$<TARGET_FILE:BundleExt>.old")
+
+  add_dependencies(BundleExtTest BundleExt)
 endif()
diff --git a/Tests/RunCMake/add_custom_command/AppendNotOutput-stderr.txt b/Tests/RunCMake/add_custom_command/AppendNotOutput-stderr.txt
index 96d0972..cd542d8 100644
--- a/Tests/RunCMake/add_custom_command/AppendNotOutput-stderr.txt
+++ b/Tests/RunCMake/add_custom_command/AppendNotOutput-stderr.txt
@@ -1,5 +1,8 @@
 CMake Error at AppendNotOutput.cmake:1 \(add_custom_command\):
-  add_custom_command given APPEND option with output.*
+  add_custom_command given APPEND option with output
+
+  .*RunCMake/add_custom_command/AppendNotOutput-build/out.*
+
   which is not already a custom command output.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/add_custom_target/RunCMakeTest.cmake b/Tests/RunCMake/add_custom_target/RunCMakeTest.cmake
index 92c4a38..6c4e91b 100644
--- a/Tests/RunCMake/add_custom_target/RunCMakeTest.cmake
+++ b/Tests/RunCMake/add_custom_target/RunCMakeTest.cmake
@@ -4,3 +4,17 @@ run_cmake(NoArguments)
 run_cmake(BadTargetName)
 run_cmake(ByproductsNoCommand)
 run_cmake(UsesTerminalNoCommand)
+
+function(run_TargetOrder)
+  # Use a single build tree for a few tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/TargetOrder-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  run_cmake(TargetOrder)
+  if(RunCMake_GENERATOR STREQUAL "Ninja")
+    set(build_flags -j 1 -v)
+  endif()
+  run_cmake_command(TargetOrder-build ${CMAKE_COMMAND} --build . -- ${build_flags})
+endfunction()
+run_TargetOrder()
diff --git a/Tests/RunCMake/add_custom_target/TargetOrder.cmake b/Tests/RunCMake/add_custom_target/TargetOrder.cmake
new file mode 100644
index 0000000..21669c0
--- /dev/null
+++ b/Tests/RunCMake/add_custom_target/TargetOrder.cmake
@@ -0,0 +1,31 @@
+# Add a target that requires step1 to run first but enforces
+# it only by target-level ordering dependency.
+add_custom_command(
+  OUTPUT step2.txt
+  COMMAND ${CMAKE_COMMAND} -E copy step1.txt step2.txt
+  )
+add_custom_target(step2 DEPENDS step2.txt)
+add_dependencies(step2 step1)
+
+# Add a target that requires step1 and step2 to work,
+# only depends on step1 transitively through step2, but
+# also gets a copy of step2's custom command.
+# The Ninja generator in particular must be careful with
+# this case because it needs to compute the proper set of
+# target ordering dependencies for the step2 custom command
+# even though it appears in both the step2 and step3
+# targets due to dependency propagation.
+add_custom_command(
+  OUTPUT step3.txt
+  COMMAND ${CMAKE_COMMAND} -E copy step1.txt step3-1.txt
+  COMMAND ${CMAKE_COMMAND} -E copy step2.txt step3.txt
+  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/step2.txt
+  )
+add_custom_target(step3 ALL DEPENDS step3.txt)
+add_dependencies(step3 step2)
+
+# We want this target to always run first.  Add it last so
+# that serial builds require dependencies to order it first.
+add_custom_target(step1
+  COMMAND ${CMAKE_COMMAND} -E touch step1.txt
+  )
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll.cmake b/Tests/RunCMake/add_subdirectory/ExcludeFromAll.cmake
new file mode 100644
index 0000000..f686005
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+
+add_subdirectory(ExcludeFromAll EXCLUDE_FROM_ALL)
+
+add_executable(main main.cpp)
+target_link_libraries(main PRIVATE foo)
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/CMakeLists.txt
new file mode 100644
index 0000000..b1df6b0
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/CMakeLists.txt
@@ -0,0 +1,4 @@
+add_library(bar STATIC bar.cpp)
+
+add_library(foo STATIC foo.cpp)
+target_include_directories(foo PUBLIC .)
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/bar.cpp b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/bar.cpp
new file mode 100644
index 0000000..7a828bd
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/bar.cpp
@@ -0,0 +1 @@
+#error This should be excluded from all target
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.cpp b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.cpp
new file mode 100644
index 0000000..c9ad322
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.cpp
@@ -0,0 +1,6 @@
+#include "foo.h"
+
+int foo()
+{
+  return 42;
+}
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.h b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.h
new file mode 100644
index 0000000..5d5f8f0
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/foo.h
@@ -0,0 +1 @@
+int foo();
diff --git a/Tests/RunCMake/add_subdirectory/RunCMakeTest.cmake b/Tests/RunCMake/add_subdirectory/RunCMakeTest.cmake
index 9d514e1..88b9283 100644
--- a/Tests/RunCMake/add_subdirectory/RunCMakeTest.cmake
+++ b/Tests/RunCMake/add_subdirectory/RunCMakeTest.cmake
@@ -3,3 +3,15 @@ include(RunCMake)
 run_cmake(DoesNotExist)
 run_cmake(Missing)
 run_cmake(Function)
+
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/ExcludeFromAll-build)
+set(RunCMake_TEST_NO_CLEAN 1)
+
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+run_cmake(ExcludeFromAll)
+run_cmake_command(ExcludeFromAll-build ${CMAKE_COMMAND} --build .)
+
+unset(RunCMake_TEST_BINARY_DIR)
+unset(RunCMake_TEST_NO_CLEAN)
diff --git a/Tests/RunCMake/add_subdirectory/main.cpp b/Tests/RunCMake/add_subdirectory/main.cpp
new file mode 100644
index 0000000..1dc3906
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/main.cpp
@@ -0,0 +1,6 @@
+#include "foo.h"
+
+int main(int, char**)
+{
+  return foo();
+}
diff --git a/Tests/RunCMake/cmake_parse_arguments/ArgvN.cmake b/Tests/RunCMake/cmake_parse_arguments/ArgvN.cmake
new file mode 100644
index 0000000..96a373d
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/ArgvN.cmake
@@ -0,0 +1,38 @@
+include(${CMAKE_CURRENT_LIST_DIR}/test_utils.cmake)
+
+function(test1)
+  cmake_parse_arguments(PARSE_ARGV 0
+    pref "OPT1;OPT2" "SINGLE1;SINGLE2" "MULTI1;MULTI2")
+
+  TEST(pref_OPT1 TRUE)
+  TEST(pref_OPT2 FALSE)
+  TEST(pref_SINGLE1 "foo;bar")
+  TEST(pref_SINGLE2 UNDEFINED)
+  TEST(pref_MULTI1 bar foo bar)
+  TEST(pref_MULTI2 UNDEFINED)
+  TEST(pref_UNPARSED_ARGUMENTS UNDEFINED)
+endfunction()
+test1(OPT1 SINGLE1 "foo;bar" MULTI1 bar foo bar)
+
+function(test2 arg1)
+  cmake_parse_arguments(PARSE_ARGV 1
+    pref "OPT1;OPT2" "SINGLE1;SINGLE2" "MULTI1;MULTI2")
+
+  TEST(arg1 "first named")
+  TEST(pref_OPT1 TRUE)
+  TEST(pref_OPT2 FALSE)
+  TEST(pref_SINGLE1 "foo;bar")
+  TEST(pref_SINGLE2 UNDEFINED)
+  TEST(pref_MULTI1 bar "foo;bar")
+  TEST(pref_MULTI2 UNDEFINED)
+  TEST(pref_UNPARSED_ARGUMENTS UNDEFINED)
+endfunction()
+test2("first named" OPT1 SINGLE1 "foo;bar" MULTI1 bar "foo;bar")
+
+function(test3 arg1)
+  cmake_parse_arguments(PARSE_ARGV 0
+    pref "" "" "")
+
+  TEST(pref_UNPARSED_ARGUMENTS "foo;bar" dog cat)
+endfunction()
+test3("foo;bar" dog cat)
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-result.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-stderr.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-stderr.txt
new file mode 100644
index 0000000..e44ab4d
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at BadArgvN1.cmake:[0-9]+ \(cmake_parse_arguments\):
+  PARSE_ARGV must be called with exactly 6 arguments.
+Call Stack \(most recent call first\):
+  BadArgvN1.cmake:[0-9]+ \(test1\)
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN1.cmake b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1.cmake
new file mode 100644
index 0000000..f894130
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN1.cmake
@@ -0,0 +1,4 @@
+function(test1)
+  cmake_parse_arguments(PARSE_ARGV 0 pref "" "" "" extra)
+endfunction()
+test1()
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-result.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-stderr.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-stderr.txt
new file mode 100644
index 0000000..1dde86d
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at BadArgvN2.cmake:[0-9]+ \(cmake_parse_arguments\):
+  PARSE_ARGV index 'pref' is not an unsigned integer
+Call Stack \(most recent call first\):
+  BadArgvN2.cmake:[0-9]+ \(test2\)
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN2.cmake b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2.cmake
new file mode 100644
index 0000000..d20c2c8
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN2.cmake
@@ -0,0 +1,4 @@
+function(test2)
+  cmake_parse_arguments(PARSE_ARGV pref "" "" "" extra)
+endfunction()
+test2()
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-result.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-stderr.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-stderr.txt
new file mode 100644
index 0000000..5a30dc9
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at BadArgvN3.cmake:[0-9]+ \(cmake_parse_arguments\):
+  PARSE_ARGV called with ARGC='' that is not an unsigned integer
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN3.cmake b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3.cmake
new file mode 100644
index 0000000..8fb3fdd
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN3.cmake
@@ -0,0 +1 @@
+cmake_parse_arguments(PARSE_ARGV 0 pref "" "" "")
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-result.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-stderr.txt b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-stderr.txt
new file mode 100644
index 0000000..f4bdac4
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at BadArgvN4.cmake:[0-9]+ \(cmake_parse_arguments\):
+  PARSE_ARGV called with ARGV0 not set
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/cmake_parse_arguments/BadArgvN4.cmake b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4.cmake
new file mode 100644
index 0000000..b887a28
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/BadArgvN4.cmake
@@ -0,0 +1,3 @@
+set(ARGC 1)
+cmake_parse_arguments(PARSE_ARGV 0 pref "" "" "")
+unset(ARGC)
diff --git a/Tests/RunCMake/cmake_parse_arguments/CornerCasesArgvN.cmake b/Tests/RunCMake/cmake_parse_arguments/CornerCasesArgvN.cmake
new file mode 100644
index 0000000..807ed03
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/CornerCasesArgvN.cmake
@@ -0,0 +1,53 @@
+include(${CMAKE_CURRENT_LIST_DIR}/test_utils.cmake)
+
+function(test1)
+  cmake_parse_arguments(PARSE_ARGV 0
+    mpref "" "" "MULTI")
+
+  TEST(mpref_MULTI foo "foo\;bar")
+
+  cmake_parse_arguments(PARSE_ARGV 1
+    upref "" "" "MULTI")
+
+  TEST(upref_UNPARSED_ARGUMENTS foo "foo\;bar")
+endfunction()
+test1(MULTI foo "foo\;bar")
+
+function(test2)
+  cmake_parse_arguments(PARSE_ARGV 0
+    mpref "" "" "MULTI")
+
+  TEST(mpref_MULTI "foo;" "bar;")
+
+  cmake_parse_arguments(PARSE_ARGV 1
+    upref "" "" "MULTI")
+
+  TEST(upref_UNPARSED_ARGUMENTS "foo;" "bar;")
+endfunction()
+test2(MULTI "foo;" "bar;")
+
+function(test3)
+  cmake_parse_arguments(PARSE_ARGV 0
+    mpref "" "" "MULTI")
+
+  TEST(mpref_MULTI "[foo;]" "bar\\")
+
+  cmake_parse_arguments(PARSE_ARGV 1
+    upref "" "" "MULTI")
+
+  TEST(upref_UNPARSED_ARGUMENTS "[foo;]" "bar\\")
+endfunction()
+test3(MULTI "[foo;]" "bar\\")
+
+function(test4)
+  cmake_parse_arguments(PARSE_ARGV 0
+    mpref "" "" "MULTI")
+
+  TEST(mpref_MULTI foo "bar;none")
+
+  cmake_parse_arguments(PARSE_ARGV 1
+    upref "" "" "MULTI")
+
+  TEST(upref_UNPARSED_ARGUMENTS foo "bar;none")
+endfunction()
+test4(MULTI foo bar\\ none)
diff --git a/Tests/RunCMake/cmake_parse_arguments/RunCMakeTest.cmake b/Tests/RunCMake/cmake_parse_arguments/RunCMakeTest.cmake
index b89f1a5..1e15b3b 100644
--- a/Tests/RunCMake/cmake_parse_arguments/RunCMakeTest.cmake
+++ b/Tests/RunCMake/cmake_parse_arguments/RunCMakeTest.cmake
@@ -5,3 +5,9 @@ run_cmake(Initialization)
 run_cmake(Mix)
 run_cmake(CornerCases)
 run_cmake(Errors)
+run_cmake(ArgvN)
+run_cmake(BadArgvN1)
+run_cmake(BadArgvN2)
+run_cmake(BadArgvN3)
+run_cmake(BadArgvN4)
+run_cmake(CornerCasesArgvN)
diff --git a/Tests/RunCMake/cmake_parse_arguments/Utils.cmake b/Tests/RunCMake/cmake_parse_arguments/Utils.cmake
index 3bbf115..f2001f2 100644
--- a/Tests/RunCMake/cmake_parse_arguments/Utils.cmake
+++ b/Tests/RunCMake/cmake_parse_arguments/Utils.cmake
@@ -17,4 +17,5 @@ SET (asdf "some value")
 TEST(asdf "some value")
 
 SET (asdf some list)
+TEST(asdf some list)
 TEST(asdf "some;list")
diff --git a/Tests/RunCMake/cmake_parse_arguments/test_utils.cmake b/Tests/RunCMake/cmake_parse_arguments/test_utils.cmake
index f5425c2..9ce99b8 100644
--- a/Tests/RunCMake/cmake_parse_arguments/test_utils.cmake
+++ b/Tests/RunCMake/cmake_parse_arguments/test_utils.cmake
@@ -1,20 +1,30 @@
-macro(TEST variable)
-  SET(expected "${ARGN}")
-  if ( "${expected}" STREQUAL "UNDEFINED" )
-    if (DEFINED ${variable})
-      message(FATAL_ERROR "'${variable}' shall be undefined but has value '${${variable}}'")
-    endif()
-  elseif( "${expected}" STREQUAL "FALSE" )
-    if (NOT ${variable} STREQUAL "FALSE")
-      message(FATAL_ERROR "'${variable}' shall be FALSE")
-    endif()
-  elseif( "${expected}" STREQUAL "TRUE" )
-    if (NOT ${variable} STREQUAL "TRUE")
-      message(FATAL_ERROR "'${variable}' shall be TRUE")
-    endif()
+function(TEST variable)
+  if(ARGC GREATER 2)
+    set(i 0)
+    foreach(value IN LISTS ${variable})
+      math(EXPR j "${i} + 1")
+      set(${variable}[${i}] "${value}")
+      TEST(${variable}[${i}] "${ARGV${j}}")
+      set(i ${j})
+    endforeach()
   else()
-    if (NOT ${variable} STREQUAL "${expected}")
-      message(FATAL_ERROR "'${variable}' shall be '${expected}'")
+    set(expected "${ARGN}")
+    if("${expected}" STREQUAL "UNDEFINED")
+      if(DEFINED ${variable})
+        message(FATAL_ERROR "'${variable}' shall be undefined but has value '${${variable}}'")
+      endif()
+    elseif("${expected}" STREQUAL "FALSE")
+      if(NOT ${variable} STREQUAL "FALSE")
+        message(FATAL_ERROR "'${variable}' shall be FALSE")
+      endif()
+    elseif("${expected}" STREQUAL "TRUE")
+      if(NOT ${variable} STREQUAL "TRUE")
+        message(FATAL_ERROR "'${variable}' shall be TRUE")
+      endif()
+    else()
+      if(NOT ${variable} STREQUAL "${expected}")
+        message(FATAL_ERROR "'${variable}' shall be '${expected}'")
+      endif()
     endif()
   endif()
-endmacro()
+endfunction()
diff --git a/Tests/RunCMake/continue/ContinueWhile.cmake b/Tests/RunCMake/continue/ContinueWhile.cmake
index c1fa87a..f69993c 100644
--- a/Tests/RunCMake/continue/ContinueWhile.cmake
+++ b/Tests/RunCMake/continue/ContinueWhile.cmake
@@ -1,7 +1,7 @@
 message(STATUS "start")
 unset(iter)
 while(NOT "${iter}" STREQUAL "aaaaa")
-  set(iter "${iter}a")
+  string(APPEND iter "a")
   if("${iter}" STREQUAL "aaa")
     continue()
   endif()
diff --git a/Tests/RunCMake/ctest_cmake_error/CMakeLists.txt.in b/Tests/RunCMake/ctest_cmake_error/CMakeLists.txt.in
new file mode 100644
index 0000000..1babd72
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CMakeLists.txt.in
@@ -0,0 +1,4 @@
+cmake_minimum_required(VERSION 3.1)
+project(CTestCoverage at CASE_NAME@ NONE)
+include(CTest)
+add_test(NAME RunCMakeVersion COMMAND "${CMAKE_COMMAND}" --version)
diff --git a/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorNonZero-stderr.txt b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorNonZero-stderr.txt
new file mode 100644
index 0000000..4afb57a
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorNonZero-stderr.txt
@@ -0,0 +1,4 @@
+.*ctest_configure called with unknown argument "junk".*
+.*ctest_build called with unknown argument "junk".*
+.*ctest_test called with unknown argument "junk".*
+.*ctest_coverage called with unknown argument "junk".*
diff --git a/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stderr.txt b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stderr.txt
new file mode 100644
index 0000000..4afb57a
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stderr.txt
@@ -0,0 +1,4 @@
+.*ctest_configure called with unknown argument "junk".*
+.*ctest_build called with unknown argument "junk".*
+.*ctest_test called with unknown argument "junk".*
+.*ctest_coverage called with unknown argument "junk".*
diff --git a/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stdout.txt b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stdout.txt
new file mode 100644
index 0000000..d00b0c8
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CTestCaptureErrorZero-stdout.txt
@@ -0,0 +1 @@
+.*Run dashboard with model Experimental.*
diff --git a/Tests/RunCMake/ctest_cmake_error/CTestConfig.cmake.in b/Tests/RunCMake/ctest_cmake_error/CTestConfig.cmake.in
new file mode 100644
index 0000000..1f679d5
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CTestConfig.cmake.in
@@ -0,0 +1 @@
+set(CTEST_PROJECT_NAME "CTestCoverage at CASE_NAME@")
diff --git a/Tests/RunCMake/ctest_cmake_error/CoverageQuiet-stdout.txt b/Tests/RunCMake/ctest_cmake_error/CoverageQuiet-stdout.txt
new file mode 100644
index 0000000..3b09eac
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/CoverageQuiet-stdout.txt
@@ -0,0 +1 @@
+sec$
diff --git a/Tests/RunCMake/ctest_cmake_error/RunCMakeTest.cmake b/Tests/RunCMake/ctest_cmake_error/RunCMakeTest.cmake
new file mode 100644
index 0000000..0ec04c2
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/RunCMakeTest.cmake
@@ -0,0 +1,10 @@
+include(RunCTest)
+
+set(CASE_CTEST_COVERAGE_ARGS "")
+
+function(run_ctest_coverage CASE_NAME)
+  set(CASE_CTEST_COVERAGE_ARGS "${ARGN}")
+  run_ctest(${CASE_NAME})
+endfunction()
+
+run_ctest_coverage(CTestCaptureErrorNonZero junk CAPTURE_CMAKE_ERROR val)
diff --git a/Tests/RunCMake/ctest_cmake_error/test.cmake.in b/Tests/RunCMake/ctest_cmake_error/test.cmake.in
new file mode 100644
index 0000000..0648e7c
--- /dev/null
+++ b/Tests/RunCMake/ctest_cmake_error/test.cmake.in
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 3.1)
+
+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 at -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_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
+
+set(ctest_coverage_args "@CASE_CTEST_COVERAGE_ARGS@")
+ctest_start(Experimental)
+ctest_configure( ${ctest_coverage_args} )
+ctest_build(  ${ctest_coverage_args} )
+ctest_test( ${ctest_coverage_args} )
+ctest_coverage( ${ctest_coverage_args} )
+ctest_upload(junk CAPTURE_CMAKE_ERROR val)
+if(NOT val EQUAL -1)
+  message(FATAL_ERROR "CAPTURE_CMAKE_ERROR should be -1 is [${val}]")
+endif()
diff --git a/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in b/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in
new file mode 100644
index 0000000..ba1c77a
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in
@@ -0,0 +1,81 @@
+cmake_minimum_required (VERSION 3.6.2)
+project(ctest_fixtures LANGUAGES NONE)
+include(CTest)
+
+macro(passTest testName)
+  set(someFile "${CMAKE_CURRENT_SOURCE_DIR}/test.cmake")
+  add_test(NAME ${testName}
+           COMMAND ${CMAKE_COMMAND} -E compare_files "${someFile}" "${someFile}")
+endmacro()
+
+macro(failTest testName)
+  set(someFile "${CMAKE_CURRENT_SOURCE_DIR}/test.cmake")
+  add_test(NAME ${testName}
+           COMMAND ${CMAKE_COMMAND} -E compare_files "${someFile}" "${someFile}xxx")
+endmacro()
+
+# Intersperse actual tests among setup/cleanup tests so that we don't
+# define them in the same order as they need to be executed. Numbers
+# at the end of each line correspond to the test numbers ctest will
+# use for each test.
+passTest(one)           # 1
+passTest(setupBoth)     # 2
+passTest(setupFoo)      # 3
+passTest(setupMeta)     # 4
+passTest(cleanupFoo)    # 5
+passTest(two)           # 6
+passTest(cleanupBar)    # 7
+passTest(three)         # 8
+failTest(setupFails)    # 9
+passTest(wontRun)       # 10
+passTest(cyclicSetup)   # 11
+passTest(cyclicCleanup) # 12
+
+# Define fixture dependencies and ordering
+set_tests_properties(setupFoo   PROPERTIES FIXTURES_SETUP    "Foo")
+set_tests_properties(cleanupFoo PROPERTIES FIXTURES_CLEANUP  "Foo")
+
+set_tests_properties(setupBoth  PROPERTIES FIXTURES_SETUP    "Foo;Bar")
+set_tests_properties(cleanupBar PROPERTIES FIXTURES_CLEANUP  "Bar")
+
+set_tests_properties(setupMeta  PROPERTIES FIXTURES_SETUP    "Meta"
+                                           FIXTURES_REQUIRED "Foo;Bar")
+
+set_tests_properties(setupBoth  PROPERTIES DEPENDS           setupFoo)
+
+set_tests_properties(setupFails PROPERTIES FIXTURES_SETUP    "Fails")
+
+set_tests_properties(one        PROPERTIES FIXTURES_REQUIRED "Other;Foo")
+set_tests_properties(two        PROPERTIES FIXTURES_REQUIRED "Bar")
+set_tests_properties(three      PROPERTIES FIXTURES_REQUIRED "Meta;Bar")
+set_tests_properties(wontRun    PROPERTIES FIXTURES_REQUIRED "Fails")
+
+ at CASE_CMAKELISTS_CYCLIC_CODE@
+
+# These are the cases verified by the main cmake build
+#
+#   Regex:         Test case list (in order)
+#    one            3, 2, 1, 5
+#    two            2, 6, 7
+#    three          3, 2, 4, 5, 8, 7
+#    setupFoo       3
+#    wontRun        9, 10
+#    cyclicSetup    -NA- (configure fails)
+#    cyclicCleanup  -NA- (configure fails)
+#
+# In the case of asking for just setupFoo, since there are
+# no tests using the Foo fixture, we do NOT expect cleanupFoo
+# to be executed. It is important not to pull in cleanupFoo
+# if setupFoo is explicitly requested and no other test requires
+# the Foo fixture, otherwise it would not be possible to run
+# just a setup or cleanup test in isolation (likely to be
+# needed during initial creation of such test cases).
+#
+# For the wontRun case, test 9 fails and test 10 should not run.
+# The result of the set of tests should be failure, which is
+# verified by the main cmake build's tests.
+#
+# For the two cyclic test cases invoked by the main cmake build,
+# FIXTURES_... properties are added to the relevant test at the
+# location marked with CASE_CMAKELISTS_CYCLIC_CODE. This creates
+# a self-dependency which causes the configure step to fail.
diff --git a/Tests/RunCMake/ctest_fixtures/CTestConfig.cmake.in b/Tests/RunCMake/ctest_fixtures/CTestConfig.cmake.in
new file mode 100644
index 0000000..9823562
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/CTestConfig.cmake.in
@@ -0,0 +1 @@
+set(CTEST_PROJECT_NAME "CTestTestFixtures. at CASE_NAME@")
diff --git a/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake b/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake
new file mode 100644
index 0000000..f13289a
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake
@@ -0,0 +1,36 @@
+include(RunCTest)
+
+# Isolate our ctest runs from external environment.
+unset(ENV{CTEST_PARALLEL_LEVEL})
+unset(ENV{CTEST_OUTPUT_ON_FAILURE})
+
+function(run_ctest_test CASE_NAME)
+  set(CASE_CTEST_FIXTURES_ARGS "${ARGN}")
+  run_ctest(${CASE_NAME})
+endfunction()
+
+#------------------------------------------------------------
+# CMake configure will pass
+#------------------------------------------------------------
+run_ctest_test(one      INCLUDE one)
+run_ctest_test(two      INCLUDE two)
+run_ctest_test(three    INCLUDE three)
+run_ctest_test(setupFoo INCLUDE setupFoo)
+run_ctest_test(wontRun  INCLUDE wontRun)
+
+#------------------------------------------------------------
+# CMake configure will fail due to cyclic test dependencies
+#------------------------------------------------------------
+set(CASE_CMAKELISTS_CYCLIC_CODE [[
+    set_tests_properties(cyclicSetup PROPERTIES
+                         FIXTURES_SETUP    "Foo"
+                         FIXTURES_REQUIRED "Foo")
+]])
+run_ctest(cyclicSetup)
+
+set(CASE_CMAKELISTS_CYCLIC_CODE [[
+    set_tests_properties(cyclicCleanup PROPERTIES
+                         FIXTURES_CLEANUP  "Foo"
+                         FIXTURES_REQUIRED "Foo")
+]])
+run_ctest(cyclicCleanup)
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicCleanup-result.txt b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-result.txt
new file mode 100644
index 0000000..b57e2de
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stderr.txt b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stderr.txt
new file mode 100644
index 0000000..1a45994
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stderr.txt
@@ -0,0 +1,3 @@
+Error: a cycle exists in the test dependency graph for the test "cyclicCleanup".
+Please fix the cycle and run ctest again.
+No tests were found!!!
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stdout.txt b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stdout.txt
new file mode 100644
index 0000000..8b7fdf7
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicCleanup-stdout.txt
@@ -0,0 +1 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/cyclicCleanup-build$
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicSetup-result.txt b/Tests/RunCMake/ctest_fixtures/cyclicSetup-result.txt
new file mode 100644
index 0000000..b57e2de
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicSetup-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicSetup-stderr.txt b/Tests/RunCMake/ctest_fixtures/cyclicSetup-stderr.txt
new file mode 100644
index 0000000..2aba6c9
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicSetup-stderr.txt
@@ -0,0 +1,3 @@
+Error: a cycle exists in the test dependency graph for the test "cyclicSetup".
+Please fix the cycle and run ctest again.
+No tests were found!!!$
diff --git a/Tests/RunCMake/ctest_fixtures/cyclicSetup-stdout.txt b/Tests/RunCMake/ctest_fixtures/cyclicSetup-stdout.txt
new file mode 100644
index 0000000..22c564d
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/cyclicSetup-stdout.txt
@@ -0,0 +1 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/cyclicSetup-build$
diff --git a/Tests/RunCMake/ctest_fixtures/one-stdout.txt b/Tests/RunCMake/ctest_fixtures/one-stdout.txt
new file mode 100644
index 0000000..e2276a4
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/one-stdout.txt
@@ -0,0 +1,13 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/one-build
+    Start 3: setupFoo
+1/4 Test #3: setupFoo +\.+ +Passed +[0-9.]+ sec
+    Start 2: setupBoth
+2/4 Test #2: setupBoth +\.+ +Passed +[0-9.]+ sec
+    Start 1: one
+3/4 Test #1: one +\.+ +Passed +[0-9.]+ sec
+    Start 5: cleanupFoo
+4/4 Test #5: cleanupFoo +\.+ +Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 4
++
+Total Test time \(real\) = +[0-9.]+ sec$
diff --git a/Tests/RunCMake/ctest_fixtures/setupFoo-stdout.txt b/Tests/RunCMake/ctest_fixtures/setupFoo-stdout.txt
new file mode 100644
index 0000000..7e21b34
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/setupFoo-stdout.txt
@@ -0,0 +1,7 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/setupFoo-build
+    Start 3: setupFoo
+1/1 Test #3: setupFoo +\.+ +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_fixtures/test.cmake.in b/Tests/RunCMake/ctest_fixtures/test.cmake.in
new file mode 100644
index 0000000..43df172
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/test.cmake.in
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.6.2)
+
+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 at -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_fixtures_args "@CASE_CTEST_FIXTURES_ARGS@")
+
+ctest_start(Experimental)
+ctest_configure()
+ctest_test(${ctest_fixtures_args})
diff --git a/Tests/RunCMake/ctest_fixtures/three-stdout.txt b/Tests/RunCMake/ctest_fixtures/three-stdout.txt
new file mode 100644
index 0000000..f192e61
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/three-stdout.txt
@@ -0,0 +1,17 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/three-build
+    Start 3: setupFoo
+1/6 Test #3: setupFoo +\.+ +Passed +[0-9.]+ sec
+    Start 2: setupBoth
+2/6 Test #2: setupBoth +\.+ +Passed +[0-9.]+ sec
+    Start 4: setupMeta
+3/6 Test #4: setupMeta +\.+ +Passed +[0-9.]+ sec
+    Start 5: cleanupFoo
+4/6 Test #5: cleanupFoo +\.+ +Passed +[0-9.]+ sec
+    Start 8: three
+5/6 Test #8: three +\.+ +Passed +[0-9.]+ sec
+    Start 7: cleanupBar
+6/6 Test #7: cleanupBar +\.+ +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/ctest_fixtures/two-stdout.txt b/Tests/RunCMake/ctest_fixtures/two-stdout.txt
new file mode 100644
index 0000000..2e667a7
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/two-stdout.txt
@@ -0,0 +1,11 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/two-build
+    Start 2: setupBoth
+1/3 Test #2: setupBoth +\.+ +Passed +[0-9.]+ sec
+    Start 6: two
+2/3 Test #6: two +\.+ +Passed +[0-9.]+ sec
+    Start 7: cleanupBar
+3/3 Test #7: cleanupBar +\.+ +Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 3
++
+Total Test time \(real\) = +[0-9.]+ sec$
diff --git a/Tests/RunCMake/ctest_fixtures/wontRun-stdout.txt b/Tests/RunCMake/ctest_fixtures/wontRun-stdout.txt
new file mode 100644
index 0000000..526ca4b
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/wontRun-stdout.txt
@@ -0,0 +1,14 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/wontRun-build
+    Start  9: setupFails
+1/2 Test  #9: setupFails +\.+\*\*\*Failed +[0-9.]+ sec
+    Start 10: wontRun
+Failed test dependencies: setupFails
+2/2 Test #10: wontRun +\.+\*\*\*Not Run +[0-9.]+ sec
++
+0% tests passed, 2 tests failed out of 2
++
+Total Test time \(real\) = +[0-9.]+ sec
++
+The following tests FAILED:
+.* +9 - setupFails \(Failed\)
+.* +10 - wontRun \(Not Run\)$
diff --git a/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-result.txt b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-stderr.txt b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-stderr.txt
new file mode 100644
index 0000000..247923b
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at DOWNLOAD-httpheader-not-set.cmake:[0-9]+ \(file\):
+  file DOWNLOAD missing string for HTTPHEADER.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set.cmake b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set.cmake
new file mode 100644
index 0000000..6efc958
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-httpheader-not-set.cmake
@@ -0,0 +1 @@
+file(DOWNLOAD "" "" HTTPHEADER "Content-Type: application/x-compressed-tar" HTTPHEADER)
diff --git a/Tests/RunCMake/file/DOWNLOAD-pass-not-set-result.txt b/Tests/RunCMake/file/DOWNLOAD-pass-not-set-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-pass-not-set-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/DOWNLOAD-pass-not-set-stderr.txt b/Tests/RunCMake/file/DOWNLOAD-pass-not-set-stderr.txt
new file mode 100644
index 0000000..2fa2731
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-pass-not-set-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at DOWNLOAD-pass-not-set.cmake:[0-9]+ \(file\):
+  file DOWNLOAD missing string for USERPWD.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/DOWNLOAD-pass-not-set.cmake b/Tests/RunCMake/file/DOWNLOAD-pass-not-set.cmake
new file mode 100644
index 0000000..61eff6d
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-pass-not-set.cmake
@@ -0,0 +1 @@
+file(DOWNLOAD "" "" USERPWD)
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/file/DOWNLOAD-unused-argument-result.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/file/DOWNLOAD-unused-argument-result.txt
diff --git a/Tests/RunCMake/file/DOWNLOAD-unused-argument-stderr.txt b/Tests/RunCMake/file/DOWNLOAD-unused-argument-stderr.txt
new file mode 100644
index 0000000..82a78c9
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-unused-argument-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Warning \(dev\) at DOWNLOAD-unused-argument.cmake:[0-9]+ \(file\):
+  Unexpected argument: JUNK
+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/DOWNLOAD-unused-argument.cmake b/Tests/RunCMake/file/DOWNLOAD-unused-argument.cmake
new file mode 100644
index 0000000..2e3fbe1
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-unused-argument.cmake
@@ -0,0 +1,5 @@
+file(DOWNLOAD
+  "file://${CMAKE_CURRENT_SOURCE_DIR}/DOWNLOAD-unused-argument.txt"
+  "${CMAKE_CURRENT_BINARY_DIR}/unused-argument.txt"
+  JUNK
+  )
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/file/DOWNLOAD-unused-argument.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/file/DOWNLOAD-unused-argument.txt
diff --git a/Tests/RunCMake/file/LOCK-lowercase.cmake b/Tests/RunCMake/file/LOCK-lowercase.cmake
new file mode 100644
index 0000000..373afda
--- /dev/null
+++ b/Tests/RunCMake/file/LOCK-lowercase.cmake
@@ -0,0 +1,11 @@
+set(lock "${CMAKE_CURRENT_BINARY_DIR}/file-to-lock")
+
+if(WIN32)
+  string(TOLOWER ${lock} lock)
+endif()
+
+file(LOCK ${lock} TIMEOUT 0)
+file(LOCK ${lock} RELEASE)
+
+file(LOCK ${lock} TIMEOUT 0)
+file(LOCK ${lock} RELEASE)
diff --git a/Tests/RunCMake/file/RunCMakeTest.cmake b/Tests/RunCMake/file/RunCMakeTest.cmake
index 5f85bba..48fa757 100644
--- a/Tests/RunCMake/file/RunCMakeTest.cmake
+++ b/Tests/RunCMake/file/RunCMakeTest.cmake
@@ -1,6 +1,12 @@
 include(RunCMake)
 
 run_cmake(DOWNLOAD-hash-mismatch)
+run_cmake(DOWNLOAD-unused-argument)
+run_cmake(DOWNLOAD-httpheader-not-set)
+run_cmake(DOWNLOAD-pass-not-set)
+run_cmake(UPLOAD-unused-argument)
+run_cmake(UPLOAD-httpheader-not-set)
+run_cmake(UPLOAD-pass-not-set)
 run_cmake(INSTALL-DIRECTORY)
 run_cmake(INSTALL-MESSAGE-bad)
 run_cmake(FileOpenFailRead)
@@ -18,6 +24,7 @@ run_cmake(LOCK-error-no-result-variable)
 run_cmake(LOCK-error-no-timeout)
 run_cmake(LOCK-error-timeout)
 run_cmake(LOCK-error-unknown-option)
+run_cmake(LOCK-lowercase)
 run_cmake(GLOB)
 run_cmake(GLOB_RECURSE)
 # test is valid both for GLOB and GLOB_RECURSE
diff --git a/Tests/RunCMake/file/UPLOAD-httpheader-not-set-result.txt b/Tests/RunCMake/file/UPLOAD-httpheader-not-set-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-httpheader-not-set-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/UPLOAD-httpheader-not-set-stderr.txt b/Tests/RunCMake/file/UPLOAD-httpheader-not-set-stderr.txt
new file mode 100644
index 0000000..341baf5
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-httpheader-not-set-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at UPLOAD-httpheader-not-set.cmake:[0-9]+ \(file\):
+  file UPLOAD missing string for HTTPHEADER.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/UPLOAD-httpheader-not-set.cmake b/Tests/RunCMake/file/UPLOAD-httpheader-not-set.cmake
new file mode 100644
index 0000000..18d43cc
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-httpheader-not-set.cmake
@@ -0,0 +1 @@
+file(UPLOAD "" "" HTTPHEADER "Content-Type: application/x-compressed-tar" HTTPHEADER)
diff --git a/Tests/RunCMake/file/UPLOAD-pass-not-set-result.txt b/Tests/RunCMake/file/UPLOAD-pass-not-set-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-pass-not-set-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/UPLOAD-pass-not-set-stderr.txt b/Tests/RunCMake/file/UPLOAD-pass-not-set-stderr.txt
new file mode 100644
index 0000000..089c0ad
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-pass-not-set-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at UPLOAD-pass-not-set.cmake:[0-9]+ \(file\):
+  file UPLOAD missing string for USERPWD.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/UPLOAD-pass-not-set.cmake b/Tests/RunCMake/file/UPLOAD-pass-not-set.cmake
new file mode 100644
index 0000000..4f3d86c
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-pass-not-set.cmake
@@ -0,0 +1 @@
+file(UPLOAD "" "" USERPWD)
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/file/UPLOAD-unused-argument-result.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/file/UPLOAD-unused-argument-result.txt
diff --git a/Tests/RunCMake/file/UPLOAD-unused-argument-stderr.txt b/Tests/RunCMake/file/UPLOAD-unused-argument-stderr.txt
new file mode 100644
index 0000000..3c1b744
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-unused-argument-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Warning \(dev\) at UPLOAD-unused-argument.cmake:[0-9]+ \(file\):
+  Unexpected argument: JUNK
+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/UPLOAD-unused-argument.cmake b/Tests/RunCMake/file/UPLOAD-unused-argument.cmake
new file mode 100644
index 0000000..94ac9ac
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-unused-argument.cmake
@@ -0,0 +1,5 @@
+file(UPLOAD
+  "${CMAKE_CURRENT_SOURCE_DIR}/UPLOAD-unused-argument.txt"
+  "file://${CMAKE_CURRENT_BINARY_DIR}/unused-argument.txt"
+  JUNK
+  )
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/file/UPLOAD-unused-argument.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/file/UPLOAD-unused-argument.txt
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/find_path/Frameworks/Foo.framework/Headers/Some/Dir/Header.h
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/find_path/Frameworks/Foo.framework/Headers/Some/Dir/Header.h
diff --git a/Tests/RunCMake/find_path/FrameworksWithSubdirs-stdout.txt b/Tests/RunCMake/find_path/FrameworksWithSubdirs-stdout.txt
new file mode 100644
index 0000000..001a3e9
--- /dev/null
+++ b/Tests/RunCMake/find_path/FrameworksWithSubdirs-stdout.txt
@@ -0,0 +1 @@
+-- SOME_INCLUDE_DIR='[^']*Tests/RunCMake/find_path/Frameworks/Foo.framework/Headers'
diff --git a/Tests/RunCMake/find_path/FrameworksWithSubdirs.cmake b/Tests/RunCMake/find_path/FrameworksWithSubdirs.cmake
new file mode 100644
index 0000000..b286021
--- /dev/null
+++ b/Tests/RunCMake/find_path/FrameworksWithSubdirs.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_FRAMEWORK_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Frameworks")
+find_path(SOME_INCLUDE_DIR "Some/Dir/Header.h")
+message(STATUS "SOME_INCLUDE_DIR='${SOME_INCLUDE_DIR}'")
diff --git a/Tests/RunCMake/find_path/RunCMakeTest.cmake b/Tests/RunCMake/find_path/RunCMakeTest.cmake
index 5ce96e0..bf0fa89 100644
--- a/Tests/RunCMake/find_path/RunCMakeTest.cmake
+++ b/Tests/RunCMake/find_path/RunCMakeTest.cmake
@@ -3,3 +3,7 @@ include(RunCMake)
 if(WIN32 OR CYGWIN)
   run_cmake(PrefixInPATH)
 endif()
+
+if(APPLE)
+  run_cmake(FrameworksWithSubdirs)
+endif()
diff --git a/Tests/RunCMake/get_filename_component/KnownComponents.cmake b/Tests/RunCMake/get_filename_component/KnownComponents.cmake
index d822258..7dfb55d 100644
--- a/Tests/RunCMake/get_filename_component/KnownComponents.cmake
+++ b/Tests/RunCMake/get_filename_component/KnownComponents.cmake
@@ -19,12 +19,12 @@ foreach(c DIRECTORY NAME EXT NAME_WE PATH)
 endforeach()
 
 # Test Windows paths with DIRECTORY component and an absolute Windows path.
-get_filename_component(test_slashes "c:\\path\\to\\filename.ext.in" DIRECTORY)
-check("DIRECTORY from backslashes" "${test_slashes}" "c:/path/to")
+get_filename_component(test_slashes "C:\\path\\to\\filename.ext.in" DIRECTORY)
+check("DIRECTORY from backslashes" "${test_slashes}" "C:/path/to")
 list(APPEND non_cache_vars test_slashes)
 
-get_filename_component(test_winroot "c:\\filename.ext.in" DIRECTORY)
-check("DIRECTORY in windows root" "${test_winroot}" "c:/")
+get_filename_component(test_winroot "C:\\filename.ext.in" DIRECTORY)
+check("DIRECTORY in windows root" "${test_winroot}" "C:/")
 list(APPEND non_cache_vars test_winroot)
 
 # Test finding absolute paths.
@@ -33,8 +33,8 @@ check("ABSOLUTE" "${test_absolute}" "/path/to/filename.ext.in")
 
 get_filename_component(test_absolute "/../path/to/filename.ext.in" ABSOLUTE)
 check("ABSOLUTE .. in root" "${test_absolute}" "/path/to/filename.ext.in")
-get_filename_component(test_absolute "c:/../path/to/filename.ext.in" ABSOLUTE)
-check("ABSOLUTE .. in windows root" "${test_absolute}" "c:/path/to/filename.ext.in")
+get_filename_component(test_absolute "C:/../path/to/filename.ext.in" ABSOLUTE)
+check("ABSOLUTE .. in windows root" "${test_absolute}" "C:/path/to/filename.ext.in")
 
 list(APPEND non_cache_vars test_absolute)
 
diff --git a/Tests/RunCMake/get_property/directory_properties-stderr.txt b/Tests/RunCMake/get_property/directory_properties-stderr.txt
index 80c9877..6d5bcdb 100644
--- a/Tests/RunCMake/get_property/directory_properties-stderr.txt
+++ b/Tests/RunCMake/get_property/directory_properties-stderr.txt
@@ -3,4 +3,20 @@ get_property: --><--
 get_directory_property: -->value<--
 get_property: -->value<--
 get_directory_property: --><--
-get_property: --><--$
+get_property: --><--
+get_directory_property: -->[^<;]*Tests/RunCMake/get_property/directory_properties<--
+get_property: -->[^<;]*Tests/RunCMake/get_property/directory_properties<--
+get_directory_property: -->[^<;]*Tests/RunCMake/get_property/directory_properties/sub1;[^<;]*Tests/RunCMake/get_property/directory_properties/sub2<--
+get_property: -->[^<;]*Tests/RunCMake/get_property/directory_properties/sub1;[^<;]*Tests/RunCMake/get_property/directory_properties/sub2<--
+get_directory_property: -->CustomTop;InterfaceTop<--
+get_property: -->CustomTop;InterfaceTop<--
+get_directory_property: -->CustomSub;InterfaceSub<--
+get_property: -->CustomSub;InterfaceSub<--
+get_directory_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build<--
+get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build<--
+get_directory_property: -->[^<;]*/RunCMake/get_property<--
+get_property: -->[^<;]*/Tests/RunCMake/get_property<--
+get_directory_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build/directory_properties<--
+get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build/directory_properties<--
+get_directory_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties<--
+get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties<--$
diff --git a/Tests/RunCMake/get_property/directory_properties.cmake b/Tests/RunCMake/get_property/directory_properties.cmake
index b0a9b1b..4e68738 100644
--- a/Tests/RunCMake/get_property/directory_properties.cmake
+++ b/Tests/RunCMake/get_property/directory_properties.cmake
@@ -13,3 +13,18 @@ set_directory_properties(PROPERTIES empty "" custom value)
 check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" empty)
 check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" custom)
 check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" noexist)
+
+add_custom_target(CustomTop)
+add_library(InterfaceTop INTERFACE)
+add_library(my::InterfaceTop ALIAS InterfaceTop)
+
+add_subdirectory(directory_properties)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" SUBDIRECTORIES)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" SUBDIRECTORIES)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" BUILDSYSTEM_TARGETS)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" BUILDSYSTEM_TARGETS)
+
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" BINARY_DIR)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" SOURCE_DIR)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" BINARY_DIR)
+check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" SOURCE_DIR)
diff --git a/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt b/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt
new file mode 100644
index 0000000..7318b97
--- /dev/null
+++ b/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt
@@ -0,0 +1,6 @@
+add_subdirectory(sub1)
+subdirs(sub2)
+
+add_custom_target(CustomSub)
+add_library(InterfaceSub INTERFACE)
+add_library(my::InterfaceSub ALIAS InterfaceSub)
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/get_property/directory_properties/sub1/CMakeLists.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/get_property/directory_properties/sub1/CMakeLists.txt
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/get_property/directory_properties/sub2/CMakeLists.txt
similarity index 100%
copy from Utilities/Release/Cygwin/cygwin-patch.diff.in
copy to Tests/RunCMake/get_property/directory_properties/sub2/CMakeLists.txt
diff --git a/Tests/RunCMake/if/IsDirectoryLong.cmake b/Tests/RunCMake/if/IsDirectoryLong.cmake
index 0e93be7..e6939ac 100644
--- a/Tests/RunCMake/if/IsDirectoryLong.cmake
+++ b/Tests/RunCMake/if/IsDirectoryLong.cmake
@@ -1,6 +1,6 @@
 set(d "/long/path/to/directory")
 foreach(i RANGE 11)
-  set(d "${d}${d}")
+  string(APPEND d "${d}")
 endforeach()
 string(LENGTH "${d}" dl)
 if(IS_DIRECTORY "${d}/")
diff --git a/Tests/RunCMake/include_external_msproject/check_utils.cmake b/Tests/RunCMake/include_external_msproject/check_utils.cmake
index 408cadb..5dd92f9 100644
--- a/Tests/RunCMake/include_external_msproject/check_utils.cmake
+++ b/Tests/RunCMake/include_external_msproject/check_utils.cmake
@@ -91,7 +91,7 @@ function(check_project test name guid type platform)
   if(guid)
     check_project_guid("${sln}" "${name}" "${guid}" passed_guid)
     if(NOT passed_guid)
-      set(failed "${failed}${sep}${name} solution has no project with expected GUID=${guid}")
+      string(APPEND failed "${sep}${name} solution has no project with expected GUID=${guid}")
       set(sep "\n")
     endif()
   else()
@@ -99,12 +99,12 @@ function(check_project test name guid type platform)
   endif()
   check_project_type("${sln}" "${name}" "${type}" passed_type)
   if(NOT passed_type)
-    set(failed "${failed}${sep}${name} solution has no project with expected TYPE=${type}")
+    string(APPEND failed "${sep}${name} solution has no project with expected TYPE=${type}")
     set(sep "\n")
   endif()
   check_custom_platform("${sln}" "${name}" "${platform}" passed_platform)
   if(NOT passed_platform)
-    set(failed "${failed}${sep}${name} solution has no project with expected PLATFORM=${platform}")
+    string(APPEND failed "${sep}${name} solution has no project with expected PLATFORM=${platform}")
     set(sep "\n")
   endif()
   set(RunCMake_TEST_FAILED "${failed}" PARENT_SCOPE)
diff --git a/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake
index 2c716e1..3605163 100644
--- a/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake
+++ b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake
@@ -3,11 +3,11 @@ execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_in
   OUTPUT_VARIABLE out ERROR_VARIABLE err)
 if(out MATCHES "-- Installing: [^\n]*prefix/dir")
   string(REGEX REPLACE "\n" "\n  " out "  ${out}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}Installation output was not quiet:\n${out}")
+  string(APPEND RunCMake_TEST_FAILED
+    "Installation output was not quiet:\n${out}")
 endif()
 set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
 if(NOT EXISTS "${f}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+  string(APPEND RunCMake_TEST_FAILED
+    "File was not installed:\n  ${f}\n")
 endif()
diff --git a/Tests/RunCMake/install/DIRECTORY-message-check.cmake b/Tests/RunCMake/install/DIRECTORY-message-check.cmake
index 857681f..c9de3ea 100644
--- a/Tests/RunCMake/install/DIRECTORY-message-check.cmake
+++ b/Tests/RunCMake/install/DIRECTORY-message-check.cmake
@@ -7,13 +7,13 @@ set(expect "
 ")
 if(NOT out MATCHES "${expect}")
   string(REGEX REPLACE "\n" "\n  " out "  ${out}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}First install did not say 'Installing' as expected:\n${out}")
+  string(APPEND RunCMake_TEST_FAILED
+    "First install did not say 'Installing' as expected:\n${out}")
 endif()
 set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
 if(NOT EXISTS "${f}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+  string(APPEND RunCMake_TEST_FAILED
+    "File was not installed:\n  ${f}\n")
 endif()
 execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
   OUTPUT_VARIABLE out ERROR_VARIABLE err)
@@ -23,6 +23,6 @@ set(expect "
 ")
 if(NOT out MATCHES "${expect}")
   string(REGEX REPLACE "\n" "\n  " out "  ${out}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}Second install did not say 'Up-to-date' as expected:\n${out}")
+  string(APPEND RunCMake_TEST_FAILED
+    "Second install did not say 'Up-to-date' as expected:\n${out}")
 endif()
diff --git a/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake b/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake
index c7e6018..4339012 100644
--- a/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake
+++ b/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake
@@ -7,18 +7,18 @@ set(expect "
 ")
 if(NOT out MATCHES "${expect}")
   string(REGEX REPLACE "\n" "\n  " out "  ${out}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}First install did not say 'Installing' as expected:\n${out}")
+  string(APPEND RunCMake_TEST_FAILED
+    "First install did not say 'Installing' as expected:\n${out}")
 endif()
 set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
 if(NOT EXISTS "${f}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+  string(APPEND RunCMake_TEST_FAILED
+    "File was not installed:\n  ${f}\n")
 endif()
 execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
   OUTPUT_VARIABLE out ERROR_VARIABLE err)
 if(out MATCHES "(Installing|Up-to-date)")
   string(REGEX REPLACE "\n" "\n  " out "  ${out}")
-  set(RunCMake_TEST_FAILED
-    "${RunCMake_TEST_FAILED}Second install was not silent as expected:\n${out}")
+  string(APPEND RunCMake_TEST_FAILED
+    "Second install was not silent as expected:\n${out}")
 endif()
diff --git a/Tests/RunCMake/message/RunCMakeTest.cmake b/Tests/RunCMake/message/RunCMakeTest.cmake
index 9489693..2346c86 100644
--- a/Tests/RunCMake/message/RunCMakeTest.cmake
+++ b/Tests/RunCMake/message/RunCMakeTest.cmake
@@ -2,6 +2,8 @@ include(RunCMake)
 
 run_cmake(defaultmessage)
 run_cmake(nomessage)
+run_cmake(message-internal-warning)
+run_cmake(nomessage-internal-warning)
 run_cmake(warnmessage)
 # message command sets fatal occurred flag, so check each type of error
 
diff --git a/Tests/RunCMake/message/message-internal-warning-stderr.txt b/Tests/RunCMake/message/message-internal-warning-stderr.txt
new file mode 100644
index 0000000..25946e9
--- /dev/null
+++ b/Tests/RunCMake/message/message-internal-warning-stderr.txt
@@ -0,0 +1,13 @@
+^CMake Warning \(dev\) in message-internal-warning.cmake:
+  A logical block opening on the line
+
+    .*Tests/RunCMake/message/message-internal-warning.cmake:4 \(macro\)
+
+  closes on the line
+
+    .*Tests/RunCMake/message/message-internal-warning.cmake:5 \(endmacro\)
+
+  with mis-matching arguments.
+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/message/message-internal-warning.cmake b/Tests/RunCMake/message/message-internal-warning.cmake
new file mode 100644
index 0000000..33993c7
--- /dev/null
+++ b/Tests/RunCMake/message/message-internal-warning.cmake
@@ -0,0 +1,5 @@
+
+set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS ON)
+
+macro(mymacro)
+endmacro(notmymacro)
diff --git a/Utilities/Release/Cygwin/cygwin-patch.diff.in b/Tests/RunCMake/message/nomessage-internal-warning-stderr.txt
similarity index 100%
rename from Utilities/Release/Cygwin/cygwin-patch.diff.in
rename to Tests/RunCMake/message/nomessage-internal-warning-stderr.txt
diff --git a/Tests/RunCMake/message/nomessage-internal-warning.cmake b/Tests/RunCMake/message/nomessage-internal-warning.cmake
new file mode 100644
index 0000000..3ec2e28
--- /dev/null
+++ b/Tests/RunCMake/message/nomessage-internal-warning.cmake
@@ -0,0 +1,5 @@
+
+set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS ON CACHE BOOL "")
+
+macro(mymacro)
+endmacro(notmymacro)
diff --git a/Tests/RunCMake/project/ExplicitRC.cmake b/Tests/RunCMake/project/ExplicitRC.cmake
new file mode 100644
index 0000000..b3feaa9
--- /dev/null
+++ b/Tests/RunCMake/project/ExplicitRC.cmake
@@ -0,0 +1 @@
+project(ExplicitRC C RC)
diff --git a/Tests/RunCMake/project/RunCMakeTest.cmake b/Tests/RunCMake/project/RunCMakeTest.cmake
index 6ab0fc9..dba97d2 100644
--- a/Tests/RunCMake/project/RunCMakeTest.cmake
+++ b/Tests/RunCMake/project/RunCMakeTest.cmake
@@ -1,5 +1,8 @@
 include(RunCMake)
 
+if(CMake_TEST_RESOURCES)
+  run_cmake(ExplicitRC)
+endif()
 run_cmake(LanguagesImplicit)
 run_cmake(LanguagesEmpty)
 run_cmake(LanguagesNONE)
diff --git a/Tests/RunCMake/try_compile/CMP0066-stderr.txt b/Tests/RunCMake/try_compile/CMP0066-stderr.txt
new file mode 100644
index 0000000..b14e290
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CMP0066-stderr.txt
@@ -0,0 +1,15 @@
+before try_compile with CMP0066 WARN-default
+after try_compile with CMP0066 WARN-default
+*
+CMake Warning \(dev\) at CMP0066.cmake:[0-9]+ \(try_compile\):
+  Policy CMP0066 is not set: Honor per-config flags in try_compile\(\)
+  source-file signature.  Run "cmake --help-policy CMP0066" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  For compatibility with older versions of CMake, try_compile is not honoring
+  caller config-specific compiler flags \(e.g.  CMAKE_C_FLAGS_DEBUG\) in the
+  test project.
+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/try_compile/CMP0066-stdout.txt b/Tests/RunCMake/try_compile/CMP0066-stdout.txt
new file mode 100644
index 0000000..1eb2f83
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CMP0066-stdout.txt
@@ -0,0 +1,4 @@
+-- try_compile with CMP0066 WARN-default worked as expected
+-- try_compile with CMP0066 WARN-enabled worked as expected
+-- try_compile with CMP0066 OLD worked as expected
+-- try_compile with CMP0066 NEW worked as expected
diff --git a/Tests/RunCMake/try_compile/CMP0066.cmake b/Tests/RunCMake/try_compile/CMP0066.cmake
new file mode 100644
index 0000000..4b95251
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CMP0066.cmake
@@ -0,0 +1,58 @@
+enable_language(C)
+set(CMAKE_C_FLAGS_RELEASE "-DPP_ERROR ${CMAKE_C_FLAGS_DEBUG}")
+set(CMAKE_TRY_COMPILE_CONFIGURATION Release)
+
+#-----------------------------------------------------------------------------
+message("before try_compile with CMP0066 WARN-default")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  OUTPUT_VARIABLE out
+  )
+string(REPLACE "\n" "\n  " out "  ${out}")
+if(NOT RESULT)
+  message(FATAL_ERROR "try_compile with CMP0066 WARN-default failed but should have passed:\n${out}")
+else()
+  message(STATUS "try_compile with CMP0066 WARN-default worked as expected")
+endif()
+message("after try_compile with CMP0066 WARN-default")
+
+#-----------------------------------------------------------------------------
+set(CMAKE_POLICY_WARNING_CMP0066 ON)
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  OUTPUT_VARIABLE out
+  )
+string(REPLACE "\n" "\n  " out "  ${out}")
+if(NOT RESULT)
+  message(FATAL_ERROR "try_compile with CMP0066 WARN-enabled failed but should have passed:\n${out}")
+else()
+  message(STATUS "try_compile with CMP0066 WARN-enabled worked as expected")
+endif()
+
+#-----------------------------------------------------------------------------
+cmake_policy(SET CMP0066 OLD)
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  OUTPUT_VARIABLE out
+  )
+string(REPLACE "\n" "\n  " out "  ${out}")
+if(NOT RESULT)
+  message(FATAL_ERROR "try_compile with CMP0066 OLD failed but should have passed:\n${out}")
+else()
+  message(STATUS "try_compile with CMP0066 OLD worked as expected")
+endif()
+
+#-----------------------------------------------------------------------------
+cmake_policy(SET CMP0066 NEW)
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  OUTPUT_VARIABLE out
+  )
+string(REPLACE "\n" "\n  " out "  ${out}")
+if(RESULT)
+  message(FATAL_ERROR "try_compile with CMP0066 NEW passed but should have failed:\n${out}")
+elseif(NOT "x${out}" MATCHES "PP_ERROR is defined")
+  message(FATAL_ERROR "try_compile with CMP0066 NEW did not fail with PP_ERROR:\n${out}")
+else()
+  message(STATUS "try_compile with CMP0066 NEW worked as expected")
+endif()
diff --git a/Tests/RunCMake/try_compile/RunCMakeTest.cmake b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
index 4f30f1d..522433a 100644
--- a/Tests/RunCMake/try_compile/RunCMakeTest.cmake
+++ b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
@@ -25,6 +25,7 @@ run_cmake(TargetTypeInvalid)
 run_cmake(TargetTypeStatic)
 
 run_cmake(CMP0056)
+run_cmake(CMP0066)
 
 if(RunCMake_GENERATOR MATCHES "Make|Ninja")
   # Use a single build tree for a few tests without cleaning.
diff --git a/Tests/RunCMake/try_compile/src.c b/Tests/RunCMake/try_compile/src.c
index 8488f4e..5e51382 100644
--- a/Tests/RunCMake/try_compile/src.c
+++ b/Tests/RunCMake/try_compile/src.c
@@ -2,3 +2,6 @@ int main(void)
 {
   return 0;
 }
+#ifdef PP_ERROR
+#error PP_ERROR is defined
+#endif
diff --git a/Tests/Server/CMakeLists.txt b/Tests/Server/CMakeLists.txt
new file mode 100644
index 0000000..8913406
--- /dev/null
+++ b/Tests/Server/CMakeLists.txt
@@ -0,0 +1,26 @@
+cmake_minimum_required(VERSION 3.4)
+project(Server CXX)
+
+find_package(PythonInterp REQUIRED)
+
+macro(do_test bsname file)
+  execute_process(COMMAND ${PYTHON_EXECUTABLE}
+    "${CMAKE_SOURCE_DIR}/server-test.py"
+    "${CMAKE_COMMAND}"
+    "${CMAKE_SOURCE_DIR}/${file}"
+    "${CMAKE_SOURCE_DIR}"
+    "${CMAKE_BINARY_DIR}"
+    "${CMAKE_GENERATOR}"
+    RESULT_VARIABLE test_result
+    )
+
+  if (NOT test_result EQUAL 0)
+    message(SEND_ERROR "TEST FAILED")
+  endif()
+endmacro()
+
+do_test("test_handshake" "tc_handshake.json")
+do_test("test_globalSettings" "tc_globalSettings.json")
+do_test("test_buildsystem1" "tc_buildsystem1.json")
+
+add_executable(Server empty.cpp)
diff --git a/Tests/Server/buildsystem1/CMakeLists.txt b/Tests/Server/buildsystem1/CMakeLists.txt
new file mode 100644
index 0000000..d690472
--- /dev/null
+++ b/Tests/Server/buildsystem1/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 3.4)
+
+project(buildsystem2)
+
+set(var1 123)
+
+set(var2 345)
+
+add_executable(main main.cpp)
+
+add_executable(m_other main.cpp)
+
+add_library(foo foo.cpp)
+
+function(f1)
+endfunction()
+
+set(var3 345)
+
+add_library(someImportedLib UNKNOWN IMPORTED)
+
+add_subdirectory(subdir)
diff --git a/Tests/Server/buildsystem1/foo.cpp b/Tests/Server/buildsystem1/foo.cpp
new file mode 100644
index 0000000..7f39d71
--- /dev/null
+++ b/Tests/Server/buildsystem1/foo.cpp
@@ -0,0 +1,5 @@
+
+int foo()
+{
+  return 0;
+}
diff --git a/Tests/Server/buildsystem1/main.cpp b/Tests/Server/buildsystem1/main.cpp
new file mode 100644
index 0000000..766b775
--- /dev/null
+++ b/Tests/Server/buildsystem1/main.cpp
@@ -0,0 +1,5 @@
+
+int main()
+{
+  return 0;
+}
diff --git a/Tests/Server/buildsystem1/subdir/CMakeLists.txt b/Tests/Server/buildsystem1/subdir/CMakeLists.txt
new file mode 100644
index 0000000..9157312
--- /dev/null
+++ b/Tests/Server/buildsystem1/subdir/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(bar4 something)
+
+set(bar5 more)
+
+add_executable(ooo empty.cpp)
diff --git a/Tests/Server/buildsystem1/subdir/empty.cpp b/Tests/Server/buildsystem1/subdir/empty.cpp
new file mode 100644
index 0000000..7f39d71
--- /dev/null
+++ b/Tests/Server/buildsystem1/subdir/empty.cpp
@@ -0,0 +1,5 @@
+
+int foo()
+{
+  return 0;
+}
diff --git a/Tests/Server/cmakelib.py b/Tests/Server/cmakelib.py
new file mode 100644
index 0000000..94384eb
--- /dev/null
+++ b/Tests/Server/cmakelib.py
@@ -0,0 +1,198 @@
+import sys, subprocess, json
+
+termwidth = 150
+
+print_communication = True
+
+def ordered(obj):
+  if isinstance(obj, dict):
+    return sorted((k, ordered(v)) for k, v in obj.items())
+  if isinstance(obj, list):
+    return sorted(ordered(x) for x in obj)
+  else:
+    return obj
+
+def col_print(title, array):
+  print
+  print
+  print(title)
+
+  indentwidth = 4
+  indent = " " * indentwidth
+
+  if not array:
+    print(indent + "<None>")
+    return
+
+  padwidth = 2
+
+  maxitemwidth = len(max(array, key=len))
+
+  numCols = max(1, int((termwidth - indentwidth + padwidth) / (maxitemwidth + padwidth)))
+
+  numRows = len(array) // numCols + 1
+
+  pad = " " * padwidth
+
+  for index in range(numRows):
+    print(indent + pad.join(item.ljust(maxitemwidth) for item in array[index::numRows]))
+
+def waitForRawMessage(cmakeCommand):
+  stdoutdata = ""
+  payload = ""
+  while not cmakeCommand.poll():
+    stdoutdataLine = cmakeCommand.stdout.readline()
+    if stdoutdataLine:
+      stdoutdata += stdoutdataLine.decode('utf-8')
+    else:
+      break
+    begin = stdoutdata.find("[== CMake Server ==[\n")
+    end = stdoutdata.find("]== CMake Server ==]")
+
+    if (begin != -1 and end != -1):
+      begin += len("[== CMake Server ==[\n")
+      payload = stdoutdata[begin:end]
+      if print_communication:
+        print("\nSERVER>", json.loads(payload), "\n")
+      return json.loads(payload)
+
+def writeRawData(cmakeCommand, content):
+  writeRawData.counter += 1
+  payload = """
+[== CMake Server ==[
+%s
+]== CMake Server ==]
+""" % content
+
+  rn = ( writeRawData.counter % 2 ) == 0
+
+  if rn:
+    payload = payload.replace('\n', '\r\n')
+
+  if print_communication:
+    print("\nCLIENT>", content, "(Use \\r\\n:", rn, ")\n")
+  cmakeCommand.stdin.write(payload.encode('utf-8'))
+  cmakeCommand.stdin.flush()
+writeRawData.counter = 0
+
+def writePayload(cmakeCommand, obj):
+  writeRawData(cmakeCommand, json.dumps(obj))
+
+def initProc(cmakeCommand):
+  cmakeCommand = subprocess.Popen([cmakeCommand, "-E", "server", "--experimental", "--debug"],
+                                  stdin=subprocess.PIPE,
+                                  stdout=subprocess.PIPE)
+
+  packet = waitForRawMessage(cmakeCommand)
+  if packet == None:
+    print("Not in server mode")
+    sys.exit(1)
+
+  if packet['type'] != 'hello':
+    print("No hello message")
+    sys.exit(1)
+
+  return cmakeCommand
+
+def waitForMessage(cmakeCommand, expected):
+  data = ordered(expected)
+  packet = ordered(waitForRawMessage(cmakeCommand))
+
+  if packet != data:
+    sys.exit(-1)
+  return packet
+
+def waitForReply(cmakeCommand, originalType, cookie, skipProgress):
+  gotResult = False
+  while True:
+    packet = waitForRawMessage(cmakeCommand)
+    t = packet['type']
+    if packet['cookie'] != cookie or packet['inReplyTo'] != originalType:
+      sys.exit(1)
+    if t == 'message' or t == 'progress':
+      if skipProgress:
+        continue
+    if t == 'reply':
+        break
+    sys.exit(1)
+
+  return packet
+
+def waitForError(cmakeCommand, originalType, cookie, message):
+  packet = waitForRawMessage(cmakeCommand)
+  if packet['cookie'] != cookie or packet['type'] != 'error' or packet['inReplyTo'] != originalType or packet['errorMessage'] != message:
+    sys.exit(1)
+
+def waitForProgress(cmakeCommand, originalType, cookie, current, message):
+  packet = waitForRawMessage(cmakeCommand)
+  if packet['cookie'] != cookie or packet['type'] != 'progress' or packet['inReplyTo'] != originalType or packet['progressCurrent'] != current or packet['progressMessage'] != message:
+    sys.exit(1)
+
+def handshake(cmakeCommand, major, minor, source, build, generator, extraGenerator):
+  version = { 'major': major }
+  if minor >= 0:
+    version['minor'] = minor
+
+  writePayload(cmakeCommand, { 'type': 'handshake', 'protocolVersion': version,
+    'cookie': 'TEST_HANDSHAKE', 'sourceDirectory': source, 'buildDirectory': build,
+    'generator': generator, 'extraGenerator': extraGenerator })
+  waitForReply(cmakeCommand, 'handshake', 'TEST_HANDSHAKE', False)
+
+def validateGlobalSettings(cmakeCommand, cmakeCommandPath, data):
+  packet = waitForReply(cmakeCommand, 'globalSettings', '', False)
+
+  capabilities = packet['capabilities']
+
+  # validate version:
+  cmakeoutput = subprocess.check_output([ cmakeCommandPath, "--version" ], universal_newlines=True)
+  cmakeVersion = cmakeoutput.splitlines()[0][14:]
+
+  version = capabilities['version']
+  versionString = version['string']
+  vs = str(version['major']) + '.' + str(version['minor']) + '.' + str(version['patch'])
+  if (versionString != vs and not versionString.startswith(vs + '-')):
+    sys.exit(1)
+  if (versionString != cmakeVersion):
+    sys.exit(1)
+
+  # validate generators:
+  generatorObjects = capabilities['generators']
+
+  cmakeoutput = subprocess.check_output([ cmakeCommandPath, "--help" ], universal_newlines=True)
+  index = cmakeoutput.index('\nGenerators\n\n')
+  cmakeGenerators = []
+  for line in cmakeoutput[index + 12:].splitlines():
+    if not line.startswith('  '):
+      continue
+    if line.startswith('    '):
+      continue
+    equalPos = line.find('=')
+    tmp = ''
+    if (equalPos > 0):
+      tmp = line[2:equalPos].strip()
+    else:
+      tmp = line.strip()
+    if tmp.endswith(" [arch]"):
+      tmp = tmp[0:len(tmp) - 7]
+    if (len(tmp) > 0) and (" - " not in tmp) and (tmp != 'KDevelop3'):
+      cmakeGenerators.append(tmp)
+
+  generators = []
+  for genObj in generatorObjects:
+    generators.append(genObj['name'])
+
+  generators.sort()
+  cmakeGenerators.sort()
+
+  for gen in cmakeGenerators:
+    if (not gen in generators):
+        sys.exit(1)
+
+  gen = packet['generator']
+  if (gen != '' and not (gen in generators)):
+    sys.exit(1)
+
+  for i in data:
+    print("Validating", i)
+    if (packet[i] != data[i]):
+      sys.exit(1)
diff --git a/Tests/Server/cmakelib.pyc b/Tests/Server/cmakelib.pyc
new file mode 100644
index 0000000..5c1975e
Binary files /dev/null and b/Tests/Server/cmakelib.pyc differ
diff --git a/Tests/Server/empty.cpp b/Tests/Server/empty.cpp
new file mode 100644
index 0000000..766b775
--- /dev/null
+++ b/Tests/Server/empty.cpp
@@ -0,0 +1,5 @@
+
+int main()
+{
+  return 0;
+}
diff --git a/Tests/Server/server-test.py b/Tests/Server/server-test.py
new file mode 100644
index 0000000..14767f4
--- /dev/null
+++ b/Tests/Server/server-test.py
@@ -0,0 +1,119 @@
+import sys, cmakelib, json, os, shutil
+
+debug = True
+
+cmakeCommand = sys.argv[1]
+testFile = sys.argv[2]
+sourceDir = sys.argv[3]
+buildDir = sys.argv[4] + "/" + os.path.splitext(os.path.basename(testFile))[0]
+cmakeGenerator = sys.argv[5]
+
+print("Test:", testFile,
+      "\n-- SourceDir:", sourceDir,
+      "\n-- BuildDir:", buildDir,
+      "\n-- Generator:", cmakeGenerator)
+
+if os.path.exists(buildDir):
+    shutil.rmtree(buildDir)
+
+proc = cmakelib.initProc(cmakeCommand)
+
+with open(testFile) as f:
+    testData = json.loads(f.read())
+
+for obj in testData:
+    if 'sendRaw' in obj:
+        data = obj['sendRaw']
+        if debug: print("Sending raw:", data)
+        cmakelib.writeRawData(proc, data)
+    elif 'send' in obj:
+        data = obj['send']
+        if debug: print("Sending:", json.dumps(data))
+        cmakelib.writePayload(proc, data)
+    elif 'recv' in obj:
+        data = obj['recv']
+        if debug: print("Waiting for:", json.dumps(data))
+        cmakelib.waitForMessage(proc, data)
+    elif 'reply' in obj:
+        data = obj['reply']
+        if debug: print("Waiting for reply:", json.dumps(data))
+        originalType = ""
+        cookie = ""
+        skipProgress = False;
+        if 'cookie' in data: cookie = data['cookie']
+        if 'type' in data: originalType = data['type']
+        if 'skipProgress' in data: skipProgress = data['skipProgress']
+        cmakelib.waitForReply(proc, originalType, cookie, skipProgress)
+    elif 'error' in obj:
+        data = obj['error']
+        if debug: print("Waiting for error:", json.dumps(data))
+        originalType = ""
+        cookie = ""
+        message = ""
+        if 'cookie' in data: cookie = data['cookie']
+        if 'type' in data: originalType = data['type']
+        if 'message' in data: message = data['message']
+        cmakelib.waitForError(proc, originalType, cookie, message)
+    elif 'progress' in obj:
+        data = obj['progress']
+        if debug: print("Waiting for progress:", json.dumps(data))
+        originalType = ''
+        cookie = ""
+        current = 0
+        message = ""
+        if 'cookie' in data: cookie = data['cookie']
+        if 'type' in data: originalType = data['type']
+        if 'current' in data: current = data['current']
+        if 'message' in data: message = data['message']
+        cmakelib.waitForProgress(proc, originalType, cookie, current, message)
+    elif 'handshake' in obj:
+        data = obj['handshake']
+        if debug: print("Doing handshake:", json.dumps(data))
+        major = -1
+        minor = -1
+        generator = cmakeGenerator
+        extraGenerator = ''
+        sourceDirectory = sourceDir
+        buildDirectory = buildDir
+        if 'major' in data: major = data['major']
+        if 'minor' in data: minor = data['minor']
+        if 'buildDirectory' in data: buildDirectory = data['buildDirectory']
+        if 'sourceDirectory' in data: sourceDirectory = data['sourceDirectory']
+        if 'generator' in data: generator = data['generator']
+        if 'extraGenerator' in data: extraGenerator = data['extraGenerator']
+        if not os.path.isabs(buildDirectory):
+            buildDirectory = buildDir + "/" + buildDirectory
+        if not os.path.isabs(sourceDirectory):
+            sourceDirectory = sourceDir + "/" + sourceDirectory
+        cmakelib.handshake(proc, major, minor, sourceDirectory, buildDirectory,
+          generator, extraGenerator)
+    elif 'validateGlobalSettings' in obj:
+        data = obj['validateGlobalSettings']
+        if not 'buildDirectory' in data: data['buildDirectory'] = buildDir
+        if not 'sourceDirectory' in data: data['sourceDirectory'] = sourceDir
+        if not 'generator' in data: data['generator'] = cmakeGenerator
+        if not 'extraGenerator' in data: data['extraGenerator'] = ''
+        cmakelib.validateGlobalSettings(proc, cmakeCommand, data)
+    elif 'message' in obj:
+        print("MESSAGE:", obj["message"])
+    else:
+        print("Unknown command:", json.dumps(obj))
+        sys.exit(2)
+
+    print("Completed")
+
+# Tell the server to exit.
+proc.stdin.close()
+proc.stdout.close()
+
+# Wait for the server to exit.
+# If this version of python supports it, terminate the server after a timeout.
+try:
+    proc.wait(timeout=5)
+except TypeError:
+    proc.wait()
+except:
+    proc.terminate()
+    raise
+
+sys.exit(0)
diff --git a/Tests/Server/tc_buildsystem1.json b/Tests/Server/tc_buildsystem1.json
new file mode 100644
index 0000000..08831b7
--- /dev/null
+++ b/Tests/Server/tc_buildsystem1.json
@@ -0,0 +1,27 @@
+[
+{ "message": "Testing globalSettings" },
+
+{ "handshake": {"major": 1, "sourceDirectory":"buildsystem1","buildDirectory":"buildsystem1"} },
+
+{ "message": "Configure:" },
+{ "send": { "type": "configure", "cookie":"CONFIG" } },
+{ "reply": { "type": "configure", "cookie":"CONFIG", "skipProgress":true } },
+
+{ "message": "Compute:" },
+{ "send": { "type": "compute", "cookie":"COMPUTE" } },
+{ "reply": { "type": "compute", "cookie":"COMPUTE", "skipProgress":true } },
+
+{ "message": "Codemodel:" },
+{ "send": { "type": "codemodel", "cookie":"CODEMODEL" } },
+{ "reply": { "type": "codemodel", "cookie":"CODEMODEL" } },
+
+{ "message": "CMake Inputs:"},
+{ "send": { "type": "cmakeInputs", "cookie":"INPUTS" } },
+{ "reply": { "type": "cmakeInputs", "cookie":"INPUTS" } },
+
+{ "message": "Cache:"},
+{ "send": { "type": "cache", "cookie":"CACHE" } },
+{ "reply": { "type": "cache", "cookie":"CACHE" } },
+
+{ "message": "Everything ok." }
+]
diff --git a/Tests/Server/tc_globalSettings.json b/Tests/Server/tc_globalSettings.json
new file mode 100644
index 0000000..d72fb41
--- /dev/null
+++ b/Tests/Server/tc_globalSettings.json
@@ -0,0 +1,140 @@
+[
+{ "message": "Testing globalSettings" },
+
+{ "handshake": {"major": 1} },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+
+
+{ "message": "Change settings:" },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": true, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "debugOutput": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": true, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "debugOutput": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUninitialized": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": true, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUninitialized": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "traceExpand": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": true, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "traceExpand": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+
+
+{ "send": { "type": "setGlobalSettings", "trace": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": true, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "trace": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnusedCli": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": false, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnusedCli": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "checkSystemVars": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": true } },
+
+{ "send": { "type": "setGlobalSettings", "checkSystemVars": false } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": false, "debugOutput": false, "warnUninitialized": false, "traceExpand": false, "trace": false, "warnUnusedCli": true, "checkSystemVars": false } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true, "debugOutput": true, "warnUninitialized": true, "traceExpand": true, "trace": true, "warnUnusedCli": false, "checkSystemVars": true } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": true, "debugOutput": true, "warnUninitialized": true, "traceExpand": true, "trace": true, "warnUnusedCli": false, "checkSystemVars": true } },
+
+{ "message": "Ignore unknown/readonly" },
+
+{ "send": { "type": "setGlobalSettings", "unknownKey": "unknownValue", "extraGenerator": "XXX", "generator": "YYY", "sourceDirectory": "/tmp/source", "buildDirectory": "/tmp/build" } },
+{ "reply": { "type": "setGlobalSettings" } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": true, "debugOutput": true, "warnUninitialized": true, "traceExpand": true, "trace": true, "warnUnusedCli": false, "checkSystemVars": true } },
+
+{ "message": "Error paths:" },
+
+{ "send": { "type": "setGlobalSettings", "debugOutput": true, "warnUnused": 1 } },
+{ "error": { "type": "setGlobalSettings", "message": "\"warnUnused\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true, "debugOutput": 1 } },
+{ "error": { "type": "setGlobalSettings", "message": "\"debugOutput\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "warnUninitialized": 1, "warnUnused": true, "debugOutput": true } },
+{ "error": { "type": "setGlobalSettings", "message": "\"warnUninitialized\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true, "debugOutput": true, "traceExpand": 1 } },
+{ "error": { "type": "setGlobalSettings", "message": "\"traceExpand\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "debugOutput": true, "trace": 1, "warnUnused": true } },
+{ "error": { "type": "setGlobalSettings", "message": "\"trace\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true, "debugOutput": true, "warnUnusedCli": 1.0 } },
+{ "error": { "type": "setGlobalSettings", "message": "\"warnUnusedCli\" must be unset or a bool value." } },
+
+{ "send": { "type": "setGlobalSettings", "warnUnused": true, "debugOutput": true, "checkSystemVars": "some string" } },
+{ "error": { "type": "setGlobalSettings", "message": "\"checkSystemVars\" must be unset or a bool value." } },
+
+{ "send": { "type": "globalSettings"} },
+{ "validateGlobalSettings": { "warnUnused": true, "debugOutput": true, "warnUninitialized": true, "traceExpand": true, "trace": true, "warnUnusedCli": false, "checkSystemVars": true } },
+
+{ "message": "Everything ok." }
+]
diff --git a/Tests/Server/tc_handshake.json b/Tests/Server/tc_handshake.json
new file mode 100644
index 0000000..5261581
--- /dev/null
+++ b/Tests/Server/tc_handshake.json
@@ -0,0 +1,71 @@
+[
+{ "message": "Testing basic message handling:" },
+
+{ "sendRaw": "Sometext"},
+{ "recv": {"cookie":"","errorMessage":"Failed to parse JSON input.","inReplyTo":"","type":"error"} },
+
+{ "message": "Testing invalid json input"},
+{ "send": { "test": "sometext" } },
+{ "recv": {"cookie":"","errorMessage":"No type given in request.","inReplyTo":"","type":"error"} },
+
+{ "send": {"test": "sometext","cookie":"monster"} },
+{ "recv": {"cookie":"monster","errorMessage":"No type given in request.","inReplyTo":"","type":"error"} },
+
+{ "message": "Testing handshake" },
+{ "send": {"type": "sometype","cookie":"monster2"} },
+{ "recv": {"cookie":"monster2","errorMessage":"Waiting for type \"handshake\".","inReplyTo":"sometype","type":"error"} },
+
+{ "send": {"type": "handshake"} },
+{ "recv": {"cookie":"","errorMessage":"\"protocolVersion\" is required for \"handshake\".","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","foo":"bar"} },
+{ "recv": {"cookie":"","errorMessage":"\"protocolVersion\" is required for \"handshake\".","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":"bar"} },
+{ "recv": {"cookie":"","errorMessage":"\"protocolVersion\" must be a JSON object.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{}} },
+{ "recv": {"cookie":"","errorMessage":"\"major\" must be set and an integer.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":"foo"}} },
+{ "recv": {"cookie":"","errorMessage":"\"major\" must be set and an integer.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":1, "minor":"foo"}} },
+{ "recv": {"cookie":"","errorMessage":"\"minor\" must be unset or an integer.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":-1, "minor":-1}} },
+{ "recv": {"cookie":"","errorMessage":"\"major\" must be >= 0.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":10, "minor":-1}} },
+{ "recv": {"cookie":"","errorMessage":"\"minor\" must be >= 0 when set.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":10000}} },
+{ "recv": {"cookie":"","errorMessage":"Protocol version not supported.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"type": "handshake","protocolVersion":{"major":1, "minor":10000}} },
+{ "recv": {"cookie":"","errorMessage":"Protocol version not supported.","inReplyTo":"handshake","type":"error"} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1}} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: \"buildDirectory\" is missing."} },
+
+{ "message": "Testing protocol version specific options (1.0):" },
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":"/tmp/src"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: \"buildDirectory\" is missing."} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":"/tmp/src","buildDirectory":"/tmp/build"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: \"sourceDirectory\" is not a directory."} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":".","buildDirectory":"/tmp/build","extraGenerator":"CodeBlocks"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: \"generator\" is unset but required."} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":".","buildDirectory":"/tmp/build","generator":"XXXX","extraGenerator":"CodeBlocks"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: Could not set up the requested combination of \"generator\" and \"extraGenerator\""} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":".","buildDirectory":"/tmp/build","generator":"Ninja","extraGenerator":"XXXX"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"error","errorMessage":"Failed to activate protocol version: Could not set up the requested combination of \"generator\" and \"extraGenerator\""} },
+
+{ "send": {"cookie":"zimtstern","type": "handshake","protocolVersion":{"major":1},"sourceDirectory":".","buildDirectory":"/tmp/build","generator":"Ninja","extraGenerator":"CodeBlocks"} },
+{ "recv": {"cookie":"zimtstern","inReplyTo":"handshake","type":"reply"} },
+
+{ "message": "Everything ok." }
+]
diff --git a/Tests/SimpleInstall/CMakeLists.txt b/Tests/SimpleInstall/CMakeLists.txt
index aee92f6..4cf7355 100644
--- a/Tests/SimpleInstall/CMakeLists.txt
+++ b/Tests/SimpleInstall/CMakeLists.txt
@@ -348,7 +348,7 @@ if(UNIX AND NOT APPLE)
   #    if(NOT SKIP_TZ)
   #      message("compress found and it was not a script")
   #      message("output from file command: [${output}]")
-  #      set(CPACK_GENERATOR "${CPACK_GENERATOR};TZ")
+  #      list(APPEND CPACK_GENERATOR "TZ")
   #    else()
   #      message("compress found, but it was a script so dont use it")
   #      message("output from file command: [${output}]")
@@ -357,7 +357,7 @@ if(UNIX AND NOT APPLE)
   find_program(found_bz2
     NAMES bzip2)
   if(found_bz2)
-    set(CPACK_GENERATOR "${CPACK_GENERATOR};TBZ2")
+    list(APPEND CPACK_GENERATOR "TBZ2")
   endif()
 endif()
 
diff --git a/Tests/SimpleInstallS2/CMakeLists.txt b/Tests/SimpleInstallS2/CMakeLists.txt
index aee92f6..4cf7355 100644
--- a/Tests/SimpleInstallS2/CMakeLists.txt
+++ b/Tests/SimpleInstallS2/CMakeLists.txt
@@ -348,7 +348,7 @@ if(UNIX AND NOT APPLE)
   #    if(NOT SKIP_TZ)
   #      message("compress found and it was not a script")
   #      message("output from file command: [${output}]")
-  #      set(CPACK_GENERATOR "${CPACK_GENERATOR};TZ")
+  #      list(APPEND CPACK_GENERATOR "TZ")
   #    else()
   #      message("compress found, but it was a script so dont use it")
   #      message("output from file command: [${output}]")
@@ -357,7 +357,7 @@ if(UNIX AND NOT APPLE)
   find_program(found_bz2
     NAMES bzip2)
   if(found_bz2)
-    set(CPACK_GENERATOR "${CPACK_GENERATOR};TBZ2")
+    list(APPEND CPACK_GENERATOR "TBZ2")
   endif()
 endif()
 
diff --git a/Tests/SwiftOnly/CMakeLists.txt b/Tests/SwiftOnly/CMakeLists.txt
index 5cb9739..cf4463c 100644
--- a/Tests/SwiftOnly/CMakeLists.txt
+++ b/Tests/SwiftOnly/CMakeLists.txt
@@ -1,4 +1,8 @@
 cmake_minimum_required(VERSION 3.3)
 project(SwiftOnly Swift)
 
+if(NOT XCODE_VERSION VERSION_LESS 8.0)
+  set(CMAKE_Swift_LANGUAGE_VERSION 3.0)
+endif()
+
 add_executable(SwiftOnly main.swift)
diff --git a/Tests/TryCompile/CMakeLists.txt b/Tests/TryCompile/CMakeLists.txt
index d11cfc5..2f8e4fb 100644
--- a/Tests/TryCompile/CMakeLists.txt
+++ b/Tests/TryCompile/CMakeLists.txt
@@ -109,9 +109,9 @@ endif()
 # try to compile a file that should compile
 set(_c_flags "${CMAKE_C_FLAGS}")
 if(WATCOM)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -dTESTDEF")
+  string(APPEND CMAKE_C_FLAGS " -dTESTDEF")
 else()
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} \"-DTESTDEF\"")
+  string(APPEND CMAKE_C_FLAGS " \"-DTESTDEF\"")
 endif()
 try_compile(SHOULD_PASS
     ${TryCompile_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp
diff --git a/Tests/VSExternalInclude/CMakeLists.txt b/Tests/VSExternalInclude/CMakeLists.txt
index 20301c2..7465243 100644
--- a/Tests/VSExternalInclude/CMakeLists.txt
+++ b/Tests/VSExternalInclude/CMakeLists.txt
@@ -1,7 +1,7 @@
 cmake_minimum_required (VERSION 2.6)
 project(VSExternalInclude)
 
-if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[0124]")
+if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[01245]")
   set(PROJECT_EXT vcxproj)
 else()
   set(PROJECT_EXT vcproj)
@@ -55,7 +55,7 @@ add_dependencies(VSExternalInclude lib2)
 # and the sln file can no longer be the only source
 # of that depend.  So, for VS 10 make the executable
 # depend on lib1 and lib2
-if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[0124]")
+if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[01245]")
   add_dependencies(VSExternalInclude lib1)
 endif()
 
diff --git a/Tests/VSMASM/CMakeLists.txt b/Tests/VSMASM/CMakeLists.txt
index f2570a3..2923e15 100644
--- a/Tests/VSMASM/CMakeLists.txt
+++ b/Tests/VSMASM/CMakeLists.txt
@@ -4,7 +4,7 @@ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
   add_definitions(-DTESTx64)
 else()
   add_definitions(-DTESTi386)
-  set(CMAKE_ASM_MASM_FLAGS "${CMAKE_ASM_MASM_FLAGS} /safeseh")
+  string(APPEND CMAKE_ASM_MASM_FLAGS " /safeseh")
 endif()
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
 add_executable(VSMASM main.c foo.asm)
diff --git a/Tests/VSNsightTegra/CMakeLists.txt b/Tests/VSNsightTegra/CMakeLists.txt
index 61a04fd..6d74f2f 100644
--- a/Tests/VSNsightTegra/CMakeLists.txt
+++ b/Tests/VSNsightTegra/CMakeLists.txt
@@ -1,7 +1,7 @@
 cmake_minimum_required(VERSION 3.3)
 project(VSNsightTegra C CXX)
 
-set(CMAKE_ANDROID_ARCH armv7-a-hard)
+set(CMAKE_ANDROID_ARCH armv7-a)
 set(CMAKE_ANDROID_STL_TYPE stlport_shared)
 set(CMAKE_ANDROID_API_MIN 9)
 set(CMAKE_ANDROID_API 15)
diff --git a/Tests/VSWinStorePhone/CMakeLists.txt b/Tests/VSWinStorePhone/CMakeLists.txt
index ae82755..2b0c478 100644
--- a/Tests/VSWinStorePhone/CMakeLists.txt
+++ b/Tests/VSWinStorePhone/CMakeLists.txt
@@ -98,13 +98,17 @@ elseif (NOT "${PLATFORM}" STREQUAL "DESKTOP")
     )
 endif()
 
+set(STRING_FILES
+  Direct3DApp1/Strings/en-US/Resources.resw)
+
 set(RESOURCE_FILES
-  ${CONTENT_FILES} ${DEBUG_CONTENT_FILES} ${RELEASE_CONTENT_FILES} ${ASSET_FILES}
+  ${CONTENT_FILES} ${DEBUG_CONTENT_FILES} ${RELEASE_CONTENT_FILES} ${ASSET_FILES} ${STRING_FILES}
   Direct3DApp1/Direct3DApp1_TemporaryKey.pfx)
 
 set_property(SOURCE ${CONTENT_FILES} PROPERTY VS_DEPLOYMENT_CONTENT 1)
 set_property(SOURCE ${ASSET_FILES} PROPERTY VS_DEPLOYMENT_CONTENT 1)
 set_property(SOURCE ${ASSET_FILES} PROPERTY VS_DEPLOYMENT_LOCATION "Assets")
+set_property(SOURCE ${STRING_FILES} PROPERTY VS_TOOL_OVERRIDE "PRIResource")
 set_property(SOURCE ${DEBUG_CONTENT_FILES} PROPERTY VS_DEPLOYMENT_CONTENT $<CONFIG:Debug>)
 set_property(SOURCE ${RELEASE_CONTENT_FILES} PROPERTY
   VS_DEPLOYMENT_CONTENT $<OR:$<CONFIG:Release>,$<CONFIG:RelWithDebInfo>,$<CONFIG:MinSizeRel>>)
@@ -134,6 +138,9 @@ if("${SHORT_VERSION}" STREQUAL "10.0")
   set_property(TARGET ${EXE_NAME} PROPERTY VS_DESKTOP_EXTENSIONS_VERSION "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}")
   set_property(TARGET ${EXE_NAME} PROPERTY VS_MOBILE_EXTENSIONS_VERSION "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}")
   set_property(TARGET ${EXE_NAME} PROPERTY VS_IOT_EXTENSIONS_VERSION "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}")
+
+  # Add a reference to an SDK
+  set_property(TARGET ${EXE_NAME} PROPERTY VS_SDK_REFERENCES "Microsoft.UniversalCRT.Debug, Version=${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}")
 endif()
 
 
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Strings/en-US/Resources.resw b/Tests/VSWinStorePhone/Direct3DApp1/Strings/en-US/Resources.resw
new file mode 100644
index 0000000..8c2c8ae
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Strings/en-US/Resources.resw
@@ -0,0 +1,123 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!--
+    Microsoft ResX Schema
+
+    Version 2.0
+
+    The primary goals of this format is to allow a simple XML format
+    that is mostly human readable. The generation and parsing of the
+    various data types are done through the TypeConverter classes
+    associated with the data types.
+
+    Example:
+
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+
+    There are any number of "resheader" rows that contain simple
+    name/value pairs.
+
+    Each data row contains a name, and value. The row also contains a
+    type or mimetype. Type corresponds to a .NET class that support
+    text/value conversion through the TypeConverter architecture.
+    Classes that don't support this are serialized and stored with the
+    mimetype set.
+
+    The mimetype is used for serialized objects, and tells the
+    ResXResourceReader how to depersist the object. This is currently not
+    extensible. For a given mimetype the value must be set accordingly:
+
+    Note - application/x-microsoft.net.object.binary.base64 is the format
+    that the ResXResourceWriter will generate, however the reader can
+    read any of the formats listed below.
+
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <data name="TestString" xml:space="preserve">
+    <value>Test String</value>
+  </data>
+</root>
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index cf6bb72..1e51ea2 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 subdirs(Doxygen KWStyle)
 
 if(CMAKE_DOC_TARBALL)
diff --git a/Utilities/Doxygen/CMakeLists.txt b/Utilities/Doxygen/CMakeLists.txt
index 813e34d..f1e8f95 100644
--- a/Utilities/Doxygen/CMakeLists.txt
+++ b/Utilities/Doxygen/CMakeLists.txt
@@ -1,39 +1,96 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(NOT CMake_SOURCE_DIR)
+  set(CMakeDeveloperReference_STANDALONE 1)
+  cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
+  get_filename_component(tmp "${CMAKE_CURRENT_SOURCE_DIR}" PATH)
+  get_filename_component(CMake_SOURCE_DIR "${tmp}" PATH)
+  include(${CMake_SOURCE_DIR}/Modules/CTestUseLaunchers.cmake)
+  include(${CMake_SOURCE_DIR}/Source/CMakeVersionCompute.cmake)
+  include(${CMake_SOURCE_DIR}/Source/CMakeInstallDestinations.cmake)
+  unset(CMAKE_DATA_DIR)
+  unset(CMAKE_DATA_DIR CACHE)
+  macro(CMake_OPTIONAL_COMPONENT)
+    set(COMPONENT "")
+  endmacro()
+endif()
+
+project(CMakeDeveloperReference NONE)
 
 #
-# Build the documentation
+# Build the reference
 #
-include (${CMAKE_ROOT}/Modules/Documentation.cmake OPTIONAL)
 
-if (BUILD_DOCUMENTATION)
+if (CMake_BUILD_DEVELOPER_REFERENCE OR CMakeDeveloperReference_STANDALONE)
+
+  find_package(Doxygen REQUIRED)
+
+  #
+  ## Output formats
+  #
+
+  option(CMake_BUILD_DEVELOPER_REFERENCE_HTML "Build CMake Developer Reference - HTML format" ON)
+  mark_as_advanced(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+  if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+    set(GENERATE_HTML YES)
+  else()
+    set(GENERATE_HTML NO)
+  endif()
+
+  option(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP "Build CMake Developer Reference - QtHelp format" OFF)
+  mark_as_advanced(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
+  if(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
+    set(GENERATE_QHP YES)
+    find_program(QHELPGENERATOR_EXECUTABLE
+      NAMES qhelpgenerator
+      DOC "qhelpgenerator tool"
+      )
+    if(NOT QHELPGENERATOR_EXECUTABLE)
+      message(FATAL_ERROR "QHELPGENERATOR_EXECUTABLE (qhelpgenerator) not found!")
+    endif()
+  else()
+    set(GENERATE_QHP NO)
+  endif()
 
   #
   # Configure the script and the doxyfile, then add target
   #
+
+  if(DOXYGEN_DOT_FOUND)
+    set(HAVE_DOT YES)
+  else()
+    set(HAVE_DOT NO)
+  endif()
+
   if(NOT DOT_PATH)
-    get_filename_component(DOT_PATH ${DOT} PATH)
+    get_filename_component(DOT_PATH ${DOXYGEN_DOT_EXECUTABLE} PATH)
   endif()
 
-  configure_file(
-    ${CMake_SOURCE_DIR}/Utilities/Doxygen/doxyfile.in
-    ${CMake_BINARY_DIR}/Utilities/Doxygen/doxyfile)
+  configure_file(doxyfile.in doxyfile @ONLY)
+
+  add_custom_target(cmake-developer-reference-all
+    ${DOXYGEN_EXECUTABLE} doxyfile
+    WORKING_DIRECTORY ${CMakeDeveloperReference_BINARY_DIR})
 
-  configure_file(
-    ${CMake_SOURCE_DIR}/Utilities/Doxygen/doc_makeall.sh.in
-    ${CMake_BINARY_DIR}/Utilities/Doxygen/doc_makeall.sh)
+  add_custom_target(cmake-developer-reference ALL DEPENDS cmake-developer-reference-all)
 
-  add_custom_target(DoxygenDoc
-    ${BASH}
-    ${CMake_BINARY_DIR}/Utilities/Doxygen/doc_makeall.sh)
+  #
+  # Installation
+  #
+
+  if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+    CMake_OPTIONAL_COMPONENT(cmake-developer-reference-html)
+    install(DIRECTORY "${CMakeDeveloperReference_BINARY_DIR}/developer-reference/html"
+      DESTINATION ${CMAKE_DOC_DIR}/developer-reference
+      ${COMPONENT})
+  endif()
+
+  if(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
+    CMake_OPTIONAL_COMPONENT(cmake-developer-reference-qthelp)
+    install(FILES "${CMakeDeveloperReference_BINARY_DIR}/developer-reference/CMakeDeveloperReference-${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR}${CMake_VERSION_PATCH}.qch"
+      DESTINATION ${CMAKE_DOC_DIR}/developer-reference
+      ${COMPONENT})
+  endif()
 
 endif ()
diff --git a/Utilities/Doxygen/DeveloperReference/mainpage.dox b/Utilities/Doxygen/DeveloperReference/mainpage.dox
new file mode 100644
index 0000000..a37927f
--- /dev/null
+++ b/Utilities/Doxygen/DeveloperReference/mainpage.dox
@@ -0,0 +1,8 @@
+/*!
+
+\mainpage CMake Developer Reference
+
+This manual is intended for reference by developers modifying the CMake
+source tree itself.
+
+*/
diff --git a/Utilities/Doxygen/authors.txt b/Utilities/Doxygen/authors.txt
deleted file mode 100644
index 9ba6cca..0000000
--- a/Utilities/Doxygen/authors.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-andy: Cedilnik, Andy (andy.cedilnik at kitware.com)
-barre: Barre, Sebastien (sebastien.barre at kitware.com)
-berk: Geveci, Berk (berk.geveci at kitware.com)
-bettingf: Bettinger, Franck (bettingf at cs.man.ac.uk)
-biddi: Biddiscombe, John (jbiddiscombe at skippingmouse.co.uk)
-blezek: Blezek, Dan (blezek at crd.ge.com)
-geoff: Cross, Geoffrey (geoff at robots.ox.ac.uk)
-hoffman: Hoffman, Bill (bill.hoffman at kitware.com)
-ibanez: Ibanez, Luis (luis.ibanez at kitware.com)
-iscott: Scott, Ian (ian.m.scott at stud.man.ac.uk)
-king: King, Brad (brad.king at kitware.com)
-lorensen: Lorensen, Bill (lorensen at crd.ge.com)
-martink, lymbdemo: Martin, Ken (ken.martin at kitware.com)
-millerjv: Miller, Jim (millerjv at crd.ge.com)
-perera: Perera, Amitha (perera at cs.rpi.edu)
-starreveld: Starreveld, Yves (ystarrev at julian.uwo.ca)
-will, schroede: Schroeder, Will (will.schroeder at kitware.com)
diff --git a/Utilities/Doxygen/doc_makeall.sh.in b/Utilities/Doxygen/doc_makeall.sh.in
deleted file mode 100755
index fceafdd..0000000
--- a/Utilities/Doxygen/doc_makeall.sh.in
+++ /dev/null
@@ -1,248 +0,0 @@
-# -------------------------------------------------------------------------
-# Doxygen documentation batch
-# modified by S. Barre (Time-stamp: <2003-01-16 14:04:41 barre>
-# -------------------------------------------------------------------------
-
-# Path to several tools (_PROG to avoid the typical GZIP env var pb)
-# Example:
-#   DOXYGEN_PROG=@DOXYGEN@   (INCLUDE(${CMAKE_ROOT}/Modules/FindDoxygen.cmake))
-#   GZIP_PROG=@GZIP@         (INCLUDE(${CMAKE_ROOT}/Modules/FindCygwin.cmake))
-#   HHC_PROG=@HHC@           (INCLUDE(${CMAKE_ROOT}/Modules/FindHhc.cmake))
-#   MV_PROG=@MV@             (INCLUDE(${CMAKE_ROOT}/Modules/FindCygwin.cmake))
-#   PERL_PROG=@PERL@         (INCLUDE(${CMAKE_ROOT}/Modules/FindPerl.cmake))
-#   RM_PROG=@RM@             (INCLUDE(${CMAKE_ROOT}/Modules/FindCygwin.cmake))
-#   TAR_PROG=@TAR@           (INCLUDE(${CMAKE_ROOT}/Modules/FindCygwin.cmake))
-#   WGET_PROG=@WGET@         (INCLUDE(${CMAKE_ROOT}/Modules/FindWget.cmake))
-#
-export DOXYGEN_PROG="@DOXYGEN@"        # Doxygen
-export GZIP_PROG="@GZIP@"              # gzip (Unix-like 'gzip compressor')
-export GNUPLOT_PROG="@GNUPLOT@"        # gnuplot (data plotting program)
-export HHC_PROG="@HTML_HELP_COMPILER@" # HTML Help Compiler
-export MV_PROG="@MV@"                  # mv (Unix-like 'move/rename files')
-export PERL_PROG="@PERL@"              # Perl
-export RM_PROG="@RM@"                  # rm (Unix-like 'remove files')
-export TAR_PROG="@TAR@"                # tar (Unix-like 'archiver')
-export WGET_PROG="@WGET@"              # wget (remote file retrieval)
-
-# PROJECT_NAME:
-# Documentation/project name. Used in some of the resulting file names and
-# xrefs to uniquify two or more projects linked together through their
-# Doxygen's tag files. Mandatory for each documentation set.
-# Note: might be the same as the doxyfile's PROJECT_NAME
-# Example:
-#   PROJECT_NAME=VTK
-#
-export PROJECT_NAME=CMake
-
-# PATH_TO_VTK_DOX_SCRIPTS:
-# Path to the directory holding the Perl scripts used to produce the VTK doc
-# in Doxygen format. You need the VTK source files or a local copy of
-# these scripts.
-# Example:
-#   PATH_TO_VTK_DOX_SCRIPTS=@VTK_SOURCE_DIR@/Utilities/Doxygen
-#
-export PATH_TO_VTK_DOX_SCRIPTS="@VTK_SOURCE_DIR@/Utilities/Doxygen"
-
-# SOURCE_DIR:
-# Source directory. The top directory of the source files.
-# Example:
-#   SOURCE_DIR=@VTK_SOURCE_DIR@
-#
-export SOURCE_DIR="@CMake_SOURCE_DIR@"
-
-# REL_PATH_TO_TOP:
-# Relative path from the top directory of the source files to the directory
-# (or top directory) holding the files to document. Useful if several parts
-# of the same source directory should be documented separately.
-# Example:
-#   REL_PATH_TO_TOP=.
-#   REL_PATH_TO_TOP=framework/src
-#
-# export REL_PATH_TO_TOP=Source
-export REL_PATH_TO_TOP=.
-
-# INTERMEDIATE_DOX_DIR:
-# Directory where the intermediate Doxygen files should be stored (mainly
-# these headers files converted from the VTK format to the Doxygen format).
-# This directory is erased at the end of this script, unless you comment
-# the corresponding line.
-# DOXTEMP might be used to simplify the syntax.
-# Example:
-#   DOXTEMP=DOXTEMP=@VTK_BINARY_DIR@/Utilities/Doxygen
-#   INTERMEDIATE_DOX_DIR=$DOXTEMP/dox
-#
-export DOXTEMP="@CMake_BINARY_DIR@/Utilities/Doxygen"
-export INTERMEDIATE_DOX_DIR="$DOXTEMP/dox"
-
-# DOXYFILE:
-# Path to the Doxygen configuration file (i.e. doxyfile).
-# Example:
-#   DOXYFILE=$DOXTEMP/doxyfile
-#
-export DOXYFILE="$DOXTEMP/doxyfile"
-
-# OUTPUT_DIRECTORY ALLOW_ERASE_OUTPUT_DIRECTORY:
-# Path to the Doxygen output directory (where the resulting doc is stored).
-# Note: should be the same as your doxyfile's OUTPUT_DIRECTORY
-# If ON, allows the output directory to be erased when some advanced output
-# file have been produced (HTML Help, or TAR archive for example).
-# Example:
-#   OUTPUT_DIRECTORY=$DOXTEMP/doc
-#   ALLOW_ERASE_OUTPUT_DIRECTORY=ON
-#
-export OUTPUT_DIRECTORY="$DOXTEMP/doc"
-export ALLOW_ERASE_OUTPUT_DIRECTORY=ON
-
-# COMPILE_HTML_HELP RESULTING_HTML_HELP_FILE:
-# Compile the CHM (Compressed HTML) HTML Help file, name of the resulting
-# file. If set to ON and name is non-empty these options will actually
-# trigger the HTML-Help compiler to create the CHM. The resulting
-# file (usually index.chm) will be renamed to this name.
-# Note: if ON, the whole $OUTPUT_DIRECTORY will be erased at the end of
-#       this script, since this file is considered to be one of the
-#       advanced final output, unless ALLOW_ERASE_OUTPUT_DIRECTORY is OFF
-# Note: your doxyfile should be configured to enable HTML Help creation
-#       (using GENERATE_HTML = YES, GENERATE_HTMLHELP = YES)
-# Example:
-#   COMPILE_HTML_HELP=ON
-#   COMPILE_HTML_HELP=@DOCUMENTATION_HTML_HELP@
-#   RESULTING_HTML_HELP_FILE=$DOXTEMP/vtk4.chm
-#
-export COMPILE_HTML_HELP=@DOCUMENTATION_HTML_HELP@
-export RESULTING_HTML_HELP_FILE="$DOXTEMP/$PROJECT_NAME.chm"
-
-# CREATE_HTML_TARZ_ARCHIVE RESULTING_HTML_TARZ_ARCHIVE_FILE:
-# Create a compressed (gzip) tar archive of the html directory (located
-# under the OUTPUT_DIRECTORY), and name of the resulting archive file.
-# Note: your doxyfile should be configured to enable HTML creation
-#       (using GENERATE_HTML = YES)
-# Example:
-#   CREATE_HTML_TARZ_ARCHIVE=ON
-#   CREATE_HTML_TARZ_ARCHIVE=@DOCUMENTATION_HTML_TARZ@
-#   RESULTING_HTML_TARZ_ARCHIVE_FILE=$DOXTEMP/vtk4-html.tar.gz
-#   RESULTING_HTML_TARZ_ARCHIVE_FILE=$DOXTEMP/$PROJECT_NAME-html.tar.gz
-#
-export CREATE_HTML_TARZ_ARCHIVE=@DOCUMENTATION_HTML_TARZ@
-export RESULTING_HTML_TARZ_ARCHIVE_FILE="$DOXTEMP/$PROJECT_NAME-html.tar.gz"
-
-# ----------------------------------------------------------------------------
-# Build the contributors list.
-
-if test "x at VTK_SOURCE_DIR@" != "x" ; then
-  if test "x$PERL_PROG" != "xNOTFOUND" ; then
-    "$PERL_PROG" "$PATH_TO_VTK_DOX_SCRIPTS/doc_contributors.pl" \
-        --authors  "$SOURCE_DIR/Utilities/Doxygen/authors.txt" \
-        --cachedir "$DOXTEMP/cache" \
-        --class_group '^(cm[A-Z0-9][A-Za-z0-9]+)\.(?:c|cpp|cxx|h|fl)$' \
-        --files_in '(?:^hints|dummy|README|^Makefile\.borland|\.(?:c|cmake|cpp|cxx|h|html|in|java|fl|pl|py|tcl|txt))$' \
-        --files_out '(?:^ChangeLog\.txt)$' \
-        --gnuplot_file "$DOXTEMP/contrib/history.plt" \
-        --history_img "|lines|$DOXTEMP/contrib/history.png" \
-        --history_img "365|lines|$DOXTEMP/contrib/history2y.png" \
-        --history_img "180|linespoints|$DOXTEMP/contrib/history6m.png" \
-        --history_dir "$DOXTEMP/contrib" \
-        --history_max_nb 10 \
-        --lines_add 1.0 \
-        --lines_rem 0.5 \
-        --massive 50 \
-        --max_class_nb 10 \
-        --max_file_nb 5 \
-        --min_class 0.02 \
-        --min_file 0.01 \
-        --min_contrib 0.05 \
-        --min_gcontrib 0.0001 \
-        --store "doc_""$PROJECT_NAME""_contributors.dox" \
-        --relativeto "$SOURCE_DIR/$REL_PATH_TO_TOP" \
-        --to "$INTERMEDIATE_DOX_DIR" \
-        "$SOURCE_DIR/$REL_PATH_TO_TOP"
-  fi
-
-  if test "x$GNUPLOT_PROG" != "xNOTFOUND" ; then
-    "$GNUPLOT_PROG" "$DOXTEMP/contrib/history.plt"
-  fi
-fi
-
-# ----------------------------------------------------------------------------
-# Create the Doxygen doc.
-
-if test "x$DOXYGEN_PROG" != "xNOTFOUND" ; then
-
-    if test "x$RM_PROG" != "xNOTFOUND" ; then
-        "$RM_PROG" -fr "$OUTPUT_DIRECTORY"
-    fi
-
-    "$DOXYGEN_PROG" "$DOXYFILE"
-
-    # yes, a second time, to get the contrib, I don't know why
-    "$DOXYGEN_PROG" "$DOXYFILE"
-fi
-
-# ----------------------------------------------------------------------------
-# Clean the HTML pages to remove the path to the intermediate Doxygen dir.
-
-if test "x at VTK_SOURCE_DIR@" != "x" ; then
-  if test "x$PERL_PROG" != "xNOTFOUND" ; then
-    "$PERL_PROG" "$PATH_TO_VTK_DOX_SCRIPTS/doc_rmpath.pl" \
-        --verbose \
-        --to "$INTERMEDIATE_DOX_DIR" \
-        --html "$OUTPUT_DIRECTORY/html"
-  fi
-fi
-
-# ----------------------------------------------------------------------------
-# Create the CHM HTML HELP doc.
-
-if test "x$COMPILE_HTML_HELP" == "xON" ; then
-    if test "x$RESULTING_HTML_HELP_FILE" != "x" ; then
-        cd $OUTPUT_DIRECTORY/html
-        if test "x$HHC_PROG" != "xNOTFOUND" ; then
-            "$HHC_PROG" index.hhp
-            if test "x$MV_PROG" != "xNOTFOUND" ; then
-                "$MV_PROG" -f index.chm "$RESULTING_HTML_HELP_FILE"
-            fi
-       fi
-   fi
-fi
-
-# ----------------------------------------------------------------------------
-# Create the compressed tar archive.
-
-if test "x$CREATE_HTML_TARZ_ARCHIVE" == "xON" ; then
-    if test "x$RESULTING_HTML_TARZ_ARCHIVE_FILE" != "x" ; then
-        cd "$OUTPUT_DIRECTORY"
-        if test "x$TAR_PROG" != "xNOTFOUND" ; then
-            if test "x$RM_PROG" != "xNOTFOUND" ; then
-                "$RM_PROG" -f html.tar
-            fi
-            "$TAR_PROG" -cf html.tar html
-            if test "x$GZIP_PROG" != "xNOTFOUND" ; then
-                if test "x$RM_PROG" != "xNOTFOUND" ; then
-                    "$RM_PROG" -f html.tar.gz
-                fi
-                "$GZIP_PROG" html.tar
-                "$MV_PROG" -f html.tar.gz "$RESULTING_HTML_TARZ_ARCHIVE_FILE"
-            fi
-       fi
-   fi
-fi
-
-# ----------------------------------------------------------------------------
-# Clean-up.
-
-if test "x$RM_PROG" != "xNOTFOUND" ; then
-    "$RM_PROG" -fr "$INTERMEDIATE_DOX_DIR"
-
-    if test "x$DOWNLOAD_VTK_TAGFILE" == "xON" ; then
-        if test "x$VTK_TAGFILE" != "x" ; then
-            "$RM_PROG" -f "$VTK_TAGFILE_DEST_DIR/$VTK_TAGFILE"
-        fi
-    fi
-
-    if test "x$COMPILE_HTML_HELP" == "xON" ; then
-        if test "x$RESULTING_HTML_HELP_FILE" != "x" ; then
-            if test "x$ALLOW_ERASE_OUTPUT_DIRECTORY" == "xON" ; then
-                "$RM_PROG" -fr "$OUTPUT_DIRECTORY"
-            fi
-        fi
-    fi
-fi
diff --git a/Utilities/Doxygen/doxyfile.in b/Utilities/Doxygen/doxyfile.in
index 2c131f5..7333340 100644
--- a/Utilities/Doxygen/doxyfile.in
+++ b/Utilities/Doxygen/doxyfile.in
@@ -1,28 +1,30 @@
 # -------------------------------------------------------------------------
-# doxyfile for CMake
-# modified by S. Barre (Time-stamp: <2002-02-13 18:24:35 barre>
+# doxyfile for CMakeReference
 # -------------------------------------------------------------------------
 
 PROJECT_NAME         = CMake
+PROJECT_BRIEF        = "Cross-platform Make"
+PROJECT_NUMBER       = "@CMake_VERSION@"
+PROJECT_LOGO         = "@CMake_SOURCE_DIR@/Source/QtDialog/CMakeSetup64.png"
 
 FULL_PATH_NAMES      = YES
 STRIP_FROM_PATH      = \
- "@CMake_SOURCE_DIR@/Source/" \
- "@CMake_BINARY_DIR@/Source/"
+ "@CMake_SOURCE_DIR@/" \
+ "@CMake_BINARY_DIR@/"
 
 WARN_IF_UNDOCUMENTED = NO
 
 GENERATE_TREEVIEW    = NO
 GENERATE_TODOLIST    = YES
 GENERATE_BUGLIST     = YES
-GENERATE_HTML        = YES
+GENERATE_HTML        = @GENERATE_HTML@
 GENERATE_HTMLHELP    = YES
+GENERATE_QHP         = @GENERATE_QHP@
 GENERATE_LATEX       = NO
 GENERATE_MAN         = NO
 GENERATE_RTF         = NO
 
-HAVE_DOT             = YES
-#HAVE_DOT            = NO
+HAVE_DOT             = @HAVE_DOT@
 DOT_PATH             = "@DOT_PATH@"
 CLASS_GRAPH          = YES
 COLLABORATION_GRAPH  = YES
@@ -37,20 +39,21 @@ REFERENCES_RELATION    = YES
 
 ALLEXTERNALS         = NO
 
-IMAGE_PATH           = "@CMake_BINARY_DIR@/Utilities/Doxygen/contrib"
-
-OUTPUT_DIRECTORY     = "@CMake_BINARY_DIR@/Utilities/Doxygen/doc"
+OUTPUT_DIRECTORY     = "@CMakeDeveloperReference_BINARY_DIR@/developer-reference"
 
 INPUT                = \
+ "@CMake_SOURCE_DIR@/Utilities/Doxygen/DeveloperReference" \
  "@CMake_SOURCE_DIR@/Source" \
  "@CMake_SOURCE_DIR@/Source/CPack" \
  "@CMake_SOURCE_DIR@/Source/CPack/IFW" \
+ "@CMake_SOURCE_DIR@/Source/CPack/WiX" \
  "@CMake_SOURCE_DIR@/Source/CTest" \
  "@CMake_SOURCE_DIR@/Source/CursesDialog" \
- "@CMake_SOURCE_DIR@/Source/MFCDialog" \
+ "@CMake_SOURCE_DIR@/Source/kwsys" \
+ "@CMake_SOURCE_DIR@/Source/QtDialog" \
+ "@CMake_BINARY_DIR@/Source" \
  "@CMake_BINARY_DIR@/Source/kwsys" \
- "@CMake_BINARY_DIR@/Source/cmsys" \
- "@CMake_BINARY_DIR@/Utilities/Doxygen/dox/doc_CMake_contributors.dox" \
+ "@CMake_BINARY_DIR@/Source/cmsys"
 
 EXTRACT_ALL          = YES
 EXTRACT_PRIVATE      = NO
@@ -68,7 +71,7 @@ SORT_MEMBER_DOCS     = NO
 DISTRIBUTE_GROUP_DOC = YES
 TAB_SIZE             = 3
 
-FILE_PATTERNS        = *.h *.hxx *.cxx
+FILE_PATTERNS        = *.h *.hxx *.cxx *.dox
 RECURSIVE            = NO
 EXCLUDE_PATTERNS     =
 
@@ -82,3 +85,7 @@ MACRO_EXPANSION      = YES
 SEARCH_INCLUDES      = YES
 INCLUDE_PATH         =
 EXPAND_ONLY_PREDEF   = YES
+
+QHP_NAMESPACE        = org.cmake.developer-reference. at CMake_VERSION_MAJOR@@CMake_VERSION_MINOR@@CMake_VERSION_PATCH@
+QCH_FILE             = ../CMakeDeveloperReference- at CMake_VERSION_MAJOR@@CMake_VERSION_MINOR@@CMake_VERSION_PATCH at .qch
+QHG_LOCATION         = "@QHELPGENERATOR_EXECUTABLE@"
diff --git a/Utilities/Git/commit-msg b/Utilities/Git/commit-msg
index 9a5d1c1..348c3ea 100755
--- a/Utilities/Git/commit-msg
+++ b/Utilities/Git/commit-msg
@@ -1,15 +1,6 @@
 #!/usr/bin/env bash
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 die() {
   echo 'commit-msg hook failure' 1>&2
diff --git a/Utilities/Git/pre-commit b/Utilities/Git/pre-commit
index a35d111..d3c149c 100755
--- a/Utilities/Git/pre-commit
+++ b/Utilities/Git/pre-commit
@@ -1,15 +1,6 @@
 #!/usr/bin/env bash
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 die() {
   echo 'pre-commit hook failure' 1>&2
diff --git a/Utilities/Git/prepare-commit-msg b/Utilities/Git/prepare-commit-msg
index 1517bb2..511472e 100755
--- a/Utilities/Git/prepare-commit-msg
+++ b/Utilities/Git/prepare-commit-msg
@@ -1,15 +1,6 @@
 #!/usr/bin/env bash
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 # This is a placeholder for future prepare-commit-msg hooks.
 exit 0
diff --git a/Utilities/KWIML/Copyright.txt b/Utilities/KWIML/Copyright.txt
index a6204b0..515c4eb 100644
--- a/Utilities/KWIML/Copyright.txt
+++ b/Utilities/KWIML/Copyright.txt
@@ -1,5 +1,5 @@
 Kitware Information Macro Library
-Copyright 2010-2015 Kitware, Inc.
+Copyright 2010-2016 Kitware, Inc.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
diff --git a/Utilities/KWIML/include/kwiml/abi.h b/Utilities/KWIML/include/kwiml/abi.h
index 3626361..5ffd542 100644
--- a/Utilities/KWIML/include/kwiml/abi.h
+++ b/Utilities/KWIML/include/kwiml/abi.h
@@ -1,6 +1,6 @@
 /*============================================================================
   Kitware Information Macro Library
-  Copyright 2010-2015 Kitware, Inc.
+  Copyright 2010-2016 Kitware, Inc.
   All rights reserved.
 
   Redistribution and use in source and binary forms, with or without
@@ -467,6 +467,10 @@ suppression macro KWIML_ABI_NO_VERIFY was defined.
 #elif defined(__XTENSA_EL__)
 # define KWIML_ABI_ENDIAN_ID KWIML_ABI_ENDIAN_ID_LITTLE
 
+/* RISC-V */
+#elif defined(__riscv__)
+# define KWIML_ABI_ENDIAN_ID KWIML_ABI_ENDIAN_ID_LITTLE
+
 /* Unknown CPU */
 #elif !defined(KWIML_ABI_NO_ERROR_ENDIAN)
 # error "Byte order of target CPU unknown."
diff --git a/Utilities/KWIML/include/kwiml/int.h b/Utilities/KWIML/include/kwiml/int.h
index b297ace..489c603 100644
--- a/Utilities/KWIML/include/kwiml/int.h
+++ b/Utilities/KWIML/include/kwiml/int.h
@@ -1,6 +1,6 @@
 /*============================================================================
   Kitware Information Macro Library
-  Copyright 2010-2015 Kitware, Inc.
+  Copyright 2010-2016 Kitware, Inc.
   All rights reserved.
 
   Redistribution and use in source and binary forms, with or without
diff --git a/Utilities/KWIML/src/version.h.in b/Utilities/KWIML/src/version.h.in
index e58e0dc..0ac8854 100644
--- a/Utilities/KWIML/src/version.h.in
+++ b/Utilities/KWIML/src/version.h.in
@@ -1,6 +1,6 @@
 /*============================================================================
   Kitware Information Macro Library
-  Copyright 2010-2015 Kitware, Inc.
+  Copyright 2010-2016 Kitware, Inc.
   All rights reserved.
 
   Redistribution and use in source and binary forms, with or without
diff --git a/Utilities/KWStyle/CMakeLists.txt b/Utilities/KWStyle/CMakeLists.txt
index b2c798c..3e96c33 100644
--- a/Utilities/KWStyle/CMakeLists.txt
+++ b/Utilities/KWStyle/CMakeLists.txt
@@ -1,14 +1,5 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 #-----------------------------------------------------------------------------
 # CMake uses KWStyle for checking the coding style
diff --git a/Utilities/KWStyle/Headers/CMakeHeader.h b/Utilities/KWStyle/Headers/CMakeHeader.h
deleted file mode 100644
index 3d7702e..0000000
--- a/Utilities/KWStyle/Headers/CMakeHeader.h
+++ /dev/null
@@ -1,11 +0,0 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
diff --git a/Utilities/Release/Cygwin/CMakeLists.txt b/Utilities/Release/Cygwin/CMakeLists.txt
deleted file mode 100644
index 73a8220..0000000
--- a/Utilities/Release/Cygwin/CMakeLists.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-file(GLOB INSTALLED_CURSES /usr/bin/cygncurses-*.dll)
-set(MAX 0)
-foreach(f ${INSTALLED_CURSES})
-  if(NOT "${f}" MATCHES "\\+")
-    string(REGEX REPLACE ".*-([0-9]*).dll" "\\1" NUMBER "${f}")
-    if(NUMBER GREATER MAX)
-      set(MAX ${NUMBER})
-    endif()
-  endif()
-endforeach()
-string(REGEX REPLACE "/usr/bin/" "\\1" NUMBER "${f}")
-set(CMAKE_NCURSES_VERSION "libncurses${MAX}")
-message(STATUS "Using curses version: libncurses${MAX}")
-configure_file("${CMake_SOURCE_DIR}/Utilities/Release/Cygwin/cygwin-setup.hint.in"
-  "${CMake_BINARY_DIR}/setup.hint")
-configure_file("${CMake_SOURCE_DIR}/Utilities/Release/Cygwin/README.cygwin.in"
-  "${CMake_BINARY_DIR}/Docs/${CPACK_PACKAGE_FILE_NAME}-${CPACK_CYGWIN_PATCH_NUMBER}.README")
-install_files(/share/doc/Cygwin FILES
-  ${CMake_BINARY_DIR}/Docs/${CPACK_PACKAGE_FILE_NAME}-${CPACK_CYGWIN_PATCH_NUMBER}.README
-  )
-configure_file("${CMake_SOURCE_DIR}/Utilities/Release/Cygwin/cygwin-package.sh.in"
-  ${CPACK_CYGWIN_BUILD_SCRIPT})
-configure_file("${CMake_SOURCE_DIR}/Utilities/Release/Cygwin/cygwin-patch.diff.in"
-  ${CPACK_CYGWIN_PATCH_FILE})
-
diff --git a/Utilities/Release/Cygwin/README.cygwin.in b/Utilities/Release/Cygwin/README.cygwin.in
deleted file mode 100644
index 17cf2a1..0000000
--- a/Utilities/Release/Cygwin/README.cygwin.in
+++ /dev/null
@@ -1,42 +0,0 @@
-cmake
---------------------------------------
-Runtime requirements:
-  cygwin-1.5.21(0.156/4/2) or newer
-
-Build requirements
-  cygwin-1.5.21(0.156/4/2) or newer
-  make
-
-Canonical homepage:
-  https://cmake.org
-
-Canonical download:
-  ftp://www.cmake.org/pub/cmake/
-
-------------------------------------
-
-Build instructions:
-  unpack @CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at -src.tar.bz2
-    if you use setup to install this src package, it will be
-         unpacked under /usr/src automatically
-  cd /usr/src
-  ./@CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at .sh all
-
-This will create:
-  /usr/src/@CPACK_PACKAGE_FILE_NAME at .tar.bz2
-  /usr/src/@CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at -src.tar.bz2
-
--------------------------------------------
-
-Port Notes:
-
-The directory /usr/share/@CPACK_PACKAGE_FILE_NAME@/include is purposely not
-located at /usr/include/@CPACK_PACKAGE_FILE_NAME@ or /usr/include/cmake.  The
-files it contains are not meant for inclusion in any C or C++ program.
-They are used for compiling dynamically loadable CMake commands inside
-projects that provide them.  CMake will automatically provide the
-proper include path when the files are needed.
-
-------------------
-
-Cygwin port maintained by: CMake Developers <cmake at www.cmake.org>
diff --git a/Utilities/Release/Cygwin/cygwin-package.sh.in b/Utilities/Release/Cygwin/cygwin-package.sh.in
deleted file mode 100755
index dff27f1..0000000
--- a/Utilities/Release/Cygwin/cygwin-package.sh.in
+++ /dev/null
@@ -1,90 +0,0 @@
-TOP_DIR=`cd \`echo "$0" | sed -n '/\//{s/\/[^\/]*$//;p;}'\`;pwd`
-
-# create build directory
-mkdirs()
-{
-  (
-  mkdir -p "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build"
-  )
-}
-
-# cd into
-# untar source tree and apply patch
-prep()
-{
-  (
-  cd "$TOP_DIR" &&
-  tar xvfj @CPACK_PACKAGE_FILE_NAME at .tar.bz2
-  patch -p0 < "@CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at .patch" &&
-  mkdirs
-  )
-}
-
-conf()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  ../bootstrap --parallel=2
-  )
-}
-
-build()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  make -j2 &&
-  make test
-  )
-}
-
-clean()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  make clean
-  )
-}
-
-pkg()
-{
-  (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  ./bin/cpack &&
-  mv @CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at .tar.bz2 "$TOP_DIR"
-  )
-}
-
-spkg()
-{
- (
-  cd "$TOP_DIR/@CPACK_PACKAGE_FILE_NAME@/.build" &&
-  ./bin/cpack --config  CPackSourceConfig.cmake &&
-  mv @CPACK_PACKAGE_FILE_NAME at -@CPACK_CYGWIN_PATCH_NUMBER at -src.tar.bz2 "$TOP_DIR"
-  )
-}
-
-finish()
-{
-  (
-  rm -rf "@CPACK_PACKAGE_FILE_NAME@"
-  )
-}
-
-case $1 in
-  prep)         prep    ; STATUS=$? ;;
-  mkdirs)       mkdirs  ; STATUS=$? ;;
-  conf)         conf    ; STATUS=$? ;;
-  build)        build   ; STATUS=$? ;;
-  clean)        clean   ; STATUS=$? ;;
-  package)      pkg     ; STATUS=$? ;;
-  pkg)          pkg     ; STATUS=$? ;;
-  src-package)  spkg    ; STATUS=$? ;;
-  spkg)         spkg    ; STATUS=$? ;;
-  finish)       finish  ; STATUS=$? ;;
-  all) (
-       prep && conf && build && pkg && spkg && finish ;
-       STATUS=$?
-       ) ;;
-  *) echo "Error: bad argument (all or one of these: prep mkdirs conf build clean package pkg src-package spkg finish)" ; exit 1 ;;
-esac
-exit ${STATUS}
diff --git a/Utilities/Release/Cygwin/cygwin-setup.hint.in b/Utilities/Release/Cygwin/cygwin-setup.hint.in
deleted file mode 100644
index a2532fc..0000000
--- a/Utilities/Release/Cygwin/cygwin-setup.hint.in
+++ /dev/null
@@ -1,5 +0,0 @@
-# CMake setup.hint file for cygwin setup.exe program
-category: Devel
-requires: libgcc1 libidn11 @CMAKE_NCURSES_VERSION@ libstdc++6
-sdesc: "A cross platform build manager"
-ldesc: "CMake is a cross platform build manager. It allows you to specify build parameters for C and C++ programs in a cross platform manner. For cygwin Makefiles will be generated. CMake is also capable of generating microsoft project files, nmake, and borland makefiles. CMake can also perform system inspection operations like finding installed libraries and header files."
diff --git a/Utilities/Release/README b/Utilities/Release/README
index 12eafe1..ed1d52e 100644
--- a/Utilities/Release/README
+++ b/Utilities/Release/README
@@ -15,7 +15,4 @@ Then as kitware at hythloth, using an up-to-date CMake:
 create-cmake-release.cmake:  script to run to create release sh scripts
 Add or remove machines in create-cmake-release.cmake.
 
-Cygwin -> directory that contains cpack cygwin package files used in
- CMakeCPack.cmake
-
 machine_release.cmake : config files for each machine
diff --git a/Utilities/Release/create-cmake-release.cmake b/Utilities/Release/create-cmake-release.cmake
index f8844e9..3af1b03 100644
--- a/Utilities/Release/create-cmake-release.cmake
+++ b/Utilities/Release/create-cmake-release.cmake
@@ -8,12 +8,10 @@ file(MAKE_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/logs)
 set(RELEASE_SCRIPTS_BATCH_1
   win32_release.cmake         # Windows x86
   osx_release.cmake           # OS X x86_64
-  linux32_release.cmake       # Linux x86
   linux64_release.cmake       # Linux x86_64
 )
 
 set(RELEASE_SCRIPTS_BATCH_2
-  cygwin_release.cmake        # Cygwin x86
   win64_release.cmake         # Windows x64
 )
 
@@ -68,7 +66,6 @@ endfunction()
 
 write_docs_shell_script("create-${CMAKE_CREATE_VERSION}-docs.sh")
 write_batch_shell_script("create-${CMAKE_CREATE_VERSION}-batch1.sh" ${RELEASE_SCRIPTS_BATCH_1})
-unset(CMAKE_DOC_TARBALL) # No pre-built docs in second batch.
 write_batch_shell_script("create-${CMAKE_CREATE_VERSION}-batch2.sh" ${RELEASE_SCRIPTS_BATCH_2})
 
 message("Run one at a time:
diff --git a/Utilities/Release/cygwin_release.cmake b/Utilities/Release/cygwin_release.cmake
deleted file mode 100644
index ca3e794..0000000
--- a/Utilities/Release/cygwin_release.cmake
+++ /dev/null
@@ -1,32 +0,0 @@
-set(CMAKE_RELEASE_DIRECTORY "c:/cygwin/home/dashboard/CMakeReleaseCygwin")
-set(PROCESSORS 9)
-set(BOOTSTRAP_ARGS "")
-set(MAKE_PROGRAM "make")
-set(MAKE "${MAKE_PROGRAM} -j8")
-set(HOST dash2win64)
-set(CPACK_BINARY_GENERATORS "CygwinBinary")
-set(CPACK_SOURCE_GENERATORS "CygwinSource")
-set(MAKE_PROGRAM "make")
-set(INITIAL_CACHE "CMAKE_BUILD_TYPE:STRING=Release
-CMAKE_Fortran_COMPILER_FULLPATH:FILEPATH=FALSE
-CTEST_TEST_TIMEOUT:STRING=7200
-DART_TESTING_TIMEOUT:STRING=7200
-SPHINX_HTML:BOOL=ON
-SPHINX_MAN:BOOL=ON
-CMake_INSTALL_DEPENDENCIES:BOOL=ON
-")
-set(CXX g++)
-set(CC  gcc)
-set(GIT_EXTRA "git config core.autocrlf false")
-get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH)
-
-# WARNING: Temporary fix!! This exclusion of the ExternalProject test
-# is temporary until we can set up a new cygwin build machine.
-# It only fails because of cygwin/non-cygwin "svn" mismatches in this
-# particular environment. This is less than ideal, but at least it
-# allows us to produce cygwin builds in the short term.
-set(EXTRA_CTEST_ARGS "-E ExternalProject")
-
-set(LOCAL_DIR cygwin)
-
-include(${path}/release_cmake.cmake)
diff --git a/Utilities/Release/linux32_release.cmake b/Utilities/Release/linux32_release.cmake
deleted file mode 100644
index 6d096d1..0000000
--- a/Utilities/Release/linux32_release.cmake
+++ /dev/null
@@ -1,25 +0,0 @@
-set(PROCESSORS 1)
-set(BOOTSTRAP_ARGS "--docdir=doc/cmake")
-set(HOST magrathea)
-set(MAKE_PROGRAM "make")
-set(CC gcc332s)
-set(CXX c++332s)
-set(CFLAGS   -DDT_RUNPATH=29)
-set(CXXFLAGS -DDT_RUNPATH=29)
-set(INITIAL_CACHE "
-CMAKE_BUILD_TYPE:STRING=Release
-CURSES_LIBRARY:FILEPATH=/usr/i686-gcc-332s/lib/libncurses.a
-CURSES_INCLUDE_PATH:PATH=/usr/i686-gcc-332s/include/ncurses
-FORM_LIBRARY:FILEPATH=/usr/i686-gcc-332s/lib/libform.a
-CMAKE_USE_OPENSSL:BOOL=ON
-OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libcrypto.a
-OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2h/include
-OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libssl.a
-CPACK_SYSTEM_NAME:STRING=Linux-i386
-BUILD_QtDialog:BOOL:=TRUE
-CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:BOOL=TRUE
-CMake_INSTALL_DEPENDENCIES:BOOL=ON
-QT_QMAKE_EXECUTABLE:FILEPATH=/home/kitware/qt-4.43-install/bin/qmake
-")
-get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH)
-include(${path}/release_cmake.cmake)
diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake
index cfe370b..b72fc12 100644
--- a/Utilities/Release/linux64_release.cmake
+++ b/Utilities/Release/linux64_release.cmake
@@ -2,12 +2,28 @@ set(PROCESSORS 4)
 set(BOOTSTRAP_ARGS "--docdir=doc/cmake")
 set(HOST linux64)
 set(MAKE_PROGRAM "make")
-set(CC /opt/gcc-4.9.2/bin/gcc)
-set(CXX /opt/gcc-4.9.2/bin/g++)
+set(CC /opt/gcc-6.1.0/bin/gcc)
+set(CXX /opt/gcc-6.1.0/bin/g++)
 set(CFLAGS   "")
 set(CXXFLAGS "")
+set(qt_prefix "/home/kitware/qt-5.7.0")
+set(qt_xcb_libs
+  ${qt_prefix}/plugins/platforms/libqxcb.a
+  ${qt_prefix}/lib/libQt5XcbQpa.a
+  ${qt_prefix}/lib/libQt5PlatformSupport.a
+  ${qt_prefix}/lib/libxcb-static.a
+  -lX11-xcb
+  -lX11
+  -lxcb
+  -lfontconfig
+  -lfreetype
+  )
 set(INITIAL_CACHE "
 CMAKE_BUILD_TYPE:STRING=Release
+CMAKE_C_STANDARD:STRING=11
+CMAKE_CXX_STANDARD:STRING=14
+CMAKE_C_FLAGS:STRING=-D_POSIX_C_SOURCE=199506L -D_POSIX_SOURCE=1 -D_SVID_SOURCE=1 -D_BSD_SOURCE=1
+CMAKE_EXE_LINKER_FLAGS:STRING=-static-libstdc++ -static-libgcc
 CURSES_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libncurses.a
 CURSES_INCLUDE_PATH:PATH=/home/kitware/ncurses-5.9/include
 FORM_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libform.a
@@ -15,11 +31,18 @@ CMAKE_USE_OPENSSL:BOOL=ON
 OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libcrypto.a
 OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2h/include
 OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libssl.a
+PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3
 CPACK_SYSTEM_NAME:STRING=Linux-x86_64
 BUILD_QtDialog:BOOL:=TRUE
-CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:BOOL=TRUE
+CMake_ENABLE_SERVER_MODE:BOOL=TRUE
+CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
 CMake_INSTALL_DEPENDENCIES:BOOL=ON
-QT_QMAKE_EXECUTABLE:FILEPATH=/home/kitware/qt-4.8.6/bin/qmake
+CMAKE_PREFIX_PATH:STRING=${qt_prefix}
+CMake_QT_STATIC_QXcbIntegrationPlugin_LIBRARIES:STRING=${qt_xcb_libs}
 ")
+
+# Exclude Qt5 tests because our Qt5 is static.
+set(EXTRA_CTEST_ARGS "-E Qt5")
+
 get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH)
 include(${path}/release_cmake.cmake)
diff --git a/Utilities/Release/osx_release.cmake b/Utilities/Release/osx_release.cmake
index 17f7df6..27c820f 100644
--- a/Utilities/Release/osx_release.cmake
+++ b/Utilities/Release/osx_release.cmake
@@ -13,16 +13,17 @@ set(CFLAGS   "")
 set(CXXFLAGS "-stdlib=libc++")
 set(INITIAL_CACHE "
 CMAKE_BUILD_TYPE:STRING=Release
+CMAKE_C_STANDARD:STRING=11
+CMAKE_CXX_STANDARD:STRING=14
 CMAKE_OSX_ARCHITECTURES:STRING=x86_64
 CMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.7
 CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
 CPACK_SYSTEM_NAME:STRING=Darwin-x86_64
 BUILD_QtDialog:BOOL=TRUE
-CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:BOOL=TRUE
+CMake_ENABLE_SERVER_MODE:BOOL=TRUE
+CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
 CMake_INSTALL_DEPENDENCIES:BOOL=ON
 CMAKE_SKIP_RPATH:BOOL=TRUE
-CMake_NO_C_STANDARD:BOOL=TRUE
-CMake_NO_CXX_STANDARD:BOOL=TRUE
 CMake_TEST_NO_FindPackageModeMakefileTest:BOOL=TRUE
 ")
 set(ENV [[
diff --git a/Utilities/Release/release_cmake.cmake b/Utilities/Release/release_cmake.cmake
index 0d9c784..0db89b5 100644
--- a/Utilities/Release/release_cmake.cmake
+++ b/Utilities/Release/release_cmake.cmake
@@ -108,10 +108,6 @@ foreach(gen ${generators})
   if("${gen}" STREQUAL "TBZ2")
     set(SUFFIXES ${SUFFIXES} "*.tar.bz2")
   endif()
-  if("${gen}" MATCHES "Cygwin")
-    set(SUFFIXES ${SUFFIXES} "*.tar.bz2")
-    set(extra_files setup.hint)
-  endif()
   if("${gen}" STREQUAL "TZ")
     set(SUFFIXES ${SUFFIXES} "*.tar.Z")
   endif()
diff --git a/Utilities/Release/upload_release.cmake b/Utilities/Release/upload_release.cmake
index 04a0cac..1485d9c 100644
--- a/Utilities/Release/upload_release.cmake
+++ b/Utilities/Release/upload_release.cmake
@@ -1,6 +1,6 @@
 set(CTEST_RUN_CURRENT_SCRIPT 0)
 if(NOT VERSION)
- set(VERSION 3.6)
+ set(VERSION 3.7)
 endif()
 if(NOT DEFINED PROJECT_PREFIX)
   set(PROJECT_PREFIX cmake-${VERSION})
diff --git a/Utilities/Release/win32_release.cmake b/Utilities/Release/win32_release.cmake
index ba83b26..df9fe27 100644
--- a/Utilities/Release/win32_release.cmake
+++ b/Utilities/Release/win32_release.cmake
@@ -1,6 +1,6 @@
 set(CMAKE_RELEASE_DIRECTORY "c:/msys64/home/dashboard/CMakeReleaseDirectory")
 set(CONFIGURE_WITH_CMAKE TRUE)
-set(CMAKE_CONFIGURE_PATH "c:/Program\\ Files\\ \\(x86\\)/CMake/bin/cmake.exe")
+set(CMAKE_CONFIGURE_PATH "c:/Program\\ Files/CMake/bin/cmake.exe")
 set(PROCESSORS 8)
 set(HOST dash3win7)
 set(RUN_LAUNCHER ~/rel/run)
@@ -15,7 +15,8 @@ CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
 CMAKE_Fortran_COMPILER:FILEPATH=FALSE
 CMAKE_GENERATOR:INTERNAL=Ninja
 BUILD_QtDialog:BOOL:=TRUE
-CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:BOOL=TRUE
+CMake_ENABLE_SERVER_MODE:BOOL=TRUE
+CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
 CMake_INSTALL_DEPENDENCIES:BOOL=ON
 CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x86 -subsystem:console,5.01
 ")
@@ -27,6 +28,6 @@ get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH)
 set(GIT_EXTRA "git config core.autocrlf true")
 if(CMAKE_CREATE_VERSION STREQUAL "nightly")
   # Some tests fail spuriously too often.
-  set(EXTRA_CTEST_ARGS "-E Qt5Autogen")
+  set(EXTRA_CTEST_ARGS "-E 'Qt5Autogen|ConsoleBuf'")
 endif()
 include(${path}/release_cmake.cmake)
diff --git a/Utilities/Release/win64_release.cmake b/Utilities/Release/win64_release.cmake
index 8e207b5..ab52d79 100644
--- a/Utilities/Release/win64_release.cmake
+++ b/Utilities/Release/win64_release.cmake
@@ -1,6 +1,6 @@
 set(CMAKE_RELEASE_DIRECTORY "c:/msys64/home/dashboard/CMakeReleaseDirectory64")
 set(CONFIGURE_WITH_CMAKE TRUE)
-set(CMAKE_CONFIGURE_PATH "c:/Program\\ Files\\ \\(x86\\)/CMake/bin/cmake.exe")
+set(CMAKE_CONFIGURE_PATH "c:/Program\\ Files/CMake/bin/cmake.exe")
 set(PROCESSORS 8)
 set(HOST dash3win7)
 set(SCRIPT_NAME dash3win7x64)
@@ -16,7 +16,8 @@ CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
 CMAKE_Fortran_COMPILER:FILEPATH=FALSE
 CMAKE_GENERATOR:INTERNAL=Ninja
 BUILD_QtDialog:BOOL:=TRUE
-CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:BOOL=TRUE
+CMake_ENABLE_SERVER_MODE:BOOL=TRUE
+CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
 CMake_INSTALL_DEPENDENCIES:BOOL=ON
 CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x64 -subsystem:console,5.02
 ")
@@ -28,6 +29,6 @@ get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH)
 set(GIT_EXTRA "git config core.autocrlf true")
 if(CMAKE_CREATE_VERSION STREQUAL "nightly")
   # Some tests fail spuriously too often.
-  set(EXTRA_CTEST_ARGS "-E Qt5Autogen")
+  set(EXTRA_CTEST_ARGS "-E 'Qt5Autogen|ConsoleBuf'")
 endif()
 include(${path}/release_cmake.cmake)
diff --git a/Utilities/Scripts/BoostScanDeps.cmake b/Utilities/Scripts/BoostScanDeps.cmake
index 1fbea4b..2fd8f86 100644
--- a/Utilities/Scripts/BoostScanDeps.cmake
+++ b/Utilities/Scripts/BoostScanDeps.cmake
@@ -1,3 +1,6 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 # Scan the Boost headers and determine the library dependencies.  Note
 # that this script only scans one Boost version at once; invoke once
 # for each Boost release.  Note that this does require the headers for
@@ -21,19 +24,6 @@
 
 # Written by Roger Leigh <rleigh at codelibre.net>
 
-#=============================================================================
-# Copyright 2014-2015 University of Dundee
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
 # Determine header dependencies on libraries using the embedded dependency information.
 #
 # component - the component to check (uses all headers from boost/${component})
diff --git a/Utilities/Scripts/clang-format.bash b/Utilities/Scripts/clang-format.bash
index a9ef62b..a7080fc 100755
--- a/Utilities/Scripts/clang-format.bash
+++ b/Utilities/Scripts/clang-format.bash
@@ -126,7 +126,7 @@ $git_ls -z -- '*.c' '*.cc' '*.cpp' '*.cxx' '*.h' '*.hh' '*.hpp' '*.hxx' |
   egrep -z -v '^Utilities/(KW|cm).*/' |
 
   # Exclude reference content.
-  egrep -z -v '^Tests/Module/GenerateExportHeader/reference/' |
+  egrep -z -v '^Tests/RunCMake/GenerateExportHeader/reference/' |
 
   # Exclude manually-formatted sources (e.g. with long lines).
   egrep -z -v '^Tests/PositionIndependentTargets/pic_test.h' |
diff --git a/Utilities/Scripts/update-curl.bash b/Utilities/Scripts/update-curl.bash
index 0e466cf..590bd44 100755
--- a/Utilities/Scripts/update-curl.bash
+++ b/Utilities/Scripts/update-curl.bash
@@ -7,7 +7,7 @@ shopt -s dotglob
 readonly name="curl"
 readonly ownership="Curl Upstream <curl-library at cool.haxx.se>"
 readonly subtree="Utilities/cmcurl"
-readonly repo="https://github.com/bagder/curl.git"
+readonly repo="https://github.com/curl/curl.git"
 readonly tag="curl-7_50_1"
 readonly shortlog=false
 readonly paths="
diff --git a/Utilities/Scripts/update-kwiml.bash b/Utilities/Scripts/update-kwiml.bash
index 5c0d192..4497c92 100755
--- a/Utilities/Scripts/update-kwiml.bash
+++ b/Utilities/Scripts/update-kwiml.bash
@@ -7,7 +7,7 @@ shopt -s dotglob
 readonly name="KWIML"
 readonly ownership="KWIML Upstream <kwrobot at kitware.com>"
 readonly subtree="Utilities/KWIML"
-readonly repo="https://github.com/Kitware/KWIML.git"
+readonly repo="https://gitlab.kitware.com/utils/kwiml.git"
 readonly tag="master"
 readonly shortlog=true
 readonly paths="
diff --git a/Utilities/Scripts/update-liblzma.bash b/Utilities/Scripts/update-liblzma.bash
new file mode 100755
index 0000000..088eb91
--- /dev/null
+++ b/Utilities/Scripts/update-liblzma.bash
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="liblzma"
+readonly ownership="liblzma upstream <xz-devel at tukaani.org>"
+readonly subtree="Utilities/cmliblzma"
+readonly repo="http://git.tukaani.org/xz.git"
+readonly tag="v5.0.8"
+readonly shortlog=false
+readonly paths="
+  COPYING
+  src/common/common_w32res.rc
+  src/common/sysdefs.h
+  src/common/tuklib_integer.h
+  src/liblzma/
+"
+
+extract_source () {
+    git_archive
+    pushd "${extractdir}/${name}-reduced"
+    mv src/common .
+    mv src/liblzma .
+    rmdir src
+    popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Scripts/update-libuv.bash b/Utilities/Scripts/update-libuv.bash
new file mode 100755
index 0000000..d7a7d1f
--- /dev/null
+++ b/Utilities/Scripts/update-libuv.bash
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="libuv"
+readonly ownership="libuv upstream <libuv at googlegroups.com>"
+readonly subtree="Utilities/cmlibuv"
+readonly repo="https://github.com/libuv/libuv.git"
+readonly tag="v1.x"
+readonly shortlog=false
+readonly paths="
+  LICENSE
+  include
+  src
+"
+
+extract_source () {
+    git_archive
+    pushd "${extractdir}/${name}-reduced"
+    echo "* -whitespace" > .gitattributes
+    popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Scripts/update-third-party.bash b/Utilities/Scripts/update-third-party.bash
index 6aeeccd..3b8358e 100644
--- a/Utilities/Scripts/update-third-party.bash
+++ b/Utilities/Scripts/update-third-party.bash
@@ -155,8 +155,14 @@ popd
 if [ -n "$basehash" ]; then
     git merge --log -s recursive "-Xsubtree=$subtree/" --no-commit "upstream-$name"
 else
+    unrelated_histories_flag=""
+    if git merge --help | grep -q -e allow-unrelated-histories; then
+        unrelated_histories_flag="--allow-unrelated-histories "
+    fi
+    readonly unrelated_histories_flag
+
     git fetch "$extractdir" "upstream-$name:upstream-$name"
-    git merge --log -s ours --no-commit "upstream-$name"
+    git merge --log -s ours --no-commit $unrelated_histories_flag "upstream-$name"
     git read-tree -u --prefix="$subtree/" "upstream-$name"
 fi
 git commit --no-edit
diff --git a/Utilities/Scripts/update-vim-syntax.bash b/Utilities/Scripts/update-vim-syntax.bash
new file mode 100755
index 0000000..bb14683
--- /dev/null
+++ b/Utilities/Scripts/update-vim-syntax.bash
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="vim-cmake-syntax"
+readonly ownership="vim-cmake-syntax upstream <kwrobot at kitware.com>"
+readonly subtree="Auxiliary/vim"
+readonly repo="https://github.com/pboettch/vim-cmake-syntax.git"
+readonly tag="master"
+readonly shortlog=true
+readonly paths="
+  indent
+  syntax
+  cmake.vim.in
+  extract-upper-case.pl
+"
+
+extract_source () {
+    git_archive
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Sphinx/CMakeLists.txt b/Utilities/Sphinx/CMakeLists.txt
index 257ba62..edb9469 100644
--- a/Utilities/Sphinx/CMakeLists.txt
+++ b/Utilities/Sphinx/CMakeLists.txt
@@ -1,17 +1,9 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 if(NOT CMake_SOURCE_DIR)
   set(CMakeHelp_STANDALONE 1)
-  cmake_minimum_required(VERSION 2.8.4 FATAL_ERROR)
+  cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
   get_filename_component(tmp "${CMAKE_CURRENT_SOURCE_DIR}" PATH)
   get_filename_component(CMake_SOURCE_DIR "${tmp}" PATH)
   include(${CMake_SOURCE_DIR}/Modules/CTestUseLaunchers.cmake)
@@ -156,18 +148,21 @@ if(SPHINX_MAN)
     if("x${m}" MATCHES "^x(.+)\\.([1-9])\\.rst$")
       set(name "${CMAKE_MATCH_1}")
       set(sec "${CMAKE_MATCH_2}")
+      set(skip FALSE)
       if(NOT CMakeHelp_STANDALONE)
         if(name STREQUAL "ccmake" AND NOT BUILD_CursesDialog)
-          continue()
-        endif()
-        if(name STREQUAL "cmake-gui" AND NOT BUILD_QtDialog)
-          continue()
+          set(skip TRUE)
+        elseif(name STREQUAL "cmake-gui" AND NOT BUILD_QtDialog)
+          set(skip TRUE)
         endif()
       endif()
-      CMake_OPTIONAL_COMPONENT(sphinx-man)
-      install(FILES ${CMAKE_CURRENT_BINARY_DIR}/man/${name}.${sec}
-              DESTINATION ${CMAKE_MAN_DIR}/man${sec}
-              ${COMPONENT})
+      if(NOT skip)
+        CMake_OPTIONAL_COMPONENT(sphinx-man)
+        install(FILES ${CMAKE_CURRENT_BINARY_DIR}/man/${name}.${sec}
+                DESTINATION ${CMAKE_MAN_DIR}/man${sec}
+                ${COMPONENT})
+      endif()
+      unset(skip)
     endif()
   endforeach()
 endif()
diff --git a/Utilities/Sphinx/cmake.py b/Utilities/Sphinx/cmake.py
index 5c0406d..edc7667 100644
--- a/Utilities/Sphinx/cmake.py
+++ b/Utilities/Sphinx/cmake.py
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 import os
 import re
 
diff --git a/Utilities/Sphinx/conf.py.in b/Utilities/Sphinx/conf.py.in
index eb24a6e..9581458 100644
--- a/Utilities/Sphinx/conf.py.in
+++ b/Utilities/Sphinx/conf.py.in
@@ -1,14 +1,6 @@
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
 import sys
 import os
 import re
diff --git a/Utilities/cmThirdParty.h.in b/Utilities/cmThirdParty.h.in
index 4c1177c..210e727 100644
--- a/Utilities/cmThirdParty.h.in
+++ b/Utilities/cmThirdParty.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmThirdParty_h
 #define cmThirdParty_h
 
@@ -22,6 +13,7 @@
 #cmakedefine CMAKE_USE_SYSTEM_LIBLZMA
 #cmakedefine CMAKE_USE_SYSTEM_FORM
 #cmakedefine CMAKE_USE_SYSTEM_JSONCPP
+#cmakedefine CMAKE_USE_SYSTEM_LIBUV
 #cmakedefine CTEST_USE_XMLRPC
 
 #endif
diff --git a/Utilities/cm_bzlib.h b/Utilities/cm_bzlib.h
index 0eb7bd8..e7f6d89 100644
--- a/Utilities/cm_bzlib.h
+++ b/Utilities/cm_bzlib.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_bzlib_h
 #define cm_bzlib_h
 
diff --git a/Utilities/cm_curl.h b/Utilities/cm_curl.h
index bf4c63c..fc2b8ab 100644
--- a/Utilities/cm_curl.h
+++ b/Utilities/cm_curl.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_curl_h
 #define cm_curl_h
 
diff --git a/Utilities/cm_expat.h b/Utilities/cm_expat.h
index c6c6683..d879337 100644
--- a/Utilities/cm_expat.h
+++ b/Utilities/cm_expat.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_expat_h
 #define cm_expat_h
 
diff --git a/Utilities/cm_jsoncpp_reader.h b/Utilities/cm_jsoncpp_reader.h
index 019044e..e78ec1e 100644
--- a/Utilities/cm_jsoncpp_reader.h
+++ b/Utilities/cm_jsoncpp_reader.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_jsoncpp_reader_h
 #define cm_jsoncpp_reader_h
 
diff --git a/Utilities/cm_jsoncpp_value.h b/Utilities/cm_jsoncpp_value.h
index 81c9ae0..cf37758 100644
--- a/Utilities/cm_jsoncpp_value.h
+++ b/Utilities/cm_jsoncpp_value.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_jsoncpp_value_h
 #define cm_jsoncpp_value_h
 
diff --git a/Utilities/cm_jsoncpp_writer.h b/Utilities/cm_jsoncpp_writer.h
index 597539d..33b2468 100644
--- a/Utilities/cm_jsoncpp_writer.h
+++ b/Utilities/cm_jsoncpp_writer.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_jsoncpp_writer_h
 #define cm_jsoncpp_writer_h
 
diff --git a/Utilities/cm_kwiml.h b/Utilities/cm_kwiml.h
index fce8881..65cb35f 100644
--- a/Utilities/cm_kwiml.h
+++ b/Utilities/cm_kwiml.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2015 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_kwiml_h
 #define cm_kwiml_h
 
diff --git a/Utilities/cm_libarchive.h b/Utilities/cm_libarchive.h
index c6a8a82..2269526 100644
--- a/Utilities/cm_libarchive.h
+++ b/Utilities/cm_libarchive.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2010 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_libarchive_h
 #define cm_libarchive_h
 
diff --git a/Utilities/cm_lzma.h b/Utilities/cm_lzma.h
index 20cf1d7..013c724 100644
--- a/Utilities/cm_lzma.h
+++ b/Utilities/cm_lzma.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2014 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_lzma_h
 #define cm_lzma_h
 
diff --git a/Utilities/cm_uv.h b/Utilities/cm_uv.h
new file mode 100644
index 0000000..6d4813d
--- /dev/null
+++ b/Utilities/cm_uv.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_uv_h
+#define cm_uv_h
+
+/* Use the libuv library configured for CMake.  */
+#include "cmThirdParty.h"
+#ifdef CMAKE_USE_SYSTEM_LIBUV
+#include <uv.h>
+#else
+#include <cmlibuv/include/uv.h>
+#endif
+
+#endif
diff --git a/Utilities/cm_xmlrpc.h b/Utilities/cm_xmlrpc.h
index 0bc93f4..08db89f 100644
--- a/Utilities/cm_xmlrpc.h
+++ b/Utilities/cm_xmlrpc.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_xmlrpc_h
 #define cm_xmlrpc_h
 
diff --git a/Utilities/cm_zlib.h b/Utilities/cm_zlib.h
index 6ff8e6c..2aee9f1 100644
--- a/Utilities/cm_zlib.h
+++ b/Utilities/cm_zlib.h
@@ -1,14 +1,5 @@
-/*============================================================================
-  CMake - Cross Platform Makefile Generator
-  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
-  Distributed under the OSI-approved BSD License (the "License");
-  see accompanying file Copyright.txt for details.
-
-  This software is distributed WITHOUT ANY WARRANTY; without even the
-  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-  See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cm_zlib_h
 #define cm_zlib_h
 
diff --git a/Utilities/cmlibarchive/libarchive/xxhash.c b/Utilities/cmlibarchive/libarchive/xxhash.c
index d7f8e96..262fecb 100644
--- a/Utilities/cmlibarchive/libarchive/xxhash.c
+++ b/Utilities/cmlibarchive/libarchive/xxhash.c
@@ -29,12 +29,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 You can contact the author at :
 - xxHash source repository : http://code.google.com/p/xxhash/
 */
-#include <stdlib.h>
-#include <string.h>
 
 #include "archive_platform.h"
 #include "archive_xxhash.h"
 
+#include <stdlib.h>
+#include <string.h>
+
 #ifdef HAVE_LIBLZ4
 
 /***************************************
diff --git a/Utilities/cmliblzma/CMakeLists.txt b/Utilities/cmliblzma/CMakeLists.txt
index 8920536..e806680 100644
--- a/Utilities/cmliblzma/CMakeLists.txt
+++ b/Utilities/cmliblzma/CMakeLists.txt
@@ -182,10 +182,6 @@ SET(LZMA_SRCS
   liblzma/simple/x86.c
   )
 
-IF(WIN32 AND BUILD_SHARED_LIBS)
-  SET(LZMA_SRCS ${LZMA_SRCS} liblzma/liblzma_w32res.rc)
-ENDIF()
-
 CONFIGURE_FILE(config.h.in config.h @ONLY)
 
 INCLUDE_DIRECTORIES(
@@ -209,7 +205,7 @@ ELSEIF(CMAKE_C_COMPILER_ID STREQUAL "PathScale")
   SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
 ENDIF()
 
-ADD_LIBRARY(cmliblzma ${LZMA_SRCS})
+ADD_LIBRARY(cmliblzma STATIC ${LZMA_SRCS})
 
 IF(CMAKE_C_COMPILER_ID STREQUAL "XL")
   # Disable the XL compiler optimizer because it causes crashes
diff --git a/Utilities/cmliblzma/README-CMake.txt b/Utilities/cmliblzma/README-CMake.txt
deleted file mode 100644
index b512997..0000000
--- a/Utilities/cmliblzma/README-CMake.txt
+++ /dev/null
@@ -1,66 +0,0 @@
-The Utilities/cmliblzma directory contains a reduced distribution
-of the liblzma source tree with only the library source code and
-CMake build system.  It is not a submodule; the actual content is part
-of our source tree and changes can be made and committed directly.
-
-We update from upstream using Git's "subtree" merge strategy.  A
-special branch contains commits of upstream liblzma snapshots and
-nothing else.  No Git ref points explicitly to the head of this
-branch, but it is merged into our history.
-
-Update liblzma from upstream as follows.  Create a local branch to
-explicitly reference the upstream snapshot branch head:
-
- git branch liblzma-upstream c289e634
-
-Use a temporary directory to checkout the branch:
-
- mkdir liblzma-tmp
- cd liblzma-tmp
- git init
- git pull .. liblzma-upstream
- rm -rf *
-
-Now place the (reduced) liblzma content in this directory.  See
-instructions shown by
-
- git log c289e634
-
-for help extracting the content from the upstream svn repo.  Then run
-the following commands to commit the new version.  Substitute the
-appropriate date and version number:
-
- git add --all
-
- GIT_AUTHOR_NAME='liblzma upstream' \
- GIT_AUTHOR_EMAIL='xz-devel at tukaani.org' \
- GIT_AUTHOR_DATE='Sun Jun 30 19:55:49 2013 +0300' \
- git commit -m 'liblzma 5.0.5-gb69900ed (reduced)' &&
- git commit --amend
-
-Edit the commit message to describe the procedure used to obtain the
-content.  Then push the changes back up to the main local repository:
-
- git push .. HEAD:liblzma-upstream
- cd ..
- rm -rf liblzma-tmp
-
-Create a topic in the main repository on which to perform the update:
-
- git checkout -b update-liblzma master
-
-Merge the liblzma-upstream branch as a subtree:
-
- git merge -s recursive -X subtree=Utilities/cmliblzma \
-           liblzma-upstream
-
-If there are conflicts, resolve them and commit.  Build and test the
-tree.  Commit any additional changes needed to succeed.
-
-Finally, run
-
- git rev-parse --short=8 liblzma-upstream
-
-to get the commit from which the liblzma-upstream branch must be started
-on the next update.  Edit the "git branch liblzma-upstream" line above to
-record it, and commit this file.
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/block.h b/Utilities/cmliblzma/liblzma/api/lzma/block.h
index 8a4bf23..e6710a7 100644
--- a/Utilities/cmliblzma/liblzma/api/lzma/block.h
+++ b/Utilities/cmliblzma/liblzma/api/lzma/block.h
@@ -318,6 +318,9 @@ extern LZMA_API(lzma_ret) lzma_block_header_encode(
  * The size of the Block Header must have already been decoded with
  * lzma_block_header_size_decode() macro and stored to block->header_size.
  *
+ * The integrity check type from Stream Header must have been stored
+ * to block->check.
+ *
  * block->filters must have been allocated, but they don't need to be
  * initialized (possible existing filter options are not freed).
  *
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/version.h b/Utilities/cmliblzma/liblzma/api/lzma/version.h
index 66e9396..09866b9 100644
--- a/Utilities/cmliblzma/liblzma/api/lzma/version.h
+++ b/Utilities/cmliblzma/liblzma/api/lzma/version.h
@@ -22,7 +22,7 @@
  */
 #define LZMA_VERSION_MAJOR 5
 #define LZMA_VERSION_MINOR 0
-#define LZMA_VERSION_PATCH 5
+#define LZMA_VERSION_PATCH 8
 #define LZMA_VERSION_STABILITY LZMA_VERSION_STABILITY_STABLE
 
 #ifndef LZMA_VERSION_COMMIT
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_fast.c b/Utilities/cmliblzma/liblzma/check/crc32_fast.c
index 13f65b4..c2c3cb7 100644
--- a/Utilities/cmliblzma/liblzma/check/crc32_fast.c
+++ b/Utilities/cmliblzma/liblzma/check/crc32_fast.c
@@ -20,7 +20,7 @@
 #include "crc_macros.h"
 
 
-// If you make any changes, do some bench marking! Seemingly unrelated
+// If you make any changes, do some benchmarking! Seemingly unrelated
 // changes can very easily ruin the performance (and very probably is
 // very compiler dependent).
 extern LZMA_API(uint32_t)
diff --git a/Utilities/cmliblzma/liblzma/check/sha256.c b/Utilities/cmliblzma/liblzma/check/sha256.c
index c2c85eb..3af6aa6 100644
--- a/Utilities/cmliblzma/liblzma/check/sha256.c
+++ b/Utilities/cmliblzma/liblzma/check/sha256.c
@@ -80,7 +80,7 @@ static const uint32_t SHA256_K[64] = {
 
 
 static void
-transform(uint32_t state[], const uint32_t data[])
+transform(uint32_t state[8], const uint32_t data[16])
 {
 	uint32_t W[16];
 	uint32_t T[8];
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c
index 8af9b9f..9332abf 100644
--- a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c
@@ -16,8 +16,9 @@
 extern LZMA_API(lzma_bool)
 lzma_lzma_preset(lzma_options_lzma *options, uint32_t preset)
 {
-	static const uint8_t dict_size_values[] = { 18, 20, 21, 22, 22, 23, 23, 24, 25, 26 };
-	static const uint8_t depth_values[] = { 4, 8, 24, 48 };
+	static const uint8_t dict_pow2[]
+			= { 18, 20, 21, 22, 22, 23, 23, 24, 25, 26 };
+	static const uint8_t depths[] = { 4, 8, 24, 48 };
 
 	const uint32_t level = preset & LZMA_PRESET_LEVEL_MASK;
 	const uint32_t flags = preset & ~LZMA_PRESET_LEVEL_MASK;
@@ -33,13 +34,13 @@ lzma_lzma_preset(lzma_options_lzma *options, uint32_t preset)
 	options->lp = LZMA_LP_DEFAULT;
 	options->pb = LZMA_PB_DEFAULT;
 
-	options->dict_size = UINT32_C(1) << dict_size_values[level];
+	options->dict_size = UINT32_C(1) << dict_pow2[level];
 
 	if (level <= 3) {
 		options->mode = LZMA_MODE_FAST;
 		options->mf = level == 0 ? LZMA_MF_HC3 : LZMA_MF_HC4;
 		options->nice_len = level <= 1 ? 128 : 273;
-		options->depth = depth_values[level];
+		options->depth = depths[level];
 	} else {
 		options->mode = LZMA_MODE_NORMAL;
 		options->mf = LZMA_MF_BT4;
diff --git a/Utilities/cmlibuv/.gitattributes b/Utilities/cmlibuv/.gitattributes
new file mode 100644
index 0000000..562b12e
--- /dev/null
+++ b/Utilities/cmlibuv/.gitattributes
@@ -0,0 +1 @@
+* -whitespace
diff --git a/Utilities/cmlibuv/CMakeLists.txt b/Utilities/cmlibuv/CMakeLists.txt
new file mode 100644
index 0000000..1b384b5
--- /dev/null
+++ b/Utilities/cmlibuv/CMakeLists.txt
@@ -0,0 +1,236 @@
+project(libuv C)
+
+# Disable warnings to avoid changing 3rd party code.
+if(CMAKE_C_COMPILER_ID MATCHES
+    "^(GNU|Clang|AppleClang|XL|VisualAge|SunPro|MIPSpro|HP|Intel)$")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w")
+elseif(CMAKE_C_COMPILER_ID STREQUAL "PathScale")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
+endif()
+
+find_package(Threads)
+
+set(uv_libraries ${CMAKE_THREAD_LIBS_INIT})
+set(uv_includes include src)
+set(uv_headers
+  include/uv.h
+  include/uv-errno.h
+  include/uv-threadpool.h
+  include/uv-version.h
+  )
+set(uv_sources
+  src/fs-poll.c
+  src/heap-inl.h
+  src/inet.c
+  src/queue.h
+  src/threadpool.c
+  src/uv-common.c
+  src/uv-common.h
+  src/version.c
+  )
+if(WIN32)
+  list(APPEND uv_libraries
+    ws2_32
+    psapi
+    iphlpapi
+    shell32
+    userenv
+    )
+  list(APPEND uv_includes
+    src/win
+    )
+  list(APPEND uv_defines
+    WIN32_LEAN_AND_MEAN
+    _WIN32_WINNT=0x0600
+    )
+  list(APPEND uv_headers
+    include/uv-win.h
+    include/tree.h
+    )
+  list(APPEND uv_sources
+    src/win/async.c
+    src/win/atomicops-inl.h
+    src/win/core.c
+    src/win/detect-wakeup.c
+    src/win/dl.c
+    src/win/error.c
+    src/win/fs-event.c
+    src/win/fs.c
+    src/win/getaddrinfo.c
+    src/win/getnameinfo.c
+    src/win/handle.c
+    src/win/handle-inl.h
+    src/win/internal.h
+    src/win/loop-watcher.c
+    src/win/pipe.c
+    src/win/poll.c
+    src/win/process-stdio.c
+    src/win/process.c
+    src/win/req.c
+    src/win/req-inl.h
+    src/win/signal.c
+    src/win/snprintf.c
+    src/win/stream.c
+    src/win/stream-inl.h
+    src/win/tcp.c
+    src/win/thread.c
+    src/win/timer.c
+    src/win/tty.c
+    src/win/udp.c
+    src/win/util.c
+    src/win/winapi.c
+    src/win/winapi.h
+    src/win/winsock.c
+    src/win/winsock.h
+    )
+else()
+  list(APPEND uv_includes
+    src/unix
+    )
+  list(APPEND uv_headers
+    include/uv-unix.h
+    )
+  list(APPEND uv_sources
+    src/unix/async.c
+    src/unix/atomic-ops.h
+    src/unix/core.c
+    src/unix/dl.c
+    src/unix/fs.c
+    src/unix/getaddrinfo.c
+    src/unix/getnameinfo.c
+    src/unix/internal.h
+    src/unix/loop-watcher.c
+    src/unix/loop.c
+    src/unix/pipe.c
+    src/unix/poll.c
+    src/unix/process.c
+    src/unix/signal.c
+    src/unix/spinlock.h
+    src/unix/stream.c
+    src/unix/tcp.c
+    src/unix/thread.c
+    src/unix/timer.c
+    src/unix/tty.c
+    src/unix/udp.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "AIX")
+  list(APPEND uv_libraries
+    perfstat
+    )
+  list(APPEND uv_headers
+    include/uv-aix.h
+    )
+  list(APPEND uv_defines
+    _ALL_SOURCE
+    _XOPEN_SOURCE=500
+    _LINUX_SOURCE_COMPAT
+    _THREAD_SAFE
+    )
+  list(APPEND uv_sources
+    src/unix/aix.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+  list(APPEND uv_headers
+    include/uv-darwin.h
+    include/pthread-barrier.h
+    )
+  list(APPEND uv_defines
+    _DARWIN_USE_64_BIT_INODE=1
+    _DARWIN_UNLIMITED_SELECT=1
+    )
+  list(APPEND uv_sources
+    src/unix/darwin.c
+    src/unix/darwin-proctitle.c
+    src/unix/fsevents.c
+    src/unix/kqueue.c
+    src/unix/proctitle.c
+    src/unix/pthread-barrier.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
+  list(APPEND uv_libraries dl rt)
+  list(APPEND uv_headers
+    include/uv-linux.h
+    )
+  list(APPEND uv_defines _GNU_SOURCE)
+  list(APPEND uv_sources
+    src/unix/linux-core.c
+    src/unix/linux-inotify.c
+    src/unix/linux-syscalls.c
+    src/unix/linux-syscalls.h
+    src/unix/proctitle.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
+  list(APPEND uv_libraries
+    kvm
+    )
+  list(APPEND uv_headers
+    include/uv-bsd.h
+    )
+  list(APPEND uv_sources
+    src/unix/freebsd.c
+    src/unix/kqueue.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "NetBSD")
+  list(APPEND uv_libraries
+    kvm
+    )
+  list(APPEND uv_headers
+    include/uv-bsd.h
+    )
+  list(APPEND uv_sources
+    src/unix/netbsd.c
+    src/unix/kqueue.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD")
+  list(APPEND uv_libraries
+    kvm
+    )
+  list(APPEND uv_headers
+    include/uv-bsd.h
+    )
+  list(APPEND uv_sources
+    src/unix/openbsd.c
+    src/unix/kqueue.c
+    )
+endif()
+
+if(CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+  list(APPEND uv_libraries
+    kstat
+    nsl
+    sendfile
+    socket
+    )
+  list(APPEND uv_headers
+    include/uv-sunos.h
+    )
+  list(APPEND uv_defines
+    __EXTENSIONS__
+    _XOPEN_SOURCE=500
+    )
+  list(APPEND uv_sources
+    src/unix/sunos.c
+    )
+endif()
+
+include_directories(
+  ${uv_includes}
+  ${KWSYS_HEADER_ROOT}
+  )
+add_library(cmlibuv STATIC ${uv_sources})
+target_link_libraries(cmlibuv ${uv_libraries})
+set_property(TARGET cmlibuv PROPERTY COMPILE_DEFINITIONS ${uv_defines})
+
+install(FILES LICENSE DESTINATION ${CMAKE_DOC_DIR}/cmlibuv)
diff --git a/Utilities/cmlibuv/LICENSE b/Utilities/cmlibuv/LICENSE
new file mode 100644
index 0000000..41ba44c
--- /dev/null
+++ b/Utilities/cmlibuv/LICENSE
@@ -0,0 +1,70 @@
+libuv is licensed for use as follows:
+
+====
+Copyright (c) 2015-present libuv project contributors.
+
+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 license applies to parts of libuv originating from the
+https://github.com/joyent/libuv repository:
+
+====
+
+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 license applies to all parts of libuv that are not externally
+maintained libraries.
+
+The externally maintained libraries used by libuv are:
+
+  - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license.
+
+  - inet_pton and inet_ntop implementations, contained in src/inet.c, are
+    copyright the Internet Systems Consortium, Inc., and licensed under the ISC
+    license.
+
+  - stdint-msvc2008.h (from msinttypes), copyright Alexander Chemeris. Three
+    clause BSD license.
+
+  - pthread-fixes.h, pthread-fixes.c, copyright Google Inc. and Sony Mobile
+    Communications AB. Three clause BSD license.
+
+  - android-ifaddrs.h, android-ifaddrs.c, copyright Berkeley Software Design
+    Inc, Kenneth MacKay and Emergya (Cloud4all, FP7/2007-2013, grant agreement
+    n° 289016). Three clause BSD license.
diff --git a/Utilities/cmlibuv/include/android-ifaddrs.h b/Utilities/cmlibuv/include/android-ifaddrs.h
new file mode 100644
index 0000000..9cd19fe
--- /dev/null
+++ b/Utilities/cmlibuv/include/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/pthread-barrier.h b/Utilities/cmlibuv/include/pthread-barrier.h
new file mode 100644
index 0000000..3e01705
--- /dev/null
+++ b/Utilities/cmlibuv/include/pthread-barrier.h
@@ -0,0 +1,66 @@
+/*
+Copyright (c) 2016, Kari Tristan Helgason <kthelgason at gmail.com>
+
+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_PTHREAD_BARRIER_
+#define _UV_PTHREAD_BARRIER_
+#include <errno.h>
+#include <pthread.h>
+#include <semaphore.h> /* sem_t */
+
+#define PTHREAD_BARRIER_SERIAL_THREAD  0x12345
+
+/*
+ * To maintain ABI compatibility with
+ * libuv v1.x struct is padded according
+ * to target platform
+ */
+#if defined(__ANDROID__)
+# define UV_BARRIER_STRUCT_PADDING \
+  sizeof(pthread_mutex_t) + \
+  sizeof(pthread_cond_t) + \
+  sizeof(unsigned int) - \
+  sizeof(void *)
+#elif defined(__APPLE__)
+# define UV_BARRIER_STRUCT_PADDING \
+  sizeof(pthread_mutex_t) + \
+  2 * sizeof(sem_t) + \
+  2 * sizeof(unsigned int) - \
+  sizeof(void *)
+#else
+# define UV_BARRIER_STRUCT_PADDING 0
+#endif
+
+typedef struct {
+  pthread_mutex_t  mutex;
+  pthread_cond_t   cond;
+  unsigned         threshold;
+  unsigned         in;
+  unsigned         out;
+} _uv_barrier;
+
+typedef struct {
+  _uv_barrier* b;
+  char _pad[UV_BARRIER_STRUCT_PADDING];
+} pthread_barrier_t;
+
+int pthread_barrier_init(pthread_barrier_t* barrier,
+                         const void* barrier_attr,
+                         unsigned count);
+
+int pthread_barrier_wait(pthread_barrier_t* barrier);
+int pthread_barrier_destroy(pthread_barrier_t *barrier);
+
+#endif /* _UV_PTHREAD_BARRIER_ */
diff --git a/Utilities/cmlibuv/include/stdint-msvc2008.h b/Utilities/cmlibuv/include/stdint-msvc2008.h
new file mode 100644
index 0000000..d02608a
--- /dev/null
+++ b/Utilities/cmlibuv/include/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/tree.h b/Utilities/cmlibuv/include/tree.h
new file mode 100644
index 0000000..f936416
--- /dev/null
+++ b/Utilities/cmlibuv/include/tree.h
@@ -0,0 +1,768 @@
+/*-
+ * Copyright 2002 Niels Provos <provos at 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-aix.h b/Utilities/cmlibuv/include/uv-aix.h
new file mode 100644
index 0000000..7dc992f
--- /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-bsd.h b/Utilities/cmlibuv/include/uv-bsd.h
new file mode 100644
index 0000000..2d72b3d
--- /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 0000000..d226415
--- /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 0000000..f137151
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv-errno.h
@@ -0,0 +1,419 @@
+/* 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>
+
+#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 (-E2BIG)
+#else
+# define UV__E2BIG (-4093)
+#endif
+
+#if defined(EACCES) && !defined(_WIN32)
+# define UV__EACCES (-EACCES)
+#else
+# define UV__EACCES (-4092)
+#endif
+
+#if defined(EADDRINUSE) && !defined(_WIN32)
+# define UV__EADDRINUSE (-EADDRINUSE)
+#else
+# define UV__EADDRINUSE (-4091)
+#endif
+
+#if defined(EADDRNOTAVAIL) && !defined(_WIN32)
+# define UV__EADDRNOTAVAIL (-EADDRNOTAVAIL)
+#else
+# define UV__EADDRNOTAVAIL (-4090)
+#endif
+
+#if defined(EAFNOSUPPORT) && !defined(_WIN32)
+# define UV__EAFNOSUPPORT (-EAFNOSUPPORT)
+#else
+# define UV__EAFNOSUPPORT (-4089)
+#endif
+
+#if defined(EAGAIN) && !defined(_WIN32)
+# define UV__EAGAIN (-EAGAIN)
+#else
+# define UV__EAGAIN (-4088)
+#endif
+
+#if defined(EALREADY) && !defined(_WIN32)
+# define UV__EALREADY (-EALREADY)
+#else
+# define UV__EALREADY (-4084)
+#endif
+
+#if defined(EBADF) && !defined(_WIN32)
+# define UV__EBADF (-EBADF)
+#else
+# define UV__EBADF (-4083)
+#endif
+
+#if defined(EBUSY) && !defined(_WIN32)
+# define UV__EBUSY (-EBUSY)
+#else
+# define UV__EBUSY (-4082)
+#endif
+
+#if defined(ECANCELED) && !defined(_WIN32)
+# define UV__ECANCELED (-ECANCELED)
+#else
+# define UV__ECANCELED (-4081)
+#endif
+
+#if defined(ECHARSET) && !defined(_WIN32)
+# define UV__ECHARSET (-ECHARSET)
+#else
+# define UV__ECHARSET (-4080)
+#endif
+
+#if defined(ECONNABORTED) && !defined(_WIN32)
+# define UV__ECONNABORTED (-ECONNABORTED)
+#else
+# define UV__ECONNABORTED (-4079)
+#endif
+
+#if defined(ECONNREFUSED) && !defined(_WIN32)
+# define UV__ECONNREFUSED (-ECONNREFUSED)
+#else
+# define UV__ECONNREFUSED (-4078)
+#endif
+
+#if defined(ECONNRESET) && !defined(_WIN32)
+# define UV__ECONNRESET (-ECONNRESET)
+#else
+# define UV__ECONNRESET (-4077)
+#endif
+
+#if defined(EDESTADDRREQ) && !defined(_WIN32)
+# define UV__EDESTADDRREQ (-EDESTADDRREQ)
+#else
+# define UV__EDESTADDRREQ (-4076)
+#endif
+
+#if defined(EEXIST) && !defined(_WIN32)
+# define UV__EEXIST (-EEXIST)
+#else
+# define UV__EEXIST (-4075)
+#endif
+
+#if defined(EFAULT) && !defined(_WIN32)
+# define UV__EFAULT (-EFAULT)
+#else
+# define UV__EFAULT (-4074)
+#endif
+
+#if defined(EHOSTUNREACH) && !defined(_WIN32)
+# define UV__EHOSTUNREACH (-EHOSTUNREACH)
+#else
+# define UV__EHOSTUNREACH (-4073)
+#endif
+
+#if defined(EINTR) && !defined(_WIN32)
+# define UV__EINTR (-EINTR)
+#else
+# define UV__EINTR (-4072)
+#endif
+
+#if defined(EINVAL) && !defined(_WIN32)
+# define UV__EINVAL (-EINVAL)
+#else
+# define UV__EINVAL (-4071)
+#endif
+
+#if defined(EIO) && !defined(_WIN32)
+# define UV__EIO (-EIO)
+#else
+# define UV__EIO (-4070)
+#endif
+
+#if defined(EISCONN) && !defined(_WIN32)
+# define UV__EISCONN (-EISCONN)
+#else
+# define UV__EISCONN (-4069)
+#endif
+
+#if defined(EISDIR) && !defined(_WIN32)
+# define UV__EISDIR (-EISDIR)
+#else
+# define UV__EISDIR (-4068)
+#endif
+
+#if defined(ELOOP) && !defined(_WIN32)
+# define UV__ELOOP (-ELOOP)
+#else
+# define UV__ELOOP (-4067)
+#endif
+
+#if defined(EMFILE) && !defined(_WIN32)
+# define UV__EMFILE (-EMFILE)
+#else
+# define UV__EMFILE (-4066)
+#endif
+
+#if defined(EMSGSIZE) && !defined(_WIN32)
+# define UV__EMSGSIZE (-EMSGSIZE)
+#else
+# define UV__EMSGSIZE (-4065)
+#endif
+
+#if defined(ENAMETOOLONG) && !defined(_WIN32)
+# define UV__ENAMETOOLONG (-ENAMETOOLONG)
+#else
+# define UV__ENAMETOOLONG (-4064)
+#endif
+
+#if defined(ENETDOWN) && !defined(_WIN32)
+# define UV__ENETDOWN (-ENETDOWN)
+#else
+# define UV__ENETDOWN (-4063)
+#endif
+
+#if defined(ENETUNREACH) && !defined(_WIN32)
+# define UV__ENETUNREACH (-ENETUNREACH)
+#else
+# define UV__ENETUNREACH (-4062)
+#endif
+
+#if defined(ENFILE) && !defined(_WIN32)
+# define UV__ENFILE (-ENFILE)
+#else
+# define UV__ENFILE (-4061)
+#endif
+
+#if defined(ENOBUFS) && !defined(_WIN32)
+# define UV__ENOBUFS (-ENOBUFS)
+#else
+# define UV__ENOBUFS (-4060)
+#endif
+
+#if defined(ENODEV) && !defined(_WIN32)
+# define UV__ENODEV (-ENODEV)
+#else
+# define UV__ENODEV (-4059)
+#endif
+
+#if defined(ENOENT) && !defined(_WIN32)
+# define UV__ENOENT (-ENOENT)
+#else
+# define UV__ENOENT (-4058)
+#endif
+
+#if defined(ENOMEM) && !defined(_WIN32)
+# define UV__ENOMEM (-ENOMEM)
+#else
+# define UV__ENOMEM (-4057)
+#endif
+
+#if defined(ENONET) && !defined(_WIN32)
+# define UV__ENONET (-ENONET)
+#else
+# define UV__ENONET (-4056)
+#endif
+
+#if defined(ENOSPC) && !defined(_WIN32)
+# define UV__ENOSPC (-ENOSPC)
+#else
+# define UV__ENOSPC (-4055)
+#endif
+
+#if defined(ENOSYS) && !defined(_WIN32)
+# define UV__ENOSYS (-ENOSYS)
+#else
+# define UV__ENOSYS (-4054)
+#endif
+
+#if defined(ENOTCONN) && !defined(_WIN32)
+# define UV__ENOTCONN (-ENOTCONN)
+#else
+# define UV__ENOTCONN (-4053)
+#endif
+
+#if defined(ENOTDIR) && !defined(_WIN32)
+# define UV__ENOTDIR (-ENOTDIR)
+#else
+# define UV__ENOTDIR (-4052)
+#endif
+
+#if defined(ENOTEMPTY) && !defined(_WIN32)
+# define UV__ENOTEMPTY (-ENOTEMPTY)
+#else
+# define UV__ENOTEMPTY (-4051)
+#endif
+
+#if defined(ENOTSOCK) && !defined(_WIN32)
+# define UV__ENOTSOCK (-ENOTSOCK)
+#else
+# define UV__ENOTSOCK (-4050)
+#endif
+
+#if defined(ENOTSUP) && !defined(_WIN32)
+# define UV__ENOTSUP (-ENOTSUP)
+#else
+# define UV__ENOTSUP (-4049)
+#endif
+
+#if defined(EPERM) && !defined(_WIN32)
+# define UV__EPERM (-EPERM)
+#else
+# define UV__EPERM (-4048)
+#endif
+
+#if defined(EPIPE) && !defined(_WIN32)
+# define UV__EPIPE (-EPIPE)
+#else
+# define UV__EPIPE (-4047)
+#endif
+
+#if defined(EPROTO) && !defined(_WIN32)
+# define UV__EPROTO (-EPROTO)
+#else
+# define UV__EPROTO (-4046)
+#endif
+
+#if defined(EPROTONOSUPPORT) && !defined(_WIN32)
+# define UV__EPROTONOSUPPORT (-EPROTONOSUPPORT)
+#else
+# define UV__EPROTONOSUPPORT (-4045)
+#endif
+
+#if defined(EPROTOTYPE) && !defined(_WIN32)
+# define UV__EPROTOTYPE (-EPROTOTYPE)
+#else
+# define UV__EPROTOTYPE (-4044)
+#endif
+
+#if defined(EROFS) && !defined(_WIN32)
+# define UV__EROFS (-EROFS)
+#else
+# define UV__EROFS (-4043)
+#endif
+
+#if defined(ESHUTDOWN) && !defined(_WIN32)
+# define UV__ESHUTDOWN (-ESHUTDOWN)
+#else
+# define UV__ESHUTDOWN (-4042)
+#endif
+
+#if defined(ESPIPE) && !defined(_WIN32)
+# define UV__ESPIPE (-ESPIPE)
+#else
+# define UV__ESPIPE (-4041)
+#endif
+
+#if defined(ESRCH) && !defined(_WIN32)
+# define UV__ESRCH (-ESRCH)
+#else
+# define UV__ESRCH (-4040)
+#endif
+
+#if defined(ETIMEDOUT) && !defined(_WIN32)
+# define UV__ETIMEDOUT (-ETIMEDOUT)
+#else
+# define UV__ETIMEDOUT (-4039)
+#endif
+
+#if defined(ETXTBSY) && !defined(_WIN32)
+# define UV__ETXTBSY (-ETXTBSY)
+#else
+# define UV__ETXTBSY (-4038)
+#endif
+
+#if defined(EXDEV) && !defined(_WIN32)
+# define UV__EXDEV (-EXDEV)
+#else
+# define UV__EXDEV (-4037)
+#endif
+
+#if defined(EFBIG) && !defined(_WIN32)
+# define UV__EFBIG (-EFBIG)
+#else
+# define UV__EFBIG (-4036)
+#endif
+
+#if defined(ENOPROTOOPT) && !defined(_WIN32)
+# define UV__ENOPROTOOPT (-ENOPROTOOPT)
+#else
+# define UV__ENOPROTOOPT (-4035)
+#endif
+
+#if defined(ERANGE) && !defined(_WIN32)
+# define UV__ERANGE (-ERANGE)
+#else
+# define UV__ERANGE (-4034)
+#endif
+
+#if defined(ENXIO) && !defined(_WIN32)
+# define UV__ENXIO (-ENXIO)
+#else
+# define UV__ENXIO (-4033)
+#endif
+
+#if defined(EMLINK) && !defined(_WIN32)
+# define UV__EMLINK (-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 (-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
+
+#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 0000000..9b38405
--- /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 0000000..b0b068f
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv-os390.h
@@ -0,0 +1,27 @@
+/* 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 int
+
+#endif /* UV_MVS_H */
diff --git a/Utilities/cmlibuv/include/uv-sunos.h b/Utilities/cmlibuv/include/uv-sunos.h
new file mode 100644
index 0000000..0421664
--- /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 0000000..9708ebd
--- /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-unix.h b/Utilities/cmlibuv/include/uv-unix.h
new file mode 100644
index 0000000..bca2714
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv-unix.h
@@ -0,0 +1,371 @@
+/* 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>
+
+#include <semaphore.h>
+#include <pthread.h>
+#include <signal.h>
+
+#include "uv-threadpool.h"
+
+#if defined(__linux__)
+# include "uv-linux.h"
+#elif defined(_AIX)
+# include "uv-aix.h"
+#elif defined(__sun)
+# include "uv-sunos.h"
+#elif defined(__APPLE__)
+# include "uv-darwin.h"
+#elif defined(__DragonFly__)       || \
+      defined(__FreeBSD__)         || \
+      defined(__FreeBSD_kernel__)  || \
+      defined(__OpenBSD__)         || \
+      defined(__NetBSD__)
+# include "uv-bsd.h"
+#endif
+
+#ifndef PTHREAD_BARRIER_SERIAL_THREAD
+# include "pthread-barrier.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__async;
+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
+};
+
+typedef void (*uv__async_cb)(struct uv_loop_s* loop,
+                             struct uv__async* w,
+                             unsigned int nevents);
+
+struct uv__async {
+  uv__async_cb cb;
+  uv__io_t io_watcher;
+  int wfd;
+};
+
+#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;
+
+#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;
+typedef pthread_barrier_t uv_barrier_t;
+
+
+/* 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];                                                     \
+  struct uv__async async_watcher;                                             \
+  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                                                 \
+
+#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 0000000..3cb9b5f
--- /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 9
+#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 0000000..89ee09a
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv-win.h
@@ -0,0 +1,660 @@
+/* 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   0x0502
+#endif
+
+#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
+typedef intptr_t ssize_t;
+# 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 <sys/stat.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#include "tree.h"
+#include "uv-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
+
+/* 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 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;
+  } fallback;
+} 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;
+
+RB_HEAD(uv_timer_tree_s, uv_timer_s);
+
+#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;                                               \
+  /* The head of the timers tree */                                           \
+  struct uv_timer_tree_s timers;                                              \
+    /* 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 ipc_header;                                                             \
+  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 ipc_header_write_req;                                            \
+  int ipc_pid;                                                                \
+  uint64_t remaining_ipc_rawdata_bytes;                                       \
+  struct {                                                                    \
+    void* queue[2];                                                           \
+    int queue_len;                                                            \
+  } pending_ipc_info;                                                         \
+  uv_write_t* non_overlapped_writes_tail;                                     \
+  uv_mutex_t readfile_mutex;                                                  \
+  volatile HANDLE readfile_thread;
+
+#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                                               \
+  RB_ENTRY(uv_timer_s) tree_entry;                                            \
+  uint64_t due;                                                               \
+  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
diff --git a/Utilities/cmlibuv/include/uv.h b/Utilities/cmlibuv/include/uv.h
new file mode 100644
index 0000000..e3e20dc
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv.h
@@ -0,0 +1,1499 @@
+/* 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.
+ */
+
+/* See https://github.com/libuv/libuv#documentation for documentation. */
+
+#ifndef UV_H
+#define UV_H
+
+/* Include KWSys Large File Support configuration. */
+#include <cmsys/Configure.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef _WIN32
+  /* Windows - set up dll import/export decorators. */
+# if defined(BUILDING_UV_SHARED)
+    /* Building shared library. */
+#   define UV_EXTERN __declspec(dllexport)
+# elif defined(USING_UV_SHARED)
+    /* Using shared library. */
+#   define UV_EXTERN __declspec(dllimport)
+# else
+    /* Building static library. */
+#   define UV_EXTERN /* nothing */
+# endif
+#elif __GNUC__ >= 4
+# define UV_EXTERN __attribute__((visibility("default")))
+#else
+# define UV_EXTERN /* nothing */
+#endif
+
+#include "uv-errno.h"
+#include "uv-version.h"
+#include <stddef.h>
+#include <stdio.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#if defined(_WIN32)
+# include "uv-win.h"
+#else
+# include "uv-unix.h"
+#endif
+
+/* Expand this list if necessary. */
+#define UV_ERRNO_MAP(XX)                                                      \
+  XX(E2BIG, "argument list too long")                                         \
+  XX(EACCES, "permission denied")                                             \
+  XX(EADDRINUSE, "address already in use")                                    \
+  XX(EADDRNOTAVAIL, "address not available")                                  \
+  XX(EAFNOSUPPORT, "address family not supported")                            \
+  XX(EAGAIN, "resource temporarily unavailable")                              \
+  XX(EAI_ADDRFAMILY, "address family not supported")                          \
+  XX(EAI_AGAIN, "temporary failure")                                          \
+  XX(EAI_BADFLAGS, "bad ai_flags value")                                      \
+  XX(EAI_BADHINTS, "invalid value for hints")                                 \
+  XX(EAI_CANCELED, "request canceled")                                        \
+  XX(EAI_FAIL, "permanent failure")                                           \
+  XX(EAI_FAMILY, "ai_family not supported")                                   \
+  XX(EAI_MEMORY, "out of memory")                                             \
+  XX(EAI_NODATA, "no address")                                                \
+  XX(EAI_NONAME, "unknown node or service")                                   \
+  XX(EAI_OVERFLOW, "argument buffer overflow")                                \
+  XX(EAI_PROTOCOL, "resolved protocol is unknown")                            \
+  XX(EAI_SERVICE, "service not available for socket type")                    \
+  XX(EAI_SOCKTYPE, "socket type not supported")                               \
+  XX(EALREADY, "connection already in progress")                              \
+  XX(EBADF, "bad file descriptor")                                            \
+  XX(EBUSY, "resource busy or locked")                                        \
+  XX(ECANCELED, "operation canceled")                                         \
+  XX(ECHARSET, "invalid Unicode character")                                   \
+  XX(ECONNABORTED, "software caused connection abort")                        \
+  XX(ECONNREFUSED, "connection refused")                                      \
+  XX(ECONNRESET, "connection reset by peer")                                  \
+  XX(EDESTADDRREQ, "destination address required")                            \
+  XX(EEXIST, "file already exists")                                           \
+  XX(EFAULT, "bad address in system call argument")                           \
+  XX(EFBIG, "file too large")                                                 \
+  XX(EHOSTUNREACH, "host is unreachable")                                     \
+  XX(EINTR, "interrupted system call")                                        \
+  XX(EINVAL, "invalid argument")                                              \
+  XX(EIO, "i/o error")                                                        \
+  XX(EISCONN, "socket is already connected")                                  \
+  XX(EISDIR, "illegal operation on a directory")                              \
+  XX(ELOOP, "too many symbolic links encountered")                            \
+  XX(EMFILE, "too many open files")                                           \
+  XX(EMSGSIZE, "message too long")                                            \
+  XX(ENAMETOOLONG, "name too long")                                           \
+  XX(ENETDOWN, "network is down")                                             \
+  XX(ENETUNREACH, "network is unreachable")                                   \
+  XX(ENFILE, "file table overflow")                                           \
+  XX(ENOBUFS, "no buffer space available")                                    \
+  XX(ENODEV, "no such device")                                                \
+  XX(ENOENT, "no such file or directory")                                     \
+  XX(ENOMEM, "not enough memory")                                             \
+  XX(ENONET, "machine is not on the network")                                 \
+  XX(ENOPROTOOPT, "protocol not available")                                   \
+  XX(ENOSPC, "no space left on device")                                       \
+  XX(ENOSYS, "function not implemented")                                      \
+  XX(ENOTCONN, "socket is not connected")                                     \
+  XX(ENOTDIR, "not a directory")                                              \
+  XX(ENOTEMPTY, "directory not empty")                                        \
+  XX(ENOTSOCK, "socket operation on non-socket")                              \
+  XX(ENOTSUP, "operation not supported on socket")                            \
+  XX(EPERM, "operation not permitted")                                        \
+  XX(EPIPE, "broken pipe")                                                    \
+  XX(EPROTO, "protocol error")                                                \
+  XX(EPROTONOSUPPORT, "protocol not supported")                               \
+  XX(EPROTOTYPE, "protocol wrong type for socket")                            \
+  XX(ERANGE, "result too large")                                              \
+  XX(EROFS, "read-only file system")                                          \
+  XX(ESHUTDOWN, "cannot send after transport endpoint shutdown")              \
+  XX(ESPIPE, "invalid seek")                                                  \
+  XX(ESRCH, "no such process")                                                \
+  XX(ETIMEDOUT, "connection timed out")                                       \
+  XX(ETXTBSY, "text file is busy")                                            \
+  XX(EXDEV, "cross-device link not permitted")                                \
+  XX(UNKNOWN, "unknown error")                                                \
+  XX(EOF, "end of file")                                                      \
+  XX(ENXIO, "no such device or address")                                      \
+  XX(EMLINK, "too many links")                                                \
+  XX(EHOSTDOWN, "host is down")                                               \
+
+#define UV_HANDLE_TYPE_MAP(XX)                                                \
+  XX(ASYNC, async)                                                            \
+  XX(CHECK, check)                                                            \
+  XX(FS_EVENT, fs_event)                                                      \
+  XX(FS_POLL, fs_poll)                                                        \
+  XX(HANDLE, handle)                                                          \
+  XX(IDLE, idle)                                                              \
+  XX(NAMED_PIPE, pipe)                                                        \
+  XX(POLL, poll)                                                              \
+  XX(PREPARE, prepare)                                                        \
+  XX(PROCESS, process)                                                        \
+  XX(STREAM, stream)                                                          \
+  XX(TCP, tcp)                                                                \
+  XX(TIMER, timer)                                                            \
+  XX(TTY, tty)                                                                \
+  XX(UDP, udp)                                                                \
+  XX(SIGNAL, signal)                                                          \
+
+#define UV_REQ_TYPE_MAP(XX)                                                   \
+  XX(REQ, req)                                                                \
+  XX(CONNECT, connect)                                                        \
+  XX(WRITE, write)                                                            \
+  XX(SHUTDOWN, shutdown)                                                      \
+  XX(UDP_SEND, udp_send)                                                      \
+  XX(FS, fs)                                                                  \
+  XX(WORK, work)                                                              \
+  XX(GETADDRINFO, getaddrinfo)                                                \
+  XX(GETNAMEINFO, getnameinfo)                                                \
+
+typedef enum {
+#define XX(code, _) UV_ ## code = UV__ ## code,
+  UV_ERRNO_MAP(XX)
+#undef XX
+  UV_ERRNO_MAX = UV__EOF - 1
+} uv_errno_t;
+
+typedef enum {
+  UV_UNKNOWN_HANDLE = 0,
+#define XX(uc, lc) UV_##uc,
+  UV_HANDLE_TYPE_MAP(XX)
+#undef XX
+  UV_FILE,
+  UV_HANDLE_TYPE_MAX
+} uv_handle_type;
+
+typedef enum {
+  UV_UNKNOWN_REQ = 0,
+#define XX(uc, lc) UV_##uc,
+  UV_REQ_TYPE_MAP(XX)
+#undef XX
+  UV_REQ_TYPE_PRIVATE
+  UV_REQ_TYPE_MAX
+} uv_req_type;
+
+
+/* Handle types. */
+typedef struct uv_loop_s uv_loop_t;
+typedef struct uv_handle_s uv_handle_t;
+typedef struct uv_stream_s uv_stream_t;
+typedef struct uv_tcp_s uv_tcp_t;
+typedef struct uv_udp_s uv_udp_t;
+typedef struct uv_pipe_s uv_pipe_t;
+typedef struct uv_tty_s uv_tty_t;
+typedef struct uv_poll_s uv_poll_t;
+typedef struct uv_timer_s uv_timer_t;
+typedef struct uv_prepare_s uv_prepare_t;
+typedef struct uv_check_s uv_check_t;
+typedef struct uv_idle_s uv_idle_t;
+typedef struct uv_async_s uv_async_t;
+typedef struct uv_process_s uv_process_t;
+typedef struct uv_fs_event_s uv_fs_event_t;
+typedef struct uv_fs_poll_s uv_fs_poll_t;
+typedef struct uv_signal_s uv_signal_t;
+
+/* Request types. */
+typedef struct uv_req_s uv_req_t;
+typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
+typedef struct uv_getnameinfo_s uv_getnameinfo_t;
+typedef struct uv_shutdown_s uv_shutdown_t;
+typedef struct uv_write_s uv_write_t;
+typedef struct uv_connect_s uv_connect_t;
+typedef struct uv_udp_send_s uv_udp_send_t;
+typedef struct uv_fs_s uv_fs_t;
+typedef struct uv_work_s uv_work_t;
+
+/* None of the above. */
+typedef struct uv_cpu_info_s uv_cpu_info_t;
+typedef struct uv_interface_address_s uv_interface_address_t;
+typedef struct uv_dirent_s uv_dirent_t;
+typedef struct uv_passwd_s uv_passwd_t;
+
+typedef enum {
+  UV_LOOP_BLOCK_SIGNAL
+} uv_loop_option;
+
+typedef enum {
+  UV_RUN_DEFAULT = 0,
+  UV_RUN_ONCE,
+  UV_RUN_NOWAIT
+} uv_run_mode;
+
+
+UV_EXTERN unsigned int uv_version(void);
+UV_EXTERN const char* uv_version_string(void);
+
+typedef void* (*uv_malloc_func)(size_t size);
+typedef void* (*uv_realloc_func)(void* ptr, size_t size);
+typedef void* (*uv_calloc_func)(size_t count, size_t size);
+typedef void (*uv_free_func)(void* ptr);
+
+UV_EXTERN int uv_replace_allocator(uv_malloc_func malloc_func,
+                                   uv_realloc_func realloc_func,
+                                   uv_calloc_func calloc_func,
+                                   uv_free_func free_func);
+
+UV_EXTERN uv_loop_t* uv_default_loop(void);
+UV_EXTERN int uv_loop_init(uv_loop_t* loop);
+UV_EXTERN int uv_loop_close(uv_loop_t* loop);
+/*
+ * NOTE:
+ *  This function is DEPRECATED (to be removed after 0.12), users should
+ *  allocate the loop manually and use uv_loop_init instead.
+ */
+UV_EXTERN uv_loop_t* uv_loop_new(void);
+/*
+ * NOTE:
+ *  This function is DEPRECATED (to be removed after 0.12). Users should use
+ *  uv_loop_close and free the memory manually instead.
+ */
+UV_EXTERN void uv_loop_delete(uv_loop_t*);
+UV_EXTERN size_t uv_loop_size(void);
+UV_EXTERN int uv_loop_alive(const uv_loop_t* loop);
+UV_EXTERN int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...);
+
+UV_EXTERN int uv_run(uv_loop_t*, uv_run_mode mode);
+UV_EXTERN void uv_stop(uv_loop_t*);
+
+UV_EXTERN void uv_ref(uv_handle_t*);
+UV_EXTERN void uv_unref(uv_handle_t*);
+UV_EXTERN int uv_has_ref(const uv_handle_t*);
+
+UV_EXTERN void uv_update_time(uv_loop_t*);
+UV_EXTERN uint64_t uv_now(const uv_loop_t*);
+
+UV_EXTERN int uv_backend_fd(const uv_loop_t*);
+UV_EXTERN int uv_backend_timeout(const uv_loop_t*);
+
+typedef void (*uv_alloc_cb)(uv_handle_t* handle,
+                            size_t suggested_size,
+                            uv_buf_t* buf);
+typedef void (*uv_read_cb)(uv_stream_t* stream,
+                           ssize_t nread,
+                           const uv_buf_t* buf);
+typedef void (*uv_write_cb)(uv_write_t* req, int status);
+typedef void (*uv_connect_cb)(uv_connect_t* req, int status);
+typedef void (*uv_shutdown_cb)(uv_shutdown_t* req, int status);
+typedef void (*uv_connection_cb)(uv_stream_t* server, int status);
+typedef void (*uv_close_cb)(uv_handle_t* handle);
+typedef void (*uv_poll_cb)(uv_poll_t* handle, int status, int events);
+typedef void (*uv_timer_cb)(uv_timer_t* handle);
+typedef void (*uv_async_cb)(uv_async_t* handle);
+typedef void (*uv_prepare_cb)(uv_prepare_t* handle);
+typedef void (*uv_check_cb)(uv_check_t* handle);
+typedef void (*uv_idle_cb)(uv_idle_t* handle);
+typedef void (*uv_exit_cb)(uv_process_t*, int64_t exit_status, int term_signal);
+typedef void (*uv_walk_cb)(uv_handle_t* handle, void* arg);
+typedef void (*uv_fs_cb)(uv_fs_t* req);
+typedef void (*uv_work_cb)(uv_work_t* req);
+typedef void (*uv_after_work_cb)(uv_work_t* req, int status);
+typedef void (*uv_getaddrinfo_cb)(uv_getaddrinfo_t* req,
+                                  int status,
+                                  struct addrinfo* res);
+typedef void (*uv_getnameinfo_cb)(uv_getnameinfo_t* req,
+                                  int status,
+                                  const char* hostname,
+                                  const char* service);
+
+typedef struct {
+  long tv_sec;
+  long tv_nsec;
+} uv_timespec_t;
+
+
+typedef struct {
+  uint64_t st_dev;
+  uint64_t st_mode;
+  uint64_t st_nlink;
+  uint64_t st_uid;
+  uint64_t st_gid;
+  uint64_t st_rdev;
+  uint64_t st_ino;
+  uint64_t st_size;
+  uint64_t st_blksize;
+  uint64_t st_blocks;
+  uint64_t st_flags;
+  uint64_t st_gen;
+  uv_timespec_t st_atim;
+  uv_timespec_t st_mtim;
+  uv_timespec_t st_ctim;
+  uv_timespec_t st_birthtim;
+} uv_stat_t;
+
+
+typedef void (*uv_fs_event_cb)(uv_fs_event_t* handle,
+                               const char* filename,
+                               int events,
+                               int status);
+
+typedef void (*uv_fs_poll_cb)(uv_fs_poll_t* handle,
+                              int status,
+                              const uv_stat_t* prev,
+                              const uv_stat_t* curr);
+
+typedef void (*uv_signal_cb)(uv_signal_t* handle, int signum);
+
+
+typedef enum {
+  UV_LEAVE_GROUP = 0,
+  UV_JOIN_GROUP
+} uv_membership;
+
+
+UV_EXTERN const char* uv_strerror(int err);
+UV_EXTERN const char* uv_err_name(int err);
+
+
+#define UV_REQ_FIELDS                                                         \
+  /* public */                                                                \
+  void* data;                                                                 \
+  /* read-only */                                                             \
+  uv_req_type type;                                                           \
+  /* private */                                                               \
+  void* active_queue[2];                                                      \
+  void* reserved[4];                                                          \
+  UV_REQ_PRIVATE_FIELDS                                                       \
+
+/* Abstract base class of all requests. */
+struct uv_req_s {
+  UV_REQ_FIELDS
+};
+
+
+/* Platform-specific request types. */
+UV_PRIVATE_REQ_TYPES
+
+
+UV_EXTERN int uv_shutdown(uv_shutdown_t* req,
+                          uv_stream_t* handle,
+                          uv_shutdown_cb cb);
+
+struct uv_shutdown_s {
+  UV_REQ_FIELDS
+  uv_stream_t* handle;
+  uv_shutdown_cb cb;
+  UV_SHUTDOWN_PRIVATE_FIELDS
+};
+
+
+#define UV_HANDLE_FIELDS                                                      \
+  /* public */                                                                \
+  void* data;                                                                 \
+  /* read-only */                                                             \
+  uv_loop_t* loop;                                                            \
+  uv_handle_type type;                                                        \
+  /* private */                                                               \
+  uv_close_cb close_cb;                                                       \
+  void* handle_queue[2];                                                      \
+  union {                                                                     \
+    int fd;                                                                   \
+    void* reserved[4];                                                        \
+  } u;                                                                        \
+  UV_HANDLE_PRIVATE_FIELDS                                                    \
+
+/* The abstract base class of all handles. */
+struct uv_handle_s {
+  UV_HANDLE_FIELDS
+};
+
+UV_EXTERN size_t uv_handle_size(uv_handle_type type);
+UV_EXTERN size_t uv_req_size(uv_req_type type);
+
+UV_EXTERN int uv_is_active(const uv_handle_t* handle);
+
+UV_EXTERN void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg);
+
+/* Helpers for ad hoc debugging, no API/ABI stability guaranteed. */
+UV_EXTERN void uv_print_all_handles(uv_loop_t* loop, FILE* stream);
+UV_EXTERN void uv_print_active_handles(uv_loop_t* loop, FILE* stream);
+
+UV_EXTERN void uv_close(uv_handle_t* handle, uv_close_cb close_cb);
+
+UV_EXTERN int uv_send_buffer_size(uv_handle_t* handle, int* value);
+UV_EXTERN int uv_recv_buffer_size(uv_handle_t* handle, int* value);
+
+UV_EXTERN int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd);
+
+UV_EXTERN uv_buf_t uv_buf_init(char* base, unsigned int len);
+
+
+#define UV_STREAM_FIELDS                                                      \
+  /* number of bytes queued for writing */                                    \
+  size_t write_queue_size;                                                    \
+  uv_alloc_cb alloc_cb;                                                       \
+  uv_read_cb read_cb;                                                         \
+  /* private */                                                               \
+  UV_STREAM_PRIVATE_FIELDS
+
+/*
+ * uv_stream_t is a subclass of uv_handle_t.
+ *
+ * uv_stream is an abstract class.
+ *
+ * uv_stream_t is the parent class of uv_tcp_t, uv_pipe_t and uv_tty_t.
+ */
+struct uv_stream_s {
+  UV_HANDLE_FIELDS
+  UV_STREAM_FIELDS
+};
+
+UV_EXTERN int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb);
+UV_EXTERN int uv_accept(uv_stream_t* server, uv_stream_t* client);
+
+UV_EXTERN int uv_read_start(uv_stream_t*,
+                            uv_alloc_cb alloc_cb,
+                            uv_read_cb read_cb);
+UV_EXTERN int uv_read_stop(uv_stream_t*);
+
+UV_EXTERN int uv_write(uv_write_t* req,
+                       uv_stream_t* handle,
+                       const uv_buf_t bufs[],
+                       unsigned int nbufs,
+                       uv_write_cb cb);
+UV_EXTERN int uv_write2(uv_write_t* req,
+                        uv_stream_t* handle,
+                        const uv_buf_t bufs[],
+                        unsigned int nbufs,
+                        uv_stream_t* send_handle,
+                        uv_write_cb cb);
+UV_EXTERN int uv_try_write(uv_stream_t* handle,
+                           const uv_buf_t bufs[],
+                           unsigned int nbufs);
+
+/* uv_write_t is a subclass of uv_req_t. */
+struct uv_write_s {
+  UV_REQ_FIELDS
+  uv_write_cb cb;
+  uv_stream_t* send_handle;
+  uv_stream_t* handle;
+  UV_WRITE_PRIVATE_FIELDS
+};
+
+
+UV_EXTERN int uv_is_readable(const uv_stream_t* handle);
+UV_EXTERN int uv_is_writable(const uv_stream_t* handle);
+
+UV_EXTERN int uv_stream_set_blocking(uv_stream_t* handle, int blocking);
+
+UV_EXTERN int uv_is_closing(const uv_handle_t* handle);
+
+
+/*
+ * uv_tcp_t is a subclass of uv_stream_t.
+ *
+ * Represents a TCP stream or TCP server.
+ */
+struct uv_tcp_s {
+  UV_HANDLE_FIELDS
+  UV_STREAM_FIELDS
+  UV_TCP_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_tcp_init(uv_loop_t*, uv_tcp_t* handle);
+UV_EXTERN int uv_tcp_init_ex(uv_loop_t*, uv_tcp_t* handle, unsigned int flags);
+UV_EXTERN int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock);
+UV_EXTERN int uv_tcp_nodelay(uv_tcp_t* handle, int enable);
+UV_EXTERN int uv_tcp_keepalive(uv_tcp_t* handle,
+                               int enable,
+                               unsigned int delay);
+UV_EXTERN int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable);
+
+enum uv_tcp_flags {
+  /* Used with uv_tcp_bind, when an IPv6 address is used. */
+  UV_TCP_IPV6ONLY = 1
+};
+
+UV_EXTERN int uv_tcp_bind(uv_tcp_t* handle,
+                          const struct sockaddr* addr,
+                          unsigned int flags);
+UV_EXTERN int uv_tcp_getsockname(const uv_tcp_t* handle,
+                                 struct sockaddr* name,
+                                 int* namelen);
+UV_EXTERN int uv_tcp_getpeername(const uv_tcp_t* handle,
+                                 struct sockaddr* name,
+                                 int* namelen);
+UV_EXTERN int uv_tcp_connect(uv_connect_t* req,
+                             uv_tcp_t* handle,
+                             const struct sockaddr* addr,
+                             uv_connect_cb cb);
+
+/* uv_connect_t is a subclass of uv_req_t. */
+struct uv_connect_s {
+  UV_REQ_FIELDS
+  uv_connect_cb cb;
+  uv_stream_t* handle;
+  UV_CONNECT_PRIVATE_FIELDS
+};
+
+
+/*
+ * UDP support.
+ */
+
+enum uv_udp_flags {
+  /* Disables dual stack mode. */
+  UV_UDP_IPV6ONLY = 1,
+  /*
+   * Indicates message was truncated because read buffer was too small. The
+   * remainder was discarded by the OS. Used in uv_udp_recv_cb.
+   */
+  UV_UDP_PARTIAL = 2,
+  /*
+   * Indicates if SO_REUSEADDR will be set when binding the handle.
+   * This sets the SO_REUSEPORT socket flag on the BSDs and OS X. On other
+   * Unix platforms, it sets the SO_REUSEADDR flag.  What that means is that
+   * multiple threads or processes can bind to the same address without error
+   * (provided they all set the flag) but only the last one to bind will receive
+   * any traffic, in effect "stealing" the port from the previous listener.
+   */
+  UV_UDP_REUSEADDR = 4
+};
+
+typedef void (*uv_udp_send_cb)(uv_udp_send_t* req, int status);
+typedef void (*uv_udp_recv_cb)(uv_udp_t* handle,
+                               ssize_t nread,
+                               const uv_buf_t* buf,
+                               const struct sockaddr* addr,
+                               unsigned flags);
+
+/* uv_udp_t is a subclass of uv_handle_t. */
+struct uv_udp_s {
+  UV_HANDLE_FIELDS
+  /* read-only */
+  /*
+   * Number of bytes queued for sending. This field strictly shows how much
+   * information is currently queued.
+   */
+  size_t send_queue_size;
+  /*
+   * Number of send requests currently in the queue awaiting to be processed.
+   */
+  size_t send_queue_count;
+  UV_UDP_PRIVATE_FIELDS
+};
+
+/* uv_udp_send_t is a subclass of uv_req_t. */
+struct uv_udp_send_s {
+  UV_REQ_FIELDS
+  uv_udp_t* handle;
+  uv_udp_send_cb cb;
+  UV_UDP_SEND_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_udp_init(uv_loop_t*, uv_udp_t* handle);
+UV_EXTERN int uv_udp_init_ex(uv_loop_t*, uv_udp_t* handle, unsigned int flags);
+UV_EXTERN int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock);
+UV_EXTERN int uv_udp_bind(uv_udp_t* handle,
+                          const struct sockaddr* addr,
+                          unsigned int flags);
+
+UV_EXTERN int uv_udp_getsockname(const uv_udp_t* handle,
+                                 struct sockaddr* name,
+                                 int* namelen);
+UV_EXTERN int uv_udp_set_membership(uv_udp_t* handle,
+                                    const char* multicast_addr,
+                                    const char* interface_addr,
+                                    uv_membership membership);
+UV_EXTERN int uv_udp_set_multicast_loop(uv_udp_t* handle, int on);
+UV_EXTERN int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl);
+UV_EXTERN int uv_udp_set_multicast_interface(uv_udp_t* handle,
+                                             const char* interface_addr);
+UV_EXTERN int uv_udp_set_broadcast(uv_udp_t* handle, int on);
+UV_EXTERN int uv_udp_set_ttl(uv_udp_t* handle, int ttl);
+UV_EXTERN int uv_udp_send(uv_udp_send_t* req,
+                          uv_udp_t* handle,
+                          const uv_buf_t bufs[],
+                          unsigned int nbufs,
+                          const struct sockaddr* addr,
+                          uv_udp_send_cb send_cb);
+UV_EXTERN int uv_udp_try_send(uv_udp_t* handle,
+                              const uv_buf_t bufs[],
+                              unsigned int nbufs,
+                              const struct sockaddr* addr);
+UV_EXTERN int uv_udp_recv_start(uv_udp_t* handle,
+                                uv_alloc_cb alloc_cb,
+                                uv_udp_recv_cb recv_cb);
+UV_EXTERN int uv_udp_recv_stop(uv_udp_t* handle);
+
+
+/*
+ * uv_tty_t is a subclass of uv_stream_t.
+ *
+ * Representing a stream for the console.
+ */
+struct uv_tty_s {
+  UV_HANDLE_FIELDS
+  UV_STREAM_FIELDS
+  UV_TTY_PRIVATE_FIELDS
+};
+
+typedef enum {
+  /* Initial/normal terminal mode */
+  UV_TTY_MODE_NORMAL,
+  /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */
+  UV_TTY_MODE_RAW,
+  /* Binary-safe I/O mode for IPC (Unix-only) */
+  UV_TTY_MODE_IO
+} uv_tty_mode_t;
+
+UV_EXTERN int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int readable);
+UV_EXTERN int uv_tty_set_mode(uv_tty_t*, uv_tty_mode_t mode);
+UV_EXTERN int uv_tty_reset_mode(void);
+UV_EXTERN int uv_tty_get_winsize(uv_tty_t*, int* width, int* height);
+
+#ifdef __cplusplus
+extern "C++" {
+
+inline int uv_tty_set_mode(uv_tty_t* handle, int mode) {
+  return uv_tty_set_mode(handle, static_cast<uv_tty_mode_t>(mode));
+}
+
+}
+#endif
+
+UV_EXTERN uv_handle_type uv_guess_handle(uv_file file);
+
+/*
+ * uv_pipe_t is a subclass of uv_stream_t.
+ *
+ * Representing a pipe stream or pipe server. On Windows this is a Named
+ * Pipe. On Unix this is a Unix domain socket.
+ */
+struct uv_pipe_s {
+  UV_HANDLE_FIELDS
+  UV_STREAM_FIELDS
+  int ipc; /* non-zero if this pipe is used for passing handles */
+  UV_PIPE_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_pipe_init(uv_loop_t*, uv_pipe_t* handle, int ipc);
+UV_EXTERN int uv_pipe_open(uv_pipe_t*, uv_file file);
+UV_EXTERN int uv_pipe_bind(uv_pipe_t* handle, const char* name);
+UV_EXTERN void uv_pipe_connect(uv_connect_t* req,
+                               uv_pipe_t* handle,
+                               const char* name,
+                               uv_connect_cb cb);
+UV_EXTERN int uv_pipe_getsockname(const uv_pipe_t* handle,
+                                  char* buffer,
+                                  size_t* size);
+UV_EXTERN int uv_pipe_getpeername(const uv_pipe_t* handle,
+                                  char* buffer,
+                                  size_t* size);
+UV_EXTERN void uv_pipe_pending_instances(uv_pipe_t* handle, int count);
+UV_EXTERN int uv_pipe_pending_count(uv_pipe_t* handle);
+UV_EXTERN uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle);
+
+
+struct uv_poll_s {
+  UV_HANDLE_FIELDS
+  uv_poll_cb poll_cb;
+  UV_POLL_PRIVATE_FIELDS
+};
+
+enum uv_poll_event {
+  UV_READABLE = 1,
+  UV_WRITABLE = 2,
+  UV_DISCONNECT = 4
+};
+
+UV_EXTERN int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd);
+UV_EXTERN int uv_poll_init_socket(uv_loop_t* loop,
+                                  uv_poll_t* handle,
+                                  uv_os_sock_t socket);
+UV_EXTERN int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb);
+UV_EXTERN int uv_poll_stop(uv_poll_t* handle);
+
+
+struct uv_prepare_s {
+  UV_HANDLE_FIELDS
+  UV_PREPARE_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_prepare_init(uv_loop_t*, uv_prepare_t* prepare);
+UV_EXTERN int uv_prepare_start(uv_prepare_t* prepare, uv_prepare_cb cb);
+UV_EXTERN int uv_prepare_stop(uv_prepare_t* prepare);
+
+
+struct uv_check_s {
+  UV_HANDLE_FIELDS
+  UV_CHECK_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_check_init(uv_loop_t*, uv_check_t* check);
+UV_EXTERN int uv_check_start(uv_check_t* check, uv_check_cb cb);
+UV_EXTERN int uv_check_stop(uv_check_t* check);
+
+
+struct uv_idle_s {
+  UV_HANDLE_FIELDS
+  UV_IDLE_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_idle_init(uv_loop_t*, uv_idle_t* idle);
+UV_EXTERN int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb);
+UV_EXTERN int uv_idle_stop(uv_idle_t* idle);
+
+
+struct uv_async_s {
+  UV_HANDLE_FIELDS
+  UV_ASYNC_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_async_init(uv_loop_t*,
+                            uv_async_t* async,
+                            uv_async_cb async_cb);
+UV_EXTERN int uv_async_send(uv_async_t* async);
+
+
+/*
+ * uv_timer_t is a subclass of uv_handle_t.
+ *
+ * Used to get woken up at a specified time in the future.
+ */
+struct uv_timer_s {
+  UV_HANDLE_FIELDS
+  UV_TIMER_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_timer_init(uv_loop_t*, uv_timer_t* handle);
+UV_EXTERN int uv_timer_start(uv_timer_t* handle,
+                             uv_timer_cb cb,
+                             uint64_t timeout,
+                             uint64_t repeat);
+UV_EXTERN int uv_timer_stop(uv_timer_t* handle);
+UV_EXTERN int uv_timer_again(uv_timer_t* handle);
+UV_EXTERN void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat);
+UV_EXTERN uint64_t uv_timer_get_repeat(const uv_timer_t* handle);
+
+
+/*
+ * uv_getaddrinfo_t is a subclass of uv_req_t.
+ *
+ * Request object for uv_getaddrinfo.
+ */
+struct uv_getaddrinfo_s {
+  UV_REQ_FIELDS
+  /* read-only */
+  uv_loop_t* loop;
+  /* struct addrinfo* addrinfo is marked as private, but it really isn't. */
+  UV_GETADDRINFO_PRIVATE_FIELDS
+};
+
+
+UV_EXTERN int uv_getaddrinfo(uv_loop_t* loop,
+                             uv_getaddrinfo_t* req,
+                             uv_getaddrinfo_cb getaddrinfo_cb,
+                             const char* node,
+                             const char* service,
+                             const struct addrinfo* hints);
+UV_EXTERN void uv_freeaddrinfo(struct addrinfo* ai);
+
+
+/*
+* uv_getnameinfo_t is a subclass of uv_req_t.
+*
+* Request object for uv_getnameinfo.
+*/
+struct uv_getnameinfo_s {
+  UV_REQ_FIELDS
+  /* read-only */
+  uv_loop_t* loop;
+  /* host and service are marked as private, but they really aren't. */
+  UV_GETNAMEINFO_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_getnameinfo(uv_loop_t* loop,
+                             uv_getnameinfo_t* req,
+                             uv_getnameinfo_cb getnameinfo_cb,
+                             const struct sockaddr* addr,
+                             int flags);
+
+
+/* uv_spawn() options. */
+typedef enum {
+  UV_IGNORE         = 0x00,
+  UV_CREATE_PIPE    = 0x01,
+  UV_INHERIT_FD     = 0x02,
+  UV_INHERIT_STREAM = 0x04,
+
+  /*
+   * When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE
+   * determine the direction of flow, from the child process' perspective. Both
+   * flags may be specified to create a duplex data stream.
+   */
+  UV_READABLE_PIPE  = 0x10,
+  UV_WRITABLE_PIPE  = 0x20
+} uv_stdio_flags;
+
+typedef struct uv_stdio_container_s {
+  uv_stdio_flags flags;
+
+  union {
+    uv_stream_t* stream;
+    int fd;
+  } data;
+} uv_stdio_container_t;
+
+typedef struct uv_process_options_s {
+  uv_exit_cb exit_cb; /* Called after the process exits. */
+  const char* file;   /* Path to program to execute. */
+  /*
+   * Command line arguments. args[0] should be the path to the program. On
+   * Windows this uses CreateProcess which concatenates the arguments into a
+   * string this can cause some strange errors. See the note at
+   * windows_verbatim_arguments.
+   */
+  char** args;
+  /*
+   * This will be set as the environ variable in the subprocess. If this is
+   * NULL then the parents environ will be used.
+   */
+  char** env;
+  /*
+   * If non-null this represents a directory the subprocess should execute
+   * in. Stands for current working directory.
+   */
+  const char* cwd;
+  /*
+   * Various flags that control how uv_spawn() behaves. See the definition of
+   * `enum uv_process_flags` below.
+   */
+  unsigned int flags;
+  /*
+   * The `stdio` field points to an array of uv_stdio_container_t structs that
+   * describe the file descriptors that will be made available to the child
+   * process. The convention is that stdio[0] points to stdin, fd 1 is used for
+   * stdout, and fd 2 is stderr.
+   *
+   * Note that on windows file descriptors greater than 2 are available to the
+   * child process only if the child processes uses the MSVCRT runtime.
+   */
+  int stdio_count;
+  uv_stdio_container_t* stdio;
+  /*
+   * Libuv can change the child process' user/group id. This happens only when
+   * the appropriate bits are set in the flags fields. This is not supported on
+   * windows; uv_spawn() will fail and set the error to UV_ENOTSUP.
+   */
+  uv_uid_t uid;
+  uv_gid_t gid;
+} uv_process_options_t;
+
+/*
+ * These are the flags that can be used for the uv_process_options.flags field.
+ */
+enum uv_process_flags {
+  /*
+   * Set the child process' user id. The user id is supplied in the `uid` field
+   * of the options struct. This does not work on windows; setting this flag
+   * will cause uv_spawn() to fail.
+   */
+  UV_PROCESS_SETUID = (1 << 0),
+  /*
+   * Set the child process' group id. The user id is supplied in the `gid`
+   * field of the options struct. This does not work on windows; setting this
+   * flag will cause uv_spawn() to fail.
+   */
+  UV_PROCESS_SETGID = (1 << 1),
+  /*
+   * Do not wrap any arguments in quotes, or perform any other escaping, when
+   * converting the argument list into a command line string. This option is
+   * only meaningful on Windows systems. On Unix it is silently ignored.
+   */
+  UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2),
+  /*
+   * Spawn the child process in a detached state - this will make it a process
+   * group leader, and will effectively enable the child to keep running after
+   * the parent exits.  Note that the child process will still keep the
+   * parent's event loop alive unless the parent process calls uv_unref() on
+   * the child's process handle.
+   */
+  UV_PROCESS_DETACHED = (1 << 3),
+  /*
+   * Hide the subprocess console window that would normally be created. This
+   * option is only meaningful on Windows systems. On Unix it is silently
+   * ignored.
+   */
+  UV_PROCESS_WINDOWS_HIDE = (1 << 4)
+};
+
+/*
+ * uv_process_t is a subclass of uv_handle_t.
+ */
+struct uv_process_s {
+  UV_HANDLE_FIELDS
+  uv_exit_cb exit_cb;
+  int pid;
+  UV_PROCESS_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_spawn(uv_loop_t* loop,
+                       uv_process_t* handle,
+                       const uv_process_options_t* options);
+UV_EXTERN int uv_process_kill(uv_process_t*, int signum);
+UV_EXTERN int uv_kill(int pid, int signum);
+
+
+/*
+ * uv_work_t is a subclass of uv_req_t.
+ */
+struct uv_work_s {
+  UV_REQ_FIELDS
+  uv_loop_t* loop;
+  uv_work_cb work_cb;
+  uv_after_work_cb after_work_cb;
+  UV_WORK_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_queue_work(uv_loop_t* loop,
+                            uv_work_t* req,
+                            uv_work_cb work_cb,
+                            uv_after_work_cb after_work_cb);
+
+UV_EXTERN int uv_cancel(uv_req_t* req);
+
+
+struct uv_cpu_info_s {
+  char* model;
+  int speed;
+  struct uv_cpu_times_s {
+    uint64_t user;
+    uint64_t nice;
+    uint64_t sys;
+    uint64_t idle;
+    uint64_t irq;
+  } cpu_times;
+};
+
+struct uv_interface_address_s {
+  char* name;
+  char phys_addr[6];
+  int is_internal;
+  union {
+    struct sockaddr_in address4;
+    struct sockaddr_in6 address6;
+  } address;
+  union {
+    struct sockaddr_in netmask4;
+    struct sockaddr_in6 netmask6;
+  } netmask;
+};
+
+struct uv_passwd_s {
+  char* username;
+  long uid;
+  long gid;
+  char* shell;
+  char* homedir;
+};
+
+typedef enum {
+  UV_DIRENT_UNKNOWN,
+  UV_DIRENT_FILE,
+  UV_DIRENT_DIR,
+  UV_DIRENT_LINK,
+  UV_DIRENT_FIFO,
+  UV_DIRENT_SOCKET,
+  UV_DIRENT_CHAR,
+  UV_DIRENT_BLOCK
+} uv_dirent_type_t;
+
+struct uv_dirent_s {
+  const char* name;
+  uv_dirent_type_t type;
+};
+
+UV_EXTERN char** uv_setup_args(int argc, char** argv);
+UV_EXTERN int uv_get_process_title(char* buffer, size_t size);
+UV_EXTERN int uv_set_process_title(const char* title);
+UV_EXTERN int uv_resident_set_memory(size_t* rss);
+UV_EXTERN int uv_uptime(double* uptime);
+
+typedef struct {
+  long tv_sec;
+  long tv_usec;
+} uv_timeval_t;
+
+typedef struct {
+   uv_timeval_t ru_utime; /* user CPU time used */
+   uv_timeval_t ru_stime; /* system CPU time used */
+   uint64_t ru_maxrss;    /* maximum resident set size */
+   uint64_t ru_ixrss;     /* integral shared memory size */
+   uint64_t ru_idrss;     /* integral unshared data size */
+   uint64_t ru_isrss;     /* integral unshared stack size */
+   uint64_t ru_minflt;    /* page reclaims (soft page faults) */
+   uint64_t ru_majflt;    /* page faults (hard page faults) */
+   uint64_t ru_nswap;     /* swaps */
+   uint64_t ru_inblock;   /* block input operations */
+   uint64_t ru_oublock;   /* block output operations */
+   uint64_t ru_msgsnd;    /* IPC messages sent */
+   uint64_t ru_msgrcv;    /* IPC messages received */
+   uint64_t ru_nsignals;  /* signals received */
+   uint64_t ru_nvcsw;     /* voluntary context switches */
+   uint64_t ru_nivcsw;    /* involuntary context switches */
+} uv_rusage_t;
+
+UV_EXTERN int uv_getrusage(uv_rusage_t* rusage);
+
+UV_EXTERN int uv_os_homedir(char* buffer, size_t* size);
+UV_EXTERN int uv_os_tmpdir(char* buffer, size_t* size);
+UV_EXTERN int uv_os_get_passwd(uv_passwd_t* pwd);
+UV_EXTERN void uv_os_free_passwd(uv_passwd_t* pwd);
+
+UV_EXTERN int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count);
+UV_EXTERN void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count);
+
+UV_EXTERN int uv_interface_addresses(uv_interface_address_t** addresses,
+                                     int* count);
+UV_EXTERN void uv_free_interface_addresses(uv_interface_address_t* addresses,
+                                           int count);
+
+
+typedef enum {
+  UV_FS_UNKNOWN = -1,
+  UV_FS_CUSTOM,
+  UV_FS_OPEN,
+  UV_FS_CLOSE,
+  UV_FS_READ,
+  UV_FS_WRITE,
+  UV_FS_SENDFILE,
+  UV_FS_STAT,
+  UV_FS_LSTAT,
+  UV_FS_FSTAT,
+  UV_FS_FTRUNCATE,
+  UV_FS_UTIME,
+  UV_FS_FUTIME,
+  UV_FS_ACCESS,
+  UV_FS_CHMOD,
+  UV_FS_FCHMOD,
+  UV_FS_FSYNC,
+  UV_FS_FDATASYNC,
+  UV_FS_UNLINK,
+  UV_FS_RMDIR,
+  UV_FS_MKDIR,
+  UV_FS_MKDTEMP,
+  UV_FS_RENAME,
+  UV_FS_SCANDIR,
+  UV_FS_LINK,
+  UV_FS_SYMLINK,
+  UV_FS_READLINK,
+  UV_FS_CHOWN,
+  UV_FS_FCHOWN,
+  UV_FS_REALPATH
+} uv_fs_type;
+
+/* uv_fs_t is a subclass of uv_req_t. */
+struct uv_fs_s {
+  UV_REQ_FIELDS
+  uv_fs_type fs_type;
+  uv_loop_t* loop;
+  uv_fs_cb cb;
+  ssize_t result;
+  void* ptr;
+  const char* path;
+  uv_stat_t statbuf;  /* Stores the result of uv_fs_stat() and uv_fs_fstat(). */
+  UV_FS_PRIVATE_FIELDS
+};
+
+UV_EXTERN void uv_fs_req_cleanup(uv_fs_t* req);
+UV_EXTERN int uv_fs_close(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          uv_file file,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_open(uv_loop_t* loop,
+                         uv_fs_t* req,
+                         const char* path,
+                         int flags,
+                         int mode,
+                         uv_fs_cb cb);
+UV_EXTERN int uv_fs_read(uv_loop_t* loop,
+                         uv_fs_t* req,
+                         uv_file file,
+                         const uv_buf_t bufs[],
+                         unsigned int nbufs,
+                         int64_t offset,
+                         uv_fs_cb cb);
+UV_EXTERN int uv_fs_unlink(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           const char* path,
+                           uv_fs_cb cb);
+UV_EXTERN int uv_fs_write(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          uv_file file,
+                          const uv_buf_t bufs[],
+                          unsigned int nbufs,
+                          int64_t offset,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          int mode,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_mkdtemp(uv_loop_t* loop,
+                            uv_fs_t* req,
+                            const char* tpl,
+                            uv_fs_cb cb);
+UV_EXTERN int uv_fs_rmdir(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_scandir(uv_loop_t* loop,
+                            uv_fs_t* req,
+                            const char* path,
+                            int flags,
+                            uv_fs_cb cb);
+UV_EXTERN int uv_fs_scandir_next(uv_fs_t* req,
+                                 uv_dirent_t* ent);
+UV_EXTERN int uv_fs_stat(uv_loop_t* loop,
+                         uv_fs_t* req,
+                         const char* path,
+                         uv_fs_cb cb);
+UV_EXTERN int uv_fs_fstat(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          uv_file file,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_rename(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           const char* path,
+                           const char* new_path,
+                           uv_fs_cb cb);
+UV_EXTERN int uv_fs_fsync(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          uv_file file,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_fdatasync(uv_loop_t* loop,
+                              uv_fs_t* req,
+                              uv_file file,
+                              uv_fs_cb cb);
+UV_EXTERN int uv_fs_ftruncate(uv_loop_t* loop,
+                              uv_fs_t* req,
+                              uv_file file,
+                              int64_t offset,
+                              uv_fs_cb cb);
+UV_EXTERN int uv_fs_sendfile(uv_loop_t* loop,
+                             uv_fs_t* req,
+                             uv_file out_fd,
+                             uv_file in_fd,
+                             int64_t in_offset,
+                             size_t length,
+                             uv_fs_cb cb);
+UV_EXTERN int uv_fs_access(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           const char* path,
+                           int mode,
+                           uv_fs_cb cb);
+UV_EXTERN int uv_fs_chmod(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          int mode,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_utime(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          double atime,
+                          double mtime,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_futime(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           uv_file file,
+                           double atime,
+                           double mtime,
+                           uv_fs_cb cb);
+UV_EXTERN int uv_fs_lstat(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_link(uv_loop_t* loop,
+                         uv_fs_t* req,
+                         const char* path,
+                         const char* new_path,
+                         uv_fs_cb cb);
+
+/*
+ * This flag can be used with uv_fs_symlink() on Windows to specify whether
+ * path argument points to a directory.
+ */
+#define UV_FS_SYMLINK_DIR          0x0001
+
+/*
+ * This flag can be used with uv_fs_symlink() on Windows to specify whether
+ * the symlink is to be created using junction points.
+ */
+#define UV_FS_SYMLINK_JUNCTION     0x0002
+
+UV_EXTERN int uv_fs_symlink(uv_loop_t* loop,
+                            uv_fs_t* req,
+                            const char* path,
+                            const char* new_path,
+                            int flags,
+                            uv_fs_cb cb);
+UV_EXTERN int uv_fs_readlink(uv_loop_t* loop,
+                             uv_fs_t* req,
+                             const char* path,
+                             uv_fs_cb cb);
+UV_EXTERN int uv_fs_realpath(uv_loop_t* loop,
+                             uv_fs_t* req,
+                             const char* path,
+                             uv_fs_cb cb);
+UV_EXTERN int uv_fs_fchmod(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           uv_file file,
+                           int mode,
+                           uv_fs_cb cb);
+UV_EXTERN int uv_fs_chown(uv_loop_t* loop,
+                          uv_fs_t* req,
+                          const char* path,
+                          uv_uid_t uid,
+                          uv_gid_t gid,
+                          uv_fs_cb cb);
+UV_EXTERN int uv_fs_fchown(uv_loop_t* loop,
+                           uv_fs_t* req,
+                           uv_file file,
+                           uv_uid_t uid,
+                           uv_gid_t gid,
+                           uv_fs_cb cb);
+
+
+enum uv_fs_event {
+  UV_RENAME = 1,
+  UV_CHANGE = 2
+};
+
+
+struct uv_fs_event_s {
+  UV_HANDLE_FIELDS
+  /* private */
+  char* path;
+  UV_FS_EVENT_PRIVATE_FIELDS
+};
+
+
+/*
+ * uv_fs_stat() based polling file watcher.
+ */
+struct uv_fs_poll_s {
+  UV_HANDLE_FIELDS
+  /* Private, don't touch. */
+  void* poll_ctx;
+};
+
+UV_EXTERN int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle);
+UV_EXTERN int uv_fs_poll_start(uv_fs_poll_t* handle,
+                               uv_fs_poll_cb poll_cb,
+                               const char* path,
+                               unsigned int interval);
+UV_EXTERN int uv_fs_poll_stop(uv_fs_poll_t* handle);
+UV_EXTERN int uv_fs_poll_getpath(uv_fs_poll_t* handle,
+                                 char* buffer,
+                                 size_t* size);
+
+
+struct uv_signal_s {
+  UV_HANDLE_FIELDS
+  uv_signal_cb signal_cb;
+  int signum;
+  UV_SIGNAL_PRIVATE_FIELDS
+};
+
+UV_EXTERN int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle);
+UV_EXTERN int uv_signal_start(uv_signal_t* handle,
+                              uv_signal_cb signal_cb,
+                              int signum);
+UV_EXTERN int uv_signal_stop(uv_signal_t* handle);
+
+UV_EXTERN void uv_loadavg(double avg[3]);
+
+
+/*
+ * Flags to be passed to uv_fs_event_start().
+ */
+enum uv_fs_event_flags {
+  /*
+   * By default, if the fs event watcher is given a directory name, we will
+   * watch for all events in that directory. This flags overrides this behavior
+   * and makes fs_event report only changes to the directory entry itself. This
+   * flag does not affect individual files watched.
+   * This flag is currently not implemented yet on any backend.
+   */
+  UV_FS_EVENT_WATCH_ENTRY = 1,
+
+  /*
+   * By default uv_fs_event will try to use a kernel interface such as inotify
+   * or kqueue to detect events. This may not work on remote filesystems such
+   * as NFS mounts. This flag makes fs_event fall back to calling stat() on a
+   * regular interval.
+   * This flag is currently not implemented yet on any backend.
+   */
+  UV_FS_EVENT_STAT = 2,
+
+  /*
+   * By default, event watcher, when watching directory, is not registering
+   * (is ignoring) changes in it's subdirectories.
+   * This flag will override this behaviour on platforms that support it.
+   */
+  UV_FS_EVENT_RECURSIVE = 4
+};
+
+
+UV_EXTERN int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle);
+UV_EXTERN int uv_fs_event_start(uv_fs_event_t* handle,
+                                uv_fs_event_cb cb,
+                                const char* path,
+                                unsigned int flags);
+UV_EXTERN int uv_fs_event_stop(uv_fs_event_t* handle);
+UV_EXTERN int uv_fs_event_getpath(uv_fs_event_t* handle,
+                                  char* buffer,
+                                  size_t* size);
+
+UV_EXTERN int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr);
+UV_EXTERN int uv_ip6_addr(const char* ip, int port, struct sockaddr_in6* addr);
+
+UV_EXTERN int uv_ip4_name(const struct sockaddr_in* src, char* dst, size_t size);
+UV_EXTERN int uv_ip6_name(const struct sockaddr_in6* src, char* dst, size_t size);
+
+UV_EXTERN int uv_inet_ntop(int af, const void* src, char* dst, size_t size);
+UV_EXTERN int uv_inet_pton(int af, const char* src, void* dst);
+
+UV_EXTERN int uv_exepath(char* buffer, size_t* size);
+
+UV_EXTERN int uv_cwd(char* buffer, size_t* size);
+
+UV_EXTERN int uv_chdir(const char* dir);
+
+UV_EXTERN uint64_t uv_get_free_memory(void);
+UV_EXTERN uint64_t uv_get_total_memory(void);
+
+UV_EXTERN uint64_t uv_hrtime(void);
+
+UV_EXTERN void uv_disable_stdio_inheritance(void);
+
+UV_EXTERN int uv_dlopen(const char* filename, uv_lib_t* lib);
+UV_EXTERN void uv_dlclose(uv_lib_t* lib);
+UV_EXTERN int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr);
+UV_EXTERN const char* uv_dlerror(const uv_lib_t* lib);
+
+UV_EXTERN int uv_mutex_init(uv_mutex_t* handle);
+UV_EXTERN void uv_mutex_destroy(uv_mutex_t* handle);
+UV_EXTERN void uv_mutex_lock(uv_mutex_t* handle);
+UV_EXTERN int uv_mutex_trylock(uv_mutex_t* handle);
+UV_EXTERN void uv_mutex_unlock(uv_mutex_t* handle);
+
+UV_EXTERN int uv_rwlock_init(uv_rwlock_t* rwlock);
+UV_EXTERN void uv_rwlock_destroy(uv_rwlock_t* rwlock);
+UV_EXTERN void uv_rwlock_rdlock(uv_rwlock_t* rwlock);
+UV_EXTERN int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock);
+UV_EXTERN void uv_rwlock_rdunlock(uv_rwlock_t* rwlock);
+UV_EXTERN void uv_rwlock_wrlock(uv_rwlock_t* rwlock);
+UV_EXTERN int uv_rwlock_trywrlock(uv_rwlock_t* rwlock);
+UV_EXTERN void uv_rwlock_wrunlock(uv_rwlock_t* rwlock);
+
+UV_EXTERN int uv_sem_init(uv_sem_t* sem, unsigned int value);
+UV_EXTERN void uv_sem_destroy(uv_sem_t* sem);
+UV_EXTERN void uv_sem_post(uv_sem_t* sem);
+UV_EXTERN void uv_sem_wait(uv_sem_t* sem);
+UV_EXTERN int uv_sem_trywait(uv_sem_t* sem);
+
+UV_EXTERN int uv_cond_init(uv_cond_t* cond);
+UV_EXTERN void uv_cond_destroy(uv_cond_t* cond);
+UV_EXTERN void uv_cond_signal(uv_cond_t* cond);
+UV_EXTERN void uv_cond_broadcast(uv_cond_t* cond);
+
+UV_EXTERN int uv_barrier_init(uv_barrier_t* barrier, unsigned int count);
+UV_EXTERN void uv_barrier_destroy(uv_barrier_t* barrier);
+UV_EXTERN int uv_barrier_wait(uv_barrier_t* barrier);
+
+UV_EXTERN void uv_cond_wait(uv_cond_t* cond, uv_mutex_t* mutex);
+UV_EXTERN int uv_cond_timedwait(uv_cond_t* cond,
+                                uv_mutex_t* mutex,
+                                uint64_t timeout);
+
+UV_EXTERN void uv_once(uv_once_t* guard, void (*callback)(void));
+
+UV_EXTERN int uv_key_create(uv_key_t* key);
+UV_EXTERN void uv_key_delete(uv_key_t* key);
+UV_EXTERN void* uv_key_get(uv_key_t* key);
+UV_EXTERN void uv_key_set(uv_key_t* key, void* value);
+
+typedef void (*uv_thread_cb)(void* arg);
+
+UV_EXTERN int uv_thread_create(uv_thread_t* tid, uv_thread_cb entry, void* arg);
+UV_EXTERN uv_thread_t uv_thread_self(void);
+UV_EXTERN int uv_thread_join(uv_thread_t *tid);
+UV_EXTERN int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2);
+
+/* The presence of these unions force similar struct layout. */
+#define XX(_, name) uv_ ## name ## _t name;
+union uv_any_handle {
+  UV_HANDLE_TYPE_MAP(XX)
+};
+
+union uv_any_req {
+  UV_REQ_TYPE_MAP(XX)
+};
+#undef XX
+
+
+struct uv_loop_s {
+  /* User data - use this for whatever. */
+  void* data;
+  /* Loop reference counting. */
+  unsigned int active_handles;
+  void* handle_queue[2];
+  void* active_reqs[2];
+  /* Internal flag to signal loop stop. */
+  unsigned int stop_flag;
+  UV_LOOP_PRIVATE_FIELDS
+};
+
+
+/* Don't export the private CPP symbols. */
+#undef UV_HANDLE_TYPE_PRIVATE
+#undef UV_REQ_TYPE_PRIVATE
+#undef UV_REQ_PRIVATE_FIELDS
+#undef UV_STREAM_PRIVATE_FIELDS
+#undef UV_TCP_PRIVATE_FIELDS
+#undef UV_PREPARE_PRIVATE_FIELDS
+#undef UV_CHECK_PRIVATE_FIELDS
+#undef UV_IDLE_PRIVATE_FIELDS
+#undef UV_ASYNC_PRIVATE_FIELDS
+#undef UV_TIMER_PRIVATE_FIELDS
+#undef UV_GETADDRINFO_PRIVATE_FIELDS
+#undef UV_GETNAMEINFO_PRIVATE_FIELDS
+#undef UV_FS_REQ_PRIVATE_FIELDS
+#undef UV_WORK_PRIVATE_FIELDS
+#undef UV_FS_EVENT_PRIVATE_FIELDS
+#undef UV_SIGNAL_PRIVATE_FIELDS
+#undef UV_LOOP_PRIVATE_FIELDS
+#undef UV_LOOP_PRIVATE_PLATFORM_FIELDS
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* UV_H */
diff --git a/Utilities/cmlibuv/src/fs-poll.c b/Utilities/cmlibuv/src/fs-poll.c
new file mode 100644
index 0000000..ee73d5a
--- /dev/null
+++ b/Utilities/cmlibuv/src/fs-poll.c
@@ -0,0 +1,256 @@
+/* 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 <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+struct poll_ctx {
+  uv_fs_poll_t* parent_handle; /* NULL if parent has been stopped or closed */
+  int busy_polling;
+  unsigned int interval;
+  uint64_t start_time;
+  uv_loop_t* loop;
+  uv_fs_poll_cb poll_cb;
+  uv_timer_t timer_handle;
+  uv_fs_t fs_req; /* TODO(bnoordhuis) mark fs_req internal */
+  uv_stat_t statbuf;
+  char path[1]; /* variable length */
+};
+
+static int statbuf_eq(const uv_stat_t* a, const uv_stat_t* b);
+static void poll_cb(uv_fs_t* req);
+static void timer_cb(uv_timer_t* timer);
+static void timer_close_cb(uv_handle_t* handle);
+
+static uv_stat_t zero_statbuf;
+
+
+int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_POLL);
+  return 0;
+}
+
+
+int uv_fs_poll_start(uv_fs_poll_t* handle,
+                     uv_fs_poll_cb cb,
+                     const char* path,
+                     unsigned int interval) {
+  struct poll_ctx* ctx;
+  uv_loop_t* loop;
+  size_t len;
+  int err;
+
+  if (uv__is_active(handle))
+    return 0;
+
+  loop = handle->loop;
+  len = strlen(path);
+  ctx = uv__calloc(1, sizeof(*ctx) + len);
+
+  if (ctx == NULL)
+    return UV_ENOMEM;
+
+  ctx->loop = loop;
+  ctx->poll_cb = cb;
+  ctx->interval = interval ? interval : 1;
+  ctx->start_time = uv_now(loop);
+  ctx->parent_handle = handle;
+  memcpy(ctx->path, path, len + 1);
+
+  err = uv_timer_init(loop, &ctx->timer_handle);
+  if (err < 0)
+    goto error;
+
+  ctx->timer_handle.flags |= UV__HANDLE_INTERNAL;
+  uv__handle_unref(&ctx->timer_handle);
+
+  err = uv_fs_stat(loop, &ctx->fs_req, ctx->path, poll_cb);
+  if (err < 0)
+    goto error;
+
+  handle->poll_ctx = ctx;
+  uv__handle_start(handle);
+
+  return 0;
+
+error:
+  uv__free(ctx);
+  return err;
+}
+
+
+int uv_fs_poll_stop(uv_fs_poll_t* handle) {
+  struct poll_ctx* ctx;
+
+  if (!uv__is_active(handle))
+    return 0;
+
+  ctx = handle->poll_ctx;
+  assert(ctx != NULL);
+  assert(ctx->parent_handle != NULL);
+  ctx->parent_handle = NULL;
+  handle->poll_ctx = NULL;
+
+  /* Close the timer if it's active. If it's inactive, there's a stat request
+   * in progress and poll_cb will take care of the cleanup.
+   */
+  if (uv__is_active(&ctx->timer_handle))
+    uv_close((uv_handle_t*)&ctx->timer_handle, timer_close_cb);
+
+  uv__handle_stop(handle);
+
+  return 0;
+}
+
+
+int uv_fs_poll_getpath(uv_fs_poll_t* handle, char* buffer, size_t* size) {
+  struct poll_ctx* ctx;
+  size_t required_len;
+
+  if (!uv__is_active(handle)) {
+    *size = 0;
+    return UV_EINVAL;
+  }
+
+  ctx = handle->poll_ctx;
+  assert(ctx != NULL);
+
+  required_len = strlen(ctx->path);
+  if (required_len >= *size) {
+    *size = required_len + 1;
+    return UV_ENOBUFS;
+  }
+
+  memcpy(buffer, ctx->path, required_len);
+  *size = required_len;
+  buffer[required_len] = '\0';
+
+  return 0;
+}
+
+
+void uv__fs_poll_close(uv_fs_poll_t* handle) {
+  uv_fs_poll_stop(handle);
+}
+
+
+static void timer_cb(uv_timer_t* timer) {
+  struct poll_ctx* ctx;
+
+  ctx = container_of(timer, struct poll_ctx, timer_handle);
+  assert(ctx->parent_handle != NULL);
+  assert(ctx->parent_handle->poll_ctx == ctx);
+  ctx->start_time = uv_now(ctx->loop);
+
+  if (uv_fs_stat(ctx->loop, &ctx->fs_req, ctx->path, poll_cb))
+    abort();
+}
+
+
+static void poll_cb(uv_fs_t* req) {
+  uv_stat_t* statbuf;
+  struct poll_ctx* ctx;
+  uint64_t interval;
+
+  ctx = container_of(req, struct poll_ctx, fs_req);
+
+  if (ctx->parent_handle == NULL) { /* handle has been stopped or closed */
+    uv_close((uv_handle_t*)&ctx->timer_handle, timer_close_cb);
+    uv_fs_req_cleanup(req);
+    return;
+  }
+
+  if (req->result != 0) {
+    if (ctx->busy_polling != req->result) {
+      ctx->poll_cb(ctx->parent_handle,
+                   req->result,
+                   &ctx->statbuf,
+                   &zero_statbuf);
+      ctx->busy_polling = req->result;
+    }
+    goto out;
+  }
+
+  statbuf = &req->statbuf;
+
+  if (ctx->busy_polling != 0)
+    if (ctx->busy_polling < 0 || !statbuf_eq(&ctx->statbuf, statbuf))
+      ctx->poll_cb(ctx->parent_handle, 0, &ctx->statbuf, statbuf);
+
+  ctx->statbuf = *statbuf;
+  ctx->busy_polling = 1;
+
+out:
+  uv_fs_req_cleanup(req);
+
+  if (ctx->parent_handle == NULL) { /* handle has been stopped by callback */
+    uv_close((uv_handle_t*)&ctx->timer_handle, timer_close_cb);
+    return;
+  }
+
+  /* Reschedule timer, subtract the delay from doing the stat(). */
+  interval = ctx->interval;
+  interval -= (uv_now(ctx->loop) - ctx->start_time) % interval;
+
+  if (uv_timer_start(&ctx->timer_handle, timer_cb, interval, 0))
+    abort();
+}
+
+
+static void timer_close_cb(uv_handle_t* handle) {
+  uv__free(container_of(handle, struct poll_ctx, timer_handle));
+}
+
+
+static int statbuf_eq(const uv_stat_t* a, const uv_stat_t* b) {
+  return a->st_ctim.tv_nsec == b->st_ctim.tv_nsec
+      && a->st_mtim.tv_nsec == b->st_mtim.tv_nsec
+      && a->st_birthtim.tv_nsec == b->st_birthtim.tv_nsec
+      && a->st_ctim.tv_sec == b->st_ctim.tv_sec
+      && a->st_mtim.tv_sec == b->st_mtim.tv_sec
+      && a->st_birthtim.tv_sec == b->st_birthtim.tv_sec
+      && a->st_size == b->st_size
+      && a->st_mode == b->st_mode
+      && a->st_uid == b->st_uid
+      && a->st_gid == b->st_gid
+      && a->st_ino == b->st_ino
+      && a->st_dev == b->st_dev
+      && a->st_flags == b->st_flags
+      && a->st_gen == b->st_gen;
+}
+
+
+#if defined(_WIN32)
+
+#include "win/internal.h"
+#include "win/handle-inl.h"
+
+void uv__fs_poll_endgame(uv_loop_t* loop, uv_fs_poll_t* handle) {
+  assert(handle->flags & UV__HANDLE_CLOSING);
+  assert(!(handle->flags & UV_HANDLE_CLOSED));
+  uv__handle_close(handle);
+}
+
+#endif /* _WIN32 */
diff --git a/Utilities/cmlibuv/src/heap-inl.h b/Utilities/cmlibuv/src/heap-inl.h
new file mode 100644
index 0000000..1e2ed60
--- /dev/null
+++ b/Utilities/cmlibuv/src/heap-inl.h
@@ -0,0 +1,245 @@
+/* Copyright (c) 2013, Ben Noordhuis <info at 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_HEAP_H_
+#define UV_SRC_HEAP_H_
+
+#include <stddef.h>  /* NULL */
+
+#if defined(__GNUC__)
+# define HEAP_EXPORT(declaration) __attribute__((unused)) static declaration
+#else
+# define HEAP_EXPORT(declaration) static declaration
+#endif
+
+struct heap_node {
+  struct heap_node* left;
+  struct heap_node* right;
+  struct heap_node* parent;
+};
+
+/* A binary min heap.  The usual properties hold: the root is the lowest
+ * element in the set, the height of the tree is at most log2(nodes) and
+ * it's always a complete binary tree.
+ *
+ * The heap function try hard to detect corrupted tree nodes at the cost
+ * of a minor reduction in performance.  Compile with -DNDEBUG to disable.
+ */
+struct heap {
+  struct heap_node* min;
+  unsigned int nelts;
+};
+
+/* Return non-zero if a < b. */
+typedef int (*heap_compare_fn)(const struct heap_node* a,
+                               const struct heap_node* b);
+
+/* Public functions. */
+HEAP_EXPORT(void heap_init(struct heap* heap));
+HEAP_EXPORT(struct heap_node* heap_min(const struct heap* heap));
+HEAP_EXPORT(void heap_insert(struct heap* heap,
+                             struct heap_node* newnode,
+                             heap_compare_fn less_than));
+HEAP_EXPORT(void heap_remove(struct heap* heap,
+                             struct heap_node* node,
+                             heap_compare_fn less_than));
+HEAP_EXPORT(void heap_dequeue(struct heap* heap, heap_compare_fn less_than));
+
+/* Implementation follows. */
+
+HEAP_EXPORT(void heap_init(struct heap* heap)) {
+  heap->min = NULL;
+  heap->nelts = 0;
+}
+
+HEAP_EXPORT(struct heap_node* heap_min(const struct heap* heap)) {
+  return heap->min;
+}
+
+/* Swap parent with child. Child moves closer to the root, parent moves away. */
+static void heap_node_swap(struct heap* heap,
+                           struct heap_node* parent,
+                           struct heap_node* child) {
+  struct heap_node* sibling;
+  struct heap_node t;
+
+  t = *parent;
+  *parent = *child;
+  *child = t;
+
+  parent->parent = child;
+  if (child->left == child) {
+    child->left = parent;
+    sibling = child->right;
+  } else {
+    child->right = parent;
+    sibling = child->left;
+  }
+  if (sibling != NULL)
+    sibling->parent = child;
+
+  if (parent->left != NULL)
+    parent->left->parent = parent;
+  if (parent->right != NULL)
+    parent->right->parent = parent;
+
+  if (child->parent == NULL)
+    heap->min = child;
+  else if (child->parent->left == parent)
+    child->parent->left = child;
+  else
+    child->parent->right = child;
+}
+
+HEAP_EXPORT(void heap_insert(struct heap* heap,
+                             struct heap_node* newnode,
+                             heap_compare_fn less_than)) {
+  struct heap_node** parent;
+  struct heap_node** child;
+  unsigned int path;
+  unsigned int n;
+  unsigned int k;
+
+  newnode->left = NULL;
+  newnode->right = NULL;
+  newnode->parent = NULL;
+
+  /* Calculate the path from the root to the insertion point.  This is a min
+   * heap so we always insert at the left-most free node of the bottom row.
+   */
+  path = 0;
+  for (k = 0, n = 1 + heap->nelts; n >= 2; k += 1, n /= 2)
+    path = (path << 1) | (n & 1);
+
+  /* Now traverse the heap using the path we calculated in the previous step. */
+  parent = child = &heap->min;
+  while (k > 0) {
+    parent = child;
+    if (path & 1)
+      child = &(*child)->right;
+    else
+      child = &(*child)->left;
+    path >>= 1;
+    k -= 1;
+  }
+
+  /* Insert the new node. */
+  newnode->parent = *parent;
+  *child = newnode;
+  heap->nelts += 1;
+
+  /* Walk up the tree and check at each node if the heap property holds.
+   * It's a min heap so parent < child must be true.
+   */
+  while (newnode->parent != NULL && less_than(newnode, newnode->parent))
+    heap_node_swap(heap, newnode->parent, newnode);
+}
+
+HEAP_EXPORT(void heap_remove(struct heap* heap,
+                             struct heap_node* node,
+                             heap_compare_fn less_than)) {
+  struct heap_node* smallest;
+  struct heap_node** max;
+  struct heap_node* child;
+  unsigned int path;
+  unsigned int k;
+  unsigned int n;
+
+  if (heap->nelts == 0)
+    return;
+
+  /* Calculate the path from the min (the root) to the max, the left-most node
+   * of the bottom row.
+   */
+  path = 0;
+  for (k = 0, n = heap->nelts; n >= 2; k += 1, n /= 2)
+    path = (path << 1) | (n & 1);
+
+  /* Now traverse the heap using the path we calculated in the previous step. */
+  max = &heap->min;
+  while (k > 0) {
+    if (path & 1)
+      max = &(*max)->right;
+    else
+      max = &(*max)->left;
+    path >>= 1;
+    k -= 1;
+  }
+
+  heap->nelts -= 1;
+
+  /* Unlink the max node. */
+  child = *max;
+  *max = NULL;
+
+  if (child == node) {
+    /* We're removing either the max or the last node in the tree. */
+    if (child == heap->min) {
+      heap->min = NULL;
+    }
+    return;
+  }
+
+  /* Replace the to be deleted node with the max node. */
+  child->left = node->left;
+  child->right = node->right;
+  child->parent = node->parent;
+
+  if (child->left != NULL) {
+    child->left->parent = child;
+  }
+
+  if (child->right != NULL) {
+    child->right->parent = child;
+  }
+
+  if (node->parent == NULL) {
+    heap->min = child;
+  } else if (node->parent->left == node) {
+    node->parent->left = child;
+  } else {
+    node->parent->right = child;
+  }
+
+  /* Walk down the subtree and check at each node if the heap property holds.
+   * It's a min heap so parent < child must be true.  If the parent is bigger,
+   * swap it with the smallest child.
+   */
+  for (;;) {
+    smallest = child;
+    if (child->left != NULL && less_than(child->left, smallest))
+      smallest = child->left;
+    if (child->right != NULL && less_than(child->right, smallest))
+      smallest = child->right;
+    if (smallest == child)
+      break;
+    heap_node_swap(heap, child, smallest);
+  }
+
+  /* Walk up the subtree and check that each parent is less than the node
+   * this is required, because `max` node is not guaranteed to be the
+   * actual maximum in tree
+   */
+  while (child->parent != NULL && less_than(child, child->parent))
+    heap_node_swap(heap, child->parent, child);
+}
+
+HEAP_EXPORT(void heap_dequeue(struct heap* heap, heap_compare_fn less_than)) {
+  heap_remove(heap, heap->min, less_than);
+}
+
+#undef HEAP_EXPORT
+
+#endif  /* UV_SRC_HEAP_H_ */
diff --git a/Utilities/cmlibuv/src/inet.c b/Utilities/cmlibuv/src/inet.c
new file mode 100644
index 0000000..7c75e43
--- /dev/null
+++ b/Utilities/cmlibuv/src/inet.c
@@ -0,0 +1,309 @@
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include "uv.h"
+#include "uv-common.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#define UV__INET_ADDRSTRLEN         16
+#define UV__INET6_ADDRSTRLEN        46
+
+
+static int inet_ntop4(const unsigned char *src, char *dst, size_t size);
+static int inet_ntop6(const unsigned char *src, char *dst, size_t size);
+static int inet_pton4(const char *src, unsigned char *dst);
+static int inet_pton6(const char *src, unsigned char *dst);
+
+
+int uv_inet_ntop(int af, const void* src, char* dst, size_t size) {
+  switch (af) {
+  case AF_INET:
+    return (inet_ntop4(src, dst, size));
+  case AF_INET6:
+    return (inet_ntop6(src, dst, size));
+  default:
+    return UV_EAFNOSUPPORT;
+  }
+  /* NOTREACHED */
+}
+
+
+static int inet_ntop4(const unsigned char *src, char *dst, size_t size) {
+  static const char fmt[] = "%u.%u.%u.%u";
+  char tmp[UV__INET_ADDRSTRLEN];
+  int l;
+
+  l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
+  if (l <= 0 || (size_t) l >= size) {
+    return UV_ENOSPC;
+  }
+  strncpy(dst, tmp, size);
+  dst[size - 1] = '\0';
+  return 0;
+}
+
+
+static int inet_ntop6(const unsigned char *src, char *dst, size_t size) {
+  /*
+   * Note that int32_t and int16_t need only be "at least" large enough
+   * to contain a value of the specified size.  On some systems, like
+   * Crays, there is no such thing as an integer variable with 16 bits.
+   * Keep this in mind if you think this function should have been coded
+   * to use pointer overlays.  All the world's not a VAX.
+   */
+  char tmp[UV__INET6_ADDRSTRLEN], *tp;
+  struct { int base, len; } best, cur;
+  unsigned int words[sizeof(struct in6_addr) / sizeof(uint16_t)];
+  int i;
+
+  /*
+   * Preprocess:
+   *  Copy the input (bytewise) array into a wordwise array.
+   *  Find the longest run of 0x00's in src[] for :: shorthanding.
+   */
+  memset(words, '\0', sizeof words);
+  for (i = 0; i < (int) sizeof(struct in6_addr); i++)
+    words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
+  best.base = -1;
+  best.len = 0;
+  cur.base = -1;
+  cur.len = 0;
+  for (i = 0; i < (int) ARRAY_SIZE(words); i++) {
+    if (words[i] == 0) {
+      if (cur.base == -1)
+        cur.base = i, cur.len = 1;
+      else
+        cur.len++;
+    } else {
+      if (cur.base != -1) {
+        if (best.base == -1 || cur.len > best.len)
+          best = cur;
+        cur.base = -1;
+      }
+    }
+  }
+  if (cur.base != -1) {
+    if (best.base == -1 || cur.len > best.len)
+      best = cur;
+  }
+  if (best.base != -1 && best.len < 2)
+    best.base = -1;
+
+  /*
+   * Format the result.
+   */
+  tp = tmp;
+  for (i = 0; i < (int) ARRAY_SIZE(words); i++) {
+    /* Are we inside the best run of 0x00's? */
+    if (best.base != -1 && i >= best.base &&
+        i < (best.base + best.len)) {
+      if (i == best.base)
+        *tp++ = ':';
+      continue;
+    }
+    /* Are we following an initial run of 0x00s or any real hex? */
+    if (i != 0)
+      *tp++ = ':';
+    /* Is this address an encapsulated IPv4? */
+    if (i == 6 && best.base == 0 && (best.len == 6 ||
+        (best.len == 7 && words[7] != 0x0001) ||
+        (best.len == 5 && words[5] == 0xffff))) {
+      int err = inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp));
+      if (err)
+        return err;
+      tp += strlen(tp);
+      break;
+    }
+    tp += sprintf(tp, "%x", words[i]);
+  }
+  /* Was it a trailing run of 0x00's? */
+  if (best.base != -1 && (best.base + best.len) == ARRAY_SIZE(words))
+    *tp++ = ':';
+  *tp++ = '\0';
+
+  /*
+   * Check for overflow, copy, and we're done.
+   */
+  if ((size_t)(tp - tmp) > size) {
+    return UV_ENOSPC;
+  }
+  strcpy(dst, tmp);
+  return 0;
+}
+
+
+int uv_inet_pton(int af, const char* src, void* dst) {
+  if (src == NULL || dst == NULL)
+    return UV_EINVAL;
+
+  switch (af) {
+  case AF_INET:
+    return (inet_pton4(src, dst));
+  case AF_INET6: {
+    int len;
+    char tmp[UV__INET6_ADDRSTRLEN], *s, *p;
+    s = (char*) src;
+    p = strchr(src, '%');
+    if (p != NULL) {
+      s = tmp;
+      len = p - src;
+      if (len > UV__INET6_ADDRSTRLEN-1)
+        return UV_EINVAL;
+      memcpy(s, src, len);
+      s[len] = '\0';
+    }
+    return inet_pton6(s, dst);
+  }
+  default:
+    return UV_EAFNOSUPPORT;
+  }
+  /* NOTREACHED */
+}
+
+
+static int inet_pton4(const char *src, unsigned char *dst) {
+  static const char digits[] = "0123456789";
+  int saw_digit, octets, ch;
+  unsigned char tmp[sizeof(struct in_addr)], *tp;
+
+  saw_digit = 0;
+  octets = 0;
+  *(tp = tmp) = 0;
+  while ((ch = *src++) != '\0') {
+    const char *pch;
+
+    if ((pch = strchr(digits, ch)) != NULL) {
+      unsigned int nw = *tp * 10 + (pch - digits);
+
+      if (saw_digit && *tp == 0)
+        return UV_EINVAL;
+      if (nw > 255)
+        return UV_EINVAL;
+      *tp = nw;
+      if (!saw_digit) {
+        if (++octets > 4)
+          return UV_EINVAL;
+        saw_digit = 1;
+      }
+    } else if (ch == '.' && saw_digit) {
+      if (octets == 4)
+        return UV_EINVAL;
+      *++tp = 0;
+      saw_digit = 0;
+    } else
+      return UV_EINVAL;
+  }
+  if (octets < 4)
+    return UV_EINVAL;
+  memcpy(dst, tmp, sizeof(struct in_addr));
+  return 0;
+}
+
+
+static int inet_pton6(const char *src, unsigned char *dst) {
+  static const char xdigits_l[] = "0123456789abcdef",
+                    xdigits_u[] = "0123456789ABCDEF";
+  unsigned char tmp[sizeof(struct in6_addr)], *tp, *endp, *colonp;
+  const char *xdigits, *curtok;
+  int ch, seen_xdigits;
+  unsigned int val;
+
+  memset((tp = tmp), '\0', sizeof tmp);
+  endp = tp + sizeof tmp;
+  colonp = NULL;
+  /* Leading :: requires some special handling. */
+  if (*src == ':')
+    if (*++src != ':')
+      return UV_EINVAL;
+  curtok = src;
+  seen_xdigits = 0;
+  val = 0;
+  while ((ch = *src++) != '\0') {
+    const char *pch;
+
+    if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
+      pch = strchr((xdigits = xdigits_u), ch);
+    if (pch != NULL) {
+      val <<= 4;
+      val |= (pch - xdigits);
+      if (++seen_xdigits > 4)
+        return UV_EINVAL;
+      continue;
+    }
+    if (ch == ':') {
+      curtok = src;
+      if (!seen_xdigits) {
+        if (colonp)
+          return UV_EINVAL;
+        colonp = tp;
+        continue;
+      } else if (*src == '\0') {
+        return UV_EINVAL;
+      }
+      if (tp + sizeof(uint16_t) > endp)
+        return UV_EINVAL;
+      *tp++ = (unsigned char) (val >> 8) & 0xff;
+      *tp++ = (unsigned char) val & 0xff;
+      seen_xdigits = 0;
+      val = 0;
+      continue;
+    }
+    if (ch == '.' && ((tp + sizeof(struct in_addr)) <= endp)) {
+      int err = inet_pton4(curtok, tp);
+      if (err == 0) {
+        tp += sizeof(struct in_addr);
+        seen_xdigits = 0;
+        break;  /*%< '\\0' was seen by inet_pton4(). */
+      }
+    }
+    return UV_EINVAL;
+  }
+  if (seen_xdigits) {
+    if (tp + sizeof(uint16_t) > endp)
+      return UV_EINVAL;
+    *tp++ = (unsigned char) (val >> 8) & 0xff;
+    *tp++ = (unsigned char) val & 0xff;
+  }
+  if (colonp != NULL) {
+    /*
+     * Since some memmove()'s erroneously fail to handle
+     * overlapping regions, we'll do the shift by hand.
+     */
+    const int n = tp - colonp;
+    int i;
+
+    if (tp == endp)
+      return UV_EINVAL;
+    for (i = 1; i <= n; i++) {
+      endp[- i] = colonp[n - i];
+      colonp[n - i] = 0;
+    }
+    tp = endp;
+  }
+  if (tp != endp)
+    return UV_EINVAL;
+  memcpy(dst, tmp, sizeof tmp);
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/queue.h b/Utilities/cmlibuv/src/queue.h
new file mode 100644
index 0000000..ff3540a
--- /dev/null
+++ b/Utilities/cmlibuv/src/queue.h
@@ -0,0 +1,108 @@
+/* Copyright (c) 2013, Ben Noordhuis <info at 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 QUEUE_H_
+#define QUEUE_H_
+
+#include <stddef.h>
+
+typedef void *QUEUE[2];
+
+/* Private macros. */
+#define QUEUE_NEXT(q)       (*(QUEUE **) &((*(q))[0]))
+#define QUEUE_PREV(q)       (*(QUEUE **) &((*(q))[1]))
+#define QUEUE_PREV_NEXT(q)  (QUEUE_NEXT(QUEUE_PREV(q)))
+#define QUEUE_NEXT_PREV(q)  (QUEUE_PREV(QUEUE_NEXT(q)))
+
+/* Public macros. */
+#define QUEUE_DATA(ptr, type, field)                                          \
+  ((type *) ((char *) (ptr) - offsetof(type, field)))
+
+/* Important note: mutating the list while QUEUE_FOREACH is
+ * iterating over its elements results in undefined behavior.
+ */
+#define QUEUE_FOREACH(q, h)                                                   \
+  for ((q) = QUEUE_NEXT(h); (q) != (h); (q) = QUEUE_NEXT(q))
+
+#define QUEUE_EMPTY(q)                                                        \
+  ((const QUEUE *) (q) == (const QUEUE *) QUEUE_NEXT(q))
+
+#define QUEUE_HEAD(q)                                                         \
+  (QUEUE_NEXT(q))
+
+#define QUEUE_INIT(q)                                                         \
+  do {                                                                        \
+    QUEUE_NEXT(q) = (q);                                                      \
+    QUEUE_PREV(q) = (q);                                                      \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_ADD(h, n)                                                       \
+  do {                                                                        \
+    QUEUE_PREV_NEXT(h) = QUEUE_NEXT(n);                                       \
+    QUEUE_NEXT_PREV(n) = QUEUE_PREV(h);                                       \
+    QUEUE_PREV(h) = QUEUE_PREV(n);                                            \
+    QUEUE_PREV_NEXT(h) = (h);                                                 \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_SPLIT(h, q, n)                                                  \
+  do {                                                                        \
+    QUEUE_PREV(n) = QUEUE_PREV(h);                                            \
+    QUEUE_PREV_NEXT(n) = (n);                                                 \
+    QUEUE_NEXT(n) = (q);                                                      \
+    QUEUE_PREV(h) = QUEUE_PREV(q);                                            \
+    QUEUE_PREV_NEXT(h) = (h);                                                 \
+    QUEUE_PREV(q) = (n);                                                      \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_MOVE(h, n)                                                      \
+  do {                                                                        \
+    if (QUEUE_EMPTY(h))                                                       \
+      QUEUE_INIT(n);                                                          \
+    else {                                                                    \
+      QUEUE* q = QUEUE_HEAD(h);                                               \
+      QUEUE_SPLIT(h, q, n);                                                   \
+    }                                                                         \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_INSERT_HEAD(h, q)                                               \
+  do {                                                                        \
+    QUEUE_NEXT(q) = QUEUE_NEXT(h);                                            \
+    QUEUE_PREV(q) = (h);                                                      \
+    QUEUE_NEXT_PREV(q) = (q);                                                 \
+    QUEUE_NEXT(h) = (q);                                                      \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_INSERT_TAIL(h, q)                                               \
+  do {                                                                        \
+    QUEUE_NEXT(q) = (h);                                                      \
+    QUEUE_PREV(q) = QUEUE_PREV(h);                                            \
+    QUEUE_PREV_NEXT(q) = (q);                                                 \
+    QUEUE_PREV(h) = (q);                                                      \
+  }                                                                           \
+  while (0)
+
+#define QUEUE_REMOVE(q)                                                       \
+  do {                                                                        \
+    QUEUE_PREV_NEXT(q) = QUEUE_NEXT(q);                                       \
+    QUEUE_NEXT_PREV(q) = QUEUE_PREV(q);                                       \
+  }                                                                           \
+  while (0)
+
+#endif /* QUEUE_H_ */
diff --git a/Utilities/cmlibuv/src/threadpool.c b/Utilities/cmlibuv/src/threadpool.c
new file mode 100644
index 0000000..2c5152b
--- /dev/null
+++ b/Utilities/cmlibuv/src/threadpool.c
@@ -0,0 +1,303 @@
+/* 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-common.h"
+
+#if !defined(_WIN32)
+# include "unix/internal.h"
+#else
+# include "win/req-inl.h"
+/* TODO(saghul): unify internal req functions */
+static void uv__req_init(uv_loop_t* loop,
+                         uv_req_t* req,
+                         uv_req_type type) {
+  uv_req_init(loop, req);
+  req->type = type;
+  uv__req_register(loop, req);
+}
+# define uv__req_init(loop, req, type) \
+    uv__req_init((loop), (uv_req_t*)(req), (type))
+#endif
+
+#include <stdlib.h>
+
+#define MAX_THREADPOOL_SIZE 128
+
+static uv_once_t once = UV_ONCE_INIT;
+static uv_cond_t cond;
+static uv_mutex_t mutex;
+static unsigned int idle_threads;
+static unsigned int nthreads;
+static uv_thread_t* threads;
+static uv_thread_t default_threads[4];
+static QUEUE exit_message;
+static QUEUE wq;
+static volatile int initialized;
+
+
+static void uv__cancelled(struct uv__work* w) {
+  abort();
+}
+
+
+/* To avoid deadlock with uv_cancel() it's crucial that the worker
+ * never holds the global mutex and the loop-local mutex at the same time.
+ */
+static void worker(void* arg) {
+  struct uv__work* w;
+  QUEUE* q;
+
+  (void) arg;
+
+  for (;;) {
+    uv_mutex_lock(&mutex);
+
+    while (QUEUE_EMPTY(&wq)) {
+      idle_threads += 1;
+      uv_cond_wait(&cond, &mutex);
+      idle_threads -= 1;
+    }
+
+    q = QUEUE_HEAD(&wq);
+
+    if (q == &exit_message)
+      uv_cond_signal(&cond);
+    else {
+      QUEUE_REMOVE(q);
+      QUEUE_INIT(q);  /* Signal uv_cancel() that the work req is
+                             executing. */
+    }
+
+    uv_mutex_unlock(&mutex);
+
+    if (q == &exit_message)
+      break;
+
+    w = QUEUE_DATA(q, struct uv__work, wq);
+    w->work(w);
+
+    uv_mutex_lock(&w->loop->wq_mutex);
+    w->work = NULL;  /* Signal uv_cancel() that the work req is done
+                        executing. */
+    QUEUE_INSERT_TAIL(&w->loop->wq, &w->wq);
+    uv_async_send(&w->loop->wq_async);
+    uv_mutex_unlock(&w->loop->wq_mutex);
+  }
+}
+
+
+static void post(QUEUE* q) {
+  uv_mutex_lock(&mutex);
+  QUEUE_INSERT_TAIL(&wq, q);
+  if (idle_threads > 0)
+    uv_cond_signal(&cond);
+  uv_mutex_unlock(&mutex);
+}
+
+
+#ifndef _WIN32
+UV_DESTRUCTOR(static void cleanup(void)) {
+  unsigned int i;
+
+  if (initialized == 0)
+    return;
+
+  post(&exit_message);
+
+  for (i = 0; i < nthreads; i++)
+    if (uv_thread_join(threads + i))
+      abort();
+
+  if (threads != default_threads)
+    uv__free(threads);
+
+  uv_mutex_destroy(&mutex);
+  uv_cond_destroy(&cond);
+
+  threads = NULL;
+  nthreads = 0;
+  initialized = 0;
+}
+#endif
+
+
+static void init_once(void) {
+  unsigned int i;
+  const char* val;
+
+  nthreads = ARRAY_SIZE(default_threads);
+  val = getenv("UV_THREADPOOL_SIZE");
+  if (val != NULL)
+    nthreads = atoi(val);
+  if (nthreads == 0)
+    nthreads = 1;
+  if (nthreads > MAX_THREADPOOL_SIZE)
+    nthreads = MAX_THREADPOOL_SIZE;
+
+  threads = default_threads;
+  if (nthreads > ARRAY_SIZE(default_threads)) {
+    threads = uv__malloc(nthreads * sizeof(threads[0]));
+    if (threads == NULL) {
+      nthreads = ARRAY_SIZE(default_threads);
+      threads = default_threads;
+    }
+  }
+
+  if (uv_cond_init(&cond))
+    abort();
+
+  if (uv_mutex_init(&mutex))
+    abort();
+
+  QUEUE_INIT(&wq);
+
+  for (i = 0; i < nthreads; i++)
+    if (uv_thread_create(threads + i, worker, NULL))
+      abort();
+
+  initialized = 1;
+}
+
+
+void uv__work_submit(uv_loop_t* loop,
+                     struct uv__work* w,
+                     void (*work)(struct uv__work* w),
+                     void (*done)(struct uv__work* w, int status)) {
+  uv_once(&once, init_once);
+  w->loop = loop;
+  w->work = work;
+  w->done = done;
+  post(&w->wq);
+}
+
+
+static int uv__work_cancel(uv_loop_t* loop, uv_req_t* req, struct uv__work* w) {
+  int cancelled;
+
+  uv_mutex_lock(&mutex);
+  uv_mutex_lock(&w->loop->wq_mutex);
+
+  cancelled = !QUEUE_EMPTY(&w->wq) && w->work != NULL;
+  if (cancelled)
+    QUEUE_REMOVE(&w->wq);
+
+  uv_mutex_unlock(&w->loop->wq_mutex);
+  uv_mutex_unlock(&mutex);
+
+  if (!cancelled)
+    return UV_EBUSY;
+
+  w->work = uv__cancelled;
+  uv_mutex_lock(&loop->wq_mutex);
+  QUEUE_INSERT_TAIL(&loop->wq, &w->wq);
+  uv_async_send(&loop->wq_async);
+  uv_mutex_unlock(&loop->wq_mutex);
+
+  return 0;
+}
+
+
+void uv__work_done(uv_async_t* handle) {
+  struct uv__work* w;
+  uv_loop_t* loop;
+  QUEUE* q;
+  QUEUE wq;
+  int err;
+
+  loop = container_of(handle, uv_loop_t, wq_async);
+  uv_mutex_lock(&loop->wq_mutex);
+  QUEUE_MOVE(&loop->wq, &wq);
+  uv_mutex_unlock(&loop->wq_mutex);
+
+  while (!QUEUE_EMPTY(&wq)) {
+    q = QUEUE_HEAD(&wq);
+    QUEUE_REMOVE(q);
+
+    w = container_of(q, struct uv__work, wq);
+    err = (w->work == uv__cancelled) ? UV_ECANCELED : 0;
+    w->done(w, err);
+  }
+}
+
+
+static void uv__queue_work(struct uv__work* w) {
+  uv_work_t* req = container_of(w, uv_work_t, work_req);
+
+  req->work_cb(req);
+}
+
+
+static void uv__queue_done(struct uv__work* w, int err) {
+  uv_work_t* req;
+
+  req = container_of(w, uv_work_t, work_req);
+  uv__req_unregister(req->loop, req);
+
+  if (req->after_work_cb == NULL)
+    return;
+
+  req->after_work_cb(req, err);
+}
+
+
+int uv_queue_work(uv_loop_t* loop,
+                  uv_work_t* req,
+                  uv_work_cb work_cb,
+                  uv_after_work_cb after_work_cb) {
+  if (work_cb == NULL)
+    return UV_EINVAL;
+
+  uv__req_init(loop, req, UV_WORK);
+  req->loop = loop;
+  req->work_cb = work_cb;
+  req->after_work_cb = after_work_cb;
+  uv__work_submit(loop, &req->work_req, uv__queue_work, uv__queue_done);
+  return 0;
+}
+
+
+int uv_cancel(uv_req_t* req) {
+  struct uv__work* wreq;
+  uv_loop_t* loop;
+
+  switch (req->type) {
+  case UV_FS:
+    loop =  ((uv_fs_t*) req)->loop;
+    wreq = &((uv_fs_t*) req)->work_req;
+    break;
+  case UV_GETADDRINFO:
+    loop =  ((uv_getaddrinfo_t*) req)->loop;
+    wreq = &((uv_getaddrinfo_t*) req)->work_req;
+    break;
+  case UV_GETNAMEINFO:
+    loop = ((uv_getnameinfo_t*) req)->loop;
+    wreq = &((uv_getnameinfo_t*) req)->work_req;
+    break;
+  case UV_WORK:
+    loop =  ((uv_work_t*) req)->loop;
+    wreq = &((uv_work_t*) req)->work_req;
+    break;
+  default:
+    return UV_EINVAL;
+  }
+
+  return uv__work_cancel(loop, req, wreq);
+}
diff --git a/Utilities/cmlibuv/src/unix/aix.c b/Utilities/cmlibuv/src/unix/aix.c
new file mode 100644
index 0000000..652cd98
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/aix.c
@@ -0,0 +1,1154 @@
+/* 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 "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 <libperfstat.h>
+#include <procinfo.h>
+#include <sys/proc.h>
+#include <sys/procfs.h>
+
+#include <sys/poll.h>
+
+#include <sys/pollset.h>
+#include <ctype.h>
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+#include <sys/ahafs_evProds.h>
+#endif
+
+#include <sys/mntctl.h>
+#include <sys/vmount.h>
+#include <limits.h>
+#include <strings.h>
+#include <sys/vnode.h>
+
+#define RDWR_BUF_SIZE   4096
+#define EQ(a,b)         (strcmp(a,b) == 0)
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  loop->fs_fd = -1;
+
+  /* Passing maxfd of -1 should mean the limit is determined
+   * by the user's ulimit or the global limit as per the doc */
+  loop->backend_fd = pollset_create(-1);
+
+  if (loop->backend_fd == -1)
+    return -1;
+
+  return 0;
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+  if (loop->fs_fd != -1) {
+    uv__close(loop->fs_fd);
+    loop->fs_fd = -1;
+  }
+
+  if (loop->backend_fd != -1) {
+    pollset_destroy(loop->backend_fd);
+    loop->backend_fd = -1;
+  }
+}
+
+
+int uv__io_check_fd(uv_loop_t* loop, int fd) {
+  struct poll_ctl pc;
+
+  pc.events = POLLIN;
+  pc.cmd = PS_MOD;  /* Equivalent to PS_ADD if the fd is not in the pollset. */
+  pc.fd = fd;
+
+  if (pollset_ctl(loop->backend_fd, &pc, 1))
+    return -errno;
+
+  pc.cmd = PS_DELETE;
+  if (pollset_ctl(loop->backend_fd, &pc, 1))
+    abort();
+
+  return 0;
+}
+
+
+void uv__io_poll(uv_loop_t* loop, int timeout) {
+  struct pollfd events[1024];
+  struct pollfd pqry;
+  struct pollfd* pe;
+  struct poll_ctl pc;
+  QUEUE* q;
+  uv__io_t* w;
+  uint64_t base;
+  uint64_t diff;
+  int have_signals;
+  int nevents;
+  int count;
+  int nfds;
+  int i;
+  int rc;
+  int add_failed;
+
+  if (loop->nfds == 0) {
+    assert(QUEUE_EMPTY(&loop->watcher_queue));
+    return;
+  }
+
+  while (!QUEUE_EMPTY(&loop->watcher_queue)) {
+    q = QUEUE_HEAD(&loop->watcher_queue);
+    QUEUE_REMOVE(q);
+    QUEUE_INIT(q);
+
+    w = QUEUE_DATA(q, uv__io_t, watcher_queue);
+    assert(w->pevents != 0);
+    assert(w->fd >= 0);
+    assert(w->fd < (int) loop->nwatchers);
+
+    pc.events = w->pevents;
+    pc.fd = w->fd;
+
+    add_failed = 0;
+    if (w->events == 0) {
+      pc.cmd = PS_ADD;
+      if (pollset_ctl(loop->backend_fd, &pc, 1)) {
+        if (errno != EINVAL) {
+          assert(0 && "Failed to add file descriptor (pc.fd) to pollset");
+          abort();
+        }
+        /* Check if the fd is already in the pollset */
+        pqry.fd = pc.fd;
+        rc = pollset_query(loop->backend_fd, &pqry);
+        switch (rc) {
+        case -1:
+          assert(0 && "Failed to query pollset for file descriptor");
+          abort();
+        case 0:
+          assert(0 && "Pollset does not contain file descriptor");
+          abort();
+        }
+        /* If we got here then the pollset already contained the file descriptor even though
+         * we didn't think it should. This probably shouldn't happen, but we can continue. */
+        add_failed = 1;
+      }
+    }
+    if (w->events != 0 || add_failed) {
+      /* Modify, potentially removing events -- need to delete then add.
+       * Could maybe mod if we knew for sure no events are removed, but
+       * content of w->events is handled above as not reliable (falls back)
+       * so may require a pollset_query() which would have to be pretty cheap
+       * compared to a PS_DELETE to be worth optimizing. Alternatively, could
+       * lazily remove events, squelching them in the mean time. */
+      pc.cmd = PS_DELETE;
+      if (pollset_ctl(loop->backend_fd, &pc, 1)) {
+        assert(0 && "Failed to delete file descriptor (pc.fd) from pollset");
+        abort();
+      }
+      pc.cmd = PS_ADD;
+      if (pollset_ctl(loop->backend_fd, &pc, 1)) {
+        assert(0 && "Failed to add file descriptor (pc.fd) to pollset");
+        abort();
+      }
+    }
+
+    w->events = w->pevents;
+  }
+
+  assert(timeout >= -1);
+  base = loop->time;
+  count = 48; /* Benchmarks suggest this gives the best throughput. */
+
+  for (;;) {
+    nfds = pollset_poll(loop->backend_fd,
+                        events,
+                        ARRAY_SIZE(events),
+                        timeout);
+
+    /* Update loop->time unconditionally. It's tempting to skip the update when
+     * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
+     * operating system didn't reschedule our process while in the syscall.
+     */
+    SAVE_ERRNO(uv__update_time(loop));
+
+    if (nfds == 0) {
+      assert(timeout != -1);
+      return;
+    }
+
+    if (nfds == -1) {
+      if (errno != EINTR) {
+        abort();
+      }
+
+      if (timeout == -1)
+        continue;
+
+      if (timeout == 0)
+        return;
+
+      /* Interrupted by a signal. Update timeout and poll again. */
+      goto update_timeout;
+    }
+
+    have_signals = 0;
+    nevents = 0;
+
+    assert(loop->watchers != NULL);
+    loop->watchers[loop->nwatchers] = (void*) events;
+    loop->watchers[loop->nwatchers + 1] = (void*) (uintptr_t) nfds;
+
+    for (i = 0; i < nfds; i++) {
+      pe = events + i;
+      pc.cmd = PS_DELETE;
+      pc.fd = pe->fd;
+
+      /* Skip invalidated events, see uv__platform_invalidate_fd */
+      if (pc.fd == -1)
+        continue;
+
+      assert(pc.fd >= 0);
+      assert((unsigned) pc.fd < loop->nwatchers);
+
+      w = loop->watchers[pc.fd];
+
+      if (w == NULL) {
+        /* File descriptor that we've stopped watching, disarm it.
+         *
+         * Ignore all errors because we may be racing with another thread
+         * when the file descriptor is closed.
+         */
+        pollset_ctl(loop->backend_fd, &pc, 1);
+        continue;
+      }
+
+      /* Run signal watchers last.  This also affects child process watchers
+       * because those are implemented in terms of signal watchers.
+       */
+      if (w == &loop->signal_io_watcher)
+        have_signals = 1;
+      else
+        w->cb(loop, w, pe->revents);
+
+      nevents++;
+    }
+
+    if (have_signals != 0)
+      loop->signal_io_watcher.cb(loop, &loop->signal_io_watcher, POLLIN);
+
+    loop->watchers[loop->nwatchers] = NULL;
+    loop->watchers[loop->nwatchers + 1] = NULL;
+
+    if (have_signals != 0)
+      return;  /* Event loop should cycle now so don't poll again. */
+
+    if (nevents != 0) {
+      if (nfds == ARRAY_SIZE(events) && --count != 0) {
+        /* Poll for more events but don't block this time. */
+        timeout = 0;
+        continue;
+      }
+      return;
+    }
+
+    if (timeout == 0)
+      return;
+
+    if (timeout == -1)
+      continue;
+
+update_timeout:
+    assert(timeout > 0);
+
+    diff = loop->time - base;
+    if (diff >= (uint64_t) timeout)
+      return;
+
+    timeout -= diff;
+  }
+}
+
+
+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 -EINVAL;
+
+  pi.pi_pid = getpid();
+  res = getargs(&pi, sizeof(pi), args, sizeof(args));
+  if (res < 0)
+    return -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 -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 -EINVAL;
+
+    clonedpath = uv__strdup(path);
+    if (clonedpath == NULL)
+      return -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 -EINVAL;
+  }
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  perfstat_memory_total_t mem_total;
+  int result = perfstat_memory_total(NULL, &mem_total, sizeof(mem_total), 1);
+  if (result == -1) {
+    return 0;
+  }
+  return mem_total.real_free * 4096;
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  perfstat_memory_total_t mem_total;
+  int result = perfstat_memory_total(NULL, &mem_total, sizeof(mem_total), 1);
+  if (result == -1) {
+    return 0;
+  }
+  return mem_total.real_total * 4096;
+}
+
+
+void uv_loadavg(double avg[3]) {
+  perfstat_cpu_total_t ps_total;
+  int result = perfstat_cpu_total(NULL, &ps_total, sizeof(ps_total), 1);
+  if (result == -1) {
+    avg[0] = 0.; avg[1] = 0.; avg[2] = 0.;
+    return;
+  }
+  avg[0] = ps_total.loadavg[0] / (double)(1 << SBITS);
+  avg[1] = ps_total.loadavg[1] / (double)(1 << SBITS);
+  avg[2] = ps_total.loadavg[2] / (double)(1 << SBITS);
+}
+
+
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+static char *uv__rawname(char *cp) {
+  static char rawbuf[FILENAME_MAX+1];
+  char *dp = rindex(cp, '/');
+
+  if (dp == 0)
+    return 0;
+
+  *dp = 0;
+  strcpy(rawbuf, cp);
+  *dp = '/';
+  strcat(rawbuf, "/r");
+  strcat(rawbuf, dp+1);
+  return rawbuf;
+}
+
+
+/*
+ * Determine whether given pathname is a directory
+ * Returns 0 if the path is a directory, -1 if not
+ *
+ * Note: Opportunity here for more detailed error information but
+ *       that requires changing callers of this function as well
+ */
+static int uv__path_is_a_directory(char* filename) {
+  struct stat statbuf;
+
+  if (stat(filename, &statbuf) < 0)
+    return -1;  /* failed: not a directory, assume it is a file */
+
+  if (statbuf.st_type == VDIR)
+    return 0;
+
+  return -1;
+}
+
+
+/*
+ * Check whether AHAFS is mounted.
+ * Returns 0 if AHAFS is mounted, or an error code < 0 on failure
+ */
+static int uv__is_ahafs_mounted(void){
+  int rv, i = 2;
+  struct vmount *p;
+  int size_multiplier = 10;
+  size_t siz = sizeof(struct vmount)*size_multiplier;
+  struct vmount *vmt;
+  const char *dev = "/aha";
+  char *obj, *stub;
+
+  p = uv__malloc(siz);
+  if (p == NULL)
+    return -errno;
+
+  /* Retrieve all mounted filesystems */
+  rv = mntctl(MCTL_QUERY, siz, (char*)p);
+  if (rv < 0)
+    return -errno;
+  if (rv == 0) {
+    /* buffer was not large enough, reallocate to correct size */
+    siz = *(int*)p;
+    uv__free(p);
+    p = uv__malloc(siz);
+    if (p == NULL)
+      return -errno;
+    rv = mntctl(MCTL_QUERY, siz, (char*)p);
+    if (rv < 0)
+      return -errno;
+  }
+
+  /* Look for dev in filesystems mount info */
+  for(vmt = p, i = 0; i < rv; i++) {
+    obj = vmt2dataptr(vmt, VMT_OBJECT);     /* device */
+    stub = vmt2dataptr(vmt, VMT_STUB);      /* mount point */
+
+    if (EQ(obj, dev) || EQ(uv__rawname(obj), dev) || EQ(stub, dev)) {
+      uv__free(p);  /* Found a match */
+      return 0;
+    }
+    vmt = (struct vmount *) ((char *) vmt + vmt->vmt_length);
+  }
+
+  /* /aha is required for monitoring filesystem changes */
+  return -1;
+}
+
+/*
+ * Recursive call to mkdir() to create intermediate folders, if any
+ * Returns code from mkdir call
+ */
+static int uv__makedir_p(const char *dir) {
+  char tmp[256];
+  char *p = NULL;
+  size_t len;
+  int err;
+
+  snprintf(tmp, sizeof(tmp),"%s",dir);
+  len = strlen(tmp);
+  if (tmp[len - 1] == '/')
+    tmp[len - 1] = 0;
+  for (p = tmp + 1; *p; p++) {
+    if (*p == '/') {
+      *p = 0;
+      err = mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
+      if (err != 0 && errno != EEXIST)
+        return err;
+      *p = '/';
+    }
+  }
+  return mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
+}
+
+/*
+ * Creates necessary subdirectories in the AIX Event Infrastructure
+ * file system for monitoring the object specified.
+ * Returns code from mkdir call
+ */
+static int uv__make_subdirs_p(const char *filename) {
+  char cmd[2048];
+  char *p;
+  int rc = 0;
+
+  /* Strip off the monitor file name */
+  p = strrchr(filename, '/');
+
+  if (p == NULL)
+    return 0;
+
+  if (uv__path_is_a_directory((char*)filename) == 0) {
+    sprintf(cmd, "/aha/fs/modDir.monFactory");
+  } else {
+    sprintf(cmd, "/aha/fs/modFile.monFactory");
+  }
+
+  strncat(cmd, filename, (p - filename));
+  rc = uv__makedir_p(cmd);
+
+  if (rc == -1 && errno != EEXIST){
+    return -errno;
+  }
+
+  return rc;
+}
+
+
+/*
+ * Checks if /aha is mounted, then proceeds to set up the monitoring
+ * objects for the specified file.
+ * Returns 0 on success, or an error code < 0 on failure
+ */
+static int uv__setup_ahafs(const char* filename, int *fd) {
+  int rc = 0;
+  char mon_file_write_string[RDWR_BUF_SIZE];
+  char mon_file[PATH_MAX];
+  int file_is_directory = 0; /* -1 == NO, 0 == YES  */
+
+  /* Create monitor file name for object */
+  file_is_directory = uv__path_is_a_directory((char*)filename);
+
+  if (file_is_directory == 0)
+    sprintf(mon_file, "/aha/fs/modDir.monFactory");
+  else
+    sprintf(mon_file, "/aha/fs/modFile.monFactory");
+
+  if ((strlen(mon_file) + strlen(filename) + 5) > PATH_MAX)
+    return -ENAMETOOLONG;
+
+  /* Make the necessary subdirectories for the monitor file */
+  rc = uv__make_subdirs_p(filename);
+  if (rc == -1 && errno != EEXIST)
+    return rc;
+
+  strcat(mon_file, filename);
+  strcat(mon_file, ".mon");
+
+  *fd = 0; errno = 0;
+
+  /* Open the monitor file, creating it if necessary */
+  *fd = open(mon_file, O_CREAT|O_RDWR);
+  if (*fd < 0)
+    return -errno;
+
+  /* Write out the monitoring specifications.
+   * In this case, we are monitoring for a state change event type
+   *    CHANGED=YES
+   * We will be waiting in select call, rather than a read:
+   *    WAIT_TYPE=WAIT_IN_SELECT
+   * We only want minimal information for files:
+   *      INFO_LVL=1
+   * For directories, we want more information to track what file
+   * caused the change
+   *      INFO_LVL=2
+   */
+
+  if (file_is_directory == 0)
+    sprintf(mon_file_write_string, "CHANGED=YES;WAIT_TYPE=WAIT_IN_SELECT;INFO_LVL=2");
+  else
+    sprintf(mon_file_write_string, "CHANGED=YES;WAIT_TYPE=WAIT_IN_SELECT;INFO_LVL=1");
+
+  rc = write(*fd, mon_file_write_string, strlen(mon_file_write_string)+1);
+  if (rc < 0)
+    return -errno;
+
+  return 0;
+}
+
+/*
+ * Skips a specified number of lines in the buffer passed in.
+ * Walks the buffer pointed to by p and attempts to skip n lines.
+ * Returns the total number of lines skipped
+ */
+static int uv__skip_lines(char **p, int n) {
+  int lines = 0;
+
+  while(n > 0) {
+    *p = strchr(*p, '\n');
+    if (!p)
+      return lines;
+
+    (*p)++;
+    n--;
+    lines++;
+  }
+  return lines;
+}
+
+
+/*
+ * Parse the event occurrence data to figure out what event just occurred
+ * and take proper action.
+ *
+ * The buf is a pointer to the buffer containing the event occurrence data
+ * Returns 0 on success, -1 if unrecoverable error in parsing
+ *
+ */
+static int uv__parse_data(char *buf, int *events, uv_fs_event_t* handle) {
+  int    evp_rc, i;
+  char   *p;
+  char   filename[PATH_MAX]; /* To be used when handling directories */
+
+  p = buf;
+  *events = 0;
+
+  /* Clean the filename buffer*/
+  for(i = 0; i < PATH_MAX; i++) {
+    filename[i] = 0;
+  }
+  i = 0;
+
+  /* Check for BUF_WRAP */
+  if (strncmp(buf, "BUF_WRAP", strlen("BUF_WRAP")) == 0) {
+    assert(0 && "Buffer wrap detected, Some event occurrences lost!");
+    return 0;
+  }
+
+  /* Since we are using the default buffer size (4K), and have specified
+   * INFO_LVL=1, we won't see any EVENT_OVERFLOW conditions.  Applications
+   * should check for this keyword if they are using an INFO_LVL of 2 or
+   * higher, and have a buffer size of <= 4K
+   */
+
+  /* Skip to RC_FROM_EVPROD */
+  if (uv__skip_lines(&p, 9) != 9)
+    return -1;
+
+  if (sscanf(p, "RC_FROM_EVPROD=%d\nEND_EVENT_DATA", &evp_rc) == 1) {
+    if (uv__path_is_a_directory(handle->path) == 0) { /* Directory */
+      if (evp_rc == AHAFS_MODDIR_UNMOUNT || evp_rc == AHAFS_MODDIR_REMOVE_SELF) {
+        /* The directory is no longer available for monitoring */
+        *events = UV_RENAME;
+        handle->dir_filename = NULL;
+      } else {
+        /* A file was added/removed inside the directory */
+        *events = UV_CHANGE;
+
+        /* Get the EVPROD_INFO */
+        if (uv__skip_lines(&p, 1) != 1)
+          return -1;
+
+        /* Scan out the name of the file that triggered the event*/
+        if (sscanf(p, "BEGIN_EVPROD_INFO\n%sEND_EVPROD_INFO", filename) == 1) {
+          handle->dir_filename = uv__strdup((const char*)&filename);
+        } else
+          return -1;
+        }
+    } else { /* Regular File */
+      if (evp_rc == AHAFS_MODFILE_RENAME)
+        *events = UV_RENAME;
+      else
+        *events = UV_CHANGE;
+    }
+  }
+  else
+    return -1;
+
+  return 0;
+}
+
+
+/* This is the internal callback */
+static void uv__ahafs_event(uv_loop_t* loop, uv__io_t* event_watch, unsigned int fflags) {
+  char   result_data[RDWR_BUF_SIZE];
+  int bytes, rc = 0;
+  uv_fs_event_t* handle;
+  int events = 0;
+  char fname[PATH_MAX];
+  char *p;
+
+  handle = container_of(event_watch, uv_fs_event_t, event_watcher);
+
+  /* At this point, we assume that polling has been done on the
+   * file descriptor, so we can just read the AHAFS event occurrence
+   * data and parse its results without having to block anything
+   */
+  bytes = pread(event_watch->fd, result_data, RDWR_BUF_SIZE, 0);
+
+  assert((bytes >= 0) && "uv__ahafs_event - Error reading monitor file");
+
+  /* Parse the data */
+  if(bytes > 0)
+    rc = uv__parse_data(result_data, &events, handle);
+
+  /* Unrecoverable error */
+  if (rc == -1)
+    return;
+
+  /* For directory changes, the name of the files that triggered the change
+   * are never absolute pathnames
+   */
+  if (uv__path_is_a_directory(handle->path) == 0) {
+    p = handle->dir_filename;
+  } else {
+    p = strrchr(handle->path, '/');
+    if (p == NULL)
+      p = handle->path;
+    else
+      p++;
+  }
+  strncpy(fname, p, sizeof(fname) - 1);
+  /* Just in case */
+  fname[sizeof(fname) - 1] = '\0';
+
+  handle->cb(handle, fname, events, 0);
+}
+#endif
+
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_EVENT);
+  return 0;
+#else
+  return -ENOSYS;
+#endif
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* filename,
+                      unsigned int flags) {
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+  int  fd, rc, str_offset = 0;
+  char cwd[PATH_MAX];
+  char absolute_path[PATH_MAX];
+  char readlink_cwd[PATH_MAX];
+
+
+  /* Figure out whether filename is absolute or not */
+  if (filename[0] == '/') {
+    /* We have absolute pathname */
+    snprintf(absolute_path, sizeof(absolute_path), "%s", filename);
+  } else {
+    /* We have a relative pathname, compose the absolute pathname */
+    snprintf(cwd, sizeof(cwd), "/proc/%lu/cwd", (unsigned long) getpid());
+    rc = readlink(cwd, readlink_cwd, sizeof(readlink_cwd) - 1);
+    if (rc < 0)
+      return rc;
+    /* readlink does not null terminate our string */
+    readlink_cwd[rc] = '\0';
+
+    if (filename[0] == '.' && filename[1] == '/')
+      str_offset = 2;
+
+    snprintf(absolute_path, sizeof(absolute_path), "%s%s", readlink_cwd,
+             filename + str_offset);
+  }
+
+  if (uv__is_ahafs_mounted() < 0)  /* /aha checks failed */
+    return UV_ENOSYS;
+
+  /* Setup ahafs */
+  rc = uv__setup_ahafs((const char *)absolute_path, &fd);
+  if (rc != 0)
+    return rc;
+
+  /* Setup/Initialize all the libuv routines */
+  uv__handle_start(handle);
+  uv__io_init(&handle->event_watcher, uv__ahafs_event, fd);
+  handle->path = uv__strdup(filename);
+  handle->cb = cb;
+
+  uv__io_start(handle->loop, &handle->event_watcher, POLLIN);
+
+  return 0;
+#else
+  return -ENOSYS;
+#endif
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+  if (!uv__is_active(handle))
+    return 0;
+
+  uv__io_close(handle->loop, &handle->event_watcher);
+  uv__handle_stop(handle);
+
+  if (uv__path_is_a_directory(handle->path) == 0) {
+    uv__free(handle->dir_filename);
+    handle->dir_filename = NULL;
+  }
+
+  uv__free(handle->path);
+  handle->path = NULL;
+  uv__close(handle->event_watcher.fd);
+  handle->event_watcher.fd = -1;
+
+  return 0;
+#else
+  return -ENOSYS;
+#endif
+}
+
+
+void uv__fs_event_close(uv_fs_event_t* handle) {
+#ifdef HAVE_SYS_AHAFS_EVPRODS_H
+  uv_fs_event_stop(handle);
+#else
+  UNREACHABLE();
+#endif
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+
+  buffer[0] = '\0';
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  char pp[64];
+  psinfo_t psinfo;
+  int err;
+  int fd;
+
+  snprintf(pp, sizeof(pp), "/proc/%lu/psinfo", (unsigned long) getpid());
+
+  fd = open(pp, O_RDONLY);
+  if (fd == -1)
+    return -errno;
+
+  /* FIXME(bnoordhuis) Handle EINTR. */
+  err = -EINVAL;
+  if (read(fd, &psinfo, sizeof(psinfo)) == sizeof(psinfo)) {
+    *rss = (size_t)psinfo.pr_rssize * 1024;
+    err = 0;
+  }
+  uv__close(fd);
+
+  return err;
+}
+
+
+int uv_uptime(double* uptime) {
+  struct utmp *utmp_buf;
+  size_t entries = 0;
+  time_t boot_time;
+
+  utmpname(UTMP_FILE);
+
+  setutent();
+
+  while ((utmp_buf = getutent()) != NULL) {
+    if (utmp_buf->ut_user[0] && utmp_buf->ut_type == USER_PROCESS)
+      ++entries;
+    if (utmp_buf->ut_type == BOOT_TIME)
+      boot_time = utmp_buf->ut_time;
+  }
+
+  endutent();
+
+  if (boot_time == 0)
+    return -ENOSYS;
+
+  *uptime = time(NULL) - boot_time;
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  uv_cpu_info_t* cpu_info;
+  perfstat_cpu_total_t ps_total;
+  perfstat_cpu_t* ps_cpus;
+  perfstat_id_t cpu_id;
+  int result, ncpus, idx = 0;
+
+  result = perfstat_cpu_total(NULL, &ps_total, sizeof(ps_total), 1);
+  if (result == -1) {
+    return -ENOSYS;
+  }
+
+  ncpus = result = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
+  if (result == -1) {
+    return -ENOSYS;
+  }
+
+  ps_cpus = (perfstat_cpu_t*) uv__malloc(ncpus * sizeof(perfstat_cpu_t));
+  if (!ps_cpus) {
+    return -ENOMEM;
+  }
+
+  strcpy(cpu_id.name, FIRST_CPU);
+  result = perfstat_cpu(&cpu_id, ps_cpus, sizeof(perfstat_cpu_t), ncpus);
+  if (result == -1) {
+    uv__free(ps_cpus);
+    return -ENOSYS;
+  }
+
+  *cpu_infos = (uv_cpu_info_t*) uv__malloc(ncpus * sizeof(uv_cpu_info_t));
+  if (!*cpu_infos) {
+    uv__free(ps_cpus);
+    return -ENOMEM;
+  }
+
+  *count = ncpus;
+
+  cpu_info = *cpu_infos;
+  while (idx < ncpus) {
+    cpu_info->speed = (int)(ps_total.processorHZ / 1000000);
+    cpu_info->model = uv__strdup(ps_total.description);
+    cpu_info->cpu_times.user = ps_cpus[idx].user;
+    cpu_info->cpu_times.sys = ps_cpus[idx].sys;
+    cpu_info->cpu_times.idle = ps_cpus[idx].idle;
+    cpu_info->cpu_times.irq = ps_cpus[idx].wait;
+    cpu_info->cpu_times.nice = 0;
+    cpu_info++;
+    idx++;
+  }
+
+  uv__free(ps_cpus);
+  return 0;
+}
+
+
+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, size = 1;
+  struct ifconf ifc;
+  struct ifreq *ifr, *p, flg;
+
+  *count = 0;
+
+  if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) {
+    return -errno;
+  }
+
+  if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) {
+    uv__close(sockfd);
+    return -errno;
+  }
+
+  ifc.ifc_req = (struct ifreq*)uv__malloc(size);
+  ifc.ifc_len = size;
+  if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) {
+    uv__close(sockfd);
+    return -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 -errno;
+    }
+
+    if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING))
+      continue;
+
+    (*count)++;
+  }
+
+  /* Alloc the return interface structs */
+  *addresses = (uv_interface_address_t*)
+    uv__malloc(*count * sizeof(uv_interface_address_t));
+  if (!(*addresses)) {
+    uv__close(sockfd);
+    return -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;
+
+    memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name));
+    if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) {
+      uv__close(sockfd);
+      return -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 (p->ifr_addr.sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr);
+    }
+
+    /* TODO: Retrieve netmask using SIOCGIFNETMASK ioctl */
+
+    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);
+}
+
+void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) {
+  struct pollfd* events;
+  uintptr_t i;
+  uintptr_t nfds;
+  struct poll_ctl pc;
+
+  assert(loop->watchers != NULL);
+
+  events = (struct pollfd*) loop->watchers[loop->nwatchers];
+  nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
+
+  if (events != NULL)
+    /* Invalidate events with same file descriptor */
+    for (i = 0; i < nfds; i++)
+      if ((int) events[i].fd == fd)
+        events[i].fd = -1;
+
+  /* Remove the file descriptor from the poll set */
+  pc.events = 0;
+  pc.cmd = PS_DELETE;
+  pc.fd = fd;
+  if(loop->backend_fd >= 0)
+    pollset_ctl(loop->backend_fd, &pc, 1);
+}
diff --git a/Utilities/cmlibuv/src/unix/android-ifaddrs.c b/Utilities/cmlibuv/src/unix/android-ifaddrs.c
new file mode 100644
index 0000000..30f681b
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/android-ifaddrs.c
@@ -0,0 +1,703 @@
+/*
+Copyright (c) 2013, Kenneth MacKay
+Copyright (c) 2014, Emergya (Cloud4all, FP7/2007-2013 grant agreement #289016)
+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.
+
+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.
+*/
+
+#include "android-ifaddrs.h"
+#include "uv-common.h"
+
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <net/if_arp.h>
+#include <netinet/in.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+typedef struct NetlinkList
+{
+    struct NetlinkList *m_next;
+    struct nlmsghdr *m_data;
+    unsigned int m_size;
+} NetlinkList;
+
+static int netlink_socket(void)
+{
+    struct sockaddr_nl l_addr;
+
+    int l_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
+    if(l_socket < 0)
+    {
+        return -1;
+    }
+
+    memset(&l_addr, 0, sizeof(l_addr));
+    l_addr.nl_family = AF_NETLINK;
+    if(bind(l_socket, (struct sockaddr *)&l_addr, sizeof(l_addr)) < 0)
+    {
+        close(l_socket);
+        return -1;
+    }
+
+    return l_socket;
+}
+
+static int netlink_send(int p_socket, int p_request)
+{
+    char l_buffer[NLMSG_ALIGN(sizeof(struct nlmsghdr)) + NLMSG_ALIGN(sizeof(struct rtgenmsg))];
+
+    struct nlmsghdr *l_hdr;
+    struct rtgenmsg *l_msg;
+    struct sockaddr_nl l_addr;
+
+    memset(l_buffer, 0, sizeof(l_buffer));
+
+    l_hdr = (struct nlmsghdr *)l_buffer;
+    l_msg = (struct rtgenmsg *)NLMSG_DATA(l_hdr);
+
+    l_hdr->nlmsg_len = NLMSG_LENGTH(sizeof(*l_msg));
+    l_hdr->nlmsg_type = p_request;
+    l_hdr->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
+    l_hdr->nlmsg_pid = 0;
+    l_hdr->nlmsg_seq = p_socket;
+    l_msg->rtgen_family = AF_UNSPEC;
+
+    memset(&l_addr, 0, sizeof(l_addr));
+    l_addr.nl_family = AF_NETLINK;
+    return (sendto(p_socket, l_hdr, l_hdr->nlmsg_len, 0, (struct sockaddr *)&l_addr, sizeof(l_addr)));
+}
+
+static int netlink_recv(int p_socket, void *p_buffer, size_t p_len)
+{
+    struct sockaddr_nl l_addr;
+    struct msghdr l_msg;
+
+    struct iovec l_iov;
+    l_iov.iov_base = p_buffer;
+    l_iov.iov_len = p_len;
+
+    for(;;)
+    {
+        int l_result;
+        l_msg.msg_name = (void *)&l_addr;
+        l_msg.msg_namelen = sizeof(l_addr);
+        l_msg.msg_iov = &l_iov;
+        l_msg.msg_iovlen = 1;
+        l_msg.msg_control = NULL;
+        l_msg.msg_controllen = 0;
+        l_msg.msg_flags = 0;
+        l_result = recvmsg(p_socket, &l_msg, 0);
+
+        if(l_result < 0)
+        {
+            if(errno == EINTR)
+            {
+                continue;
+            }
+            return -2;
+        }
+
+        /* Buffer was too small */
+        if(l_msg.msg_flags & MSG_TRUNC)
+        {
+            return -1;
+        }
+        return l_result;
+    }
+}
+
+static struct nlmsghdr *getNetlinkResponse(int p_socket, int *p_size, int *p_done)
+{
+    size_t l_size = 4096;
+    void *l_buffer = NULL;
+
+    for(;;)
+    {
+        int l_read;
+
+        uv__free(l_buffer);
+        l_buffer = uv__malloc(l_size);
+        if (l_buffer == NULL)
+        {
+            return NULL;
+        }
+
+        l_read = netlink_recv(p_socket, l_buffer, l_size);
+        *p_size = l_read;
+        if(l_read == -2)
+        {
+            uv__free(l_buffer);
+            return NULL;
+        }
+        if(l_read >= 0)
+        {
+            pid_t l_pid = getpid();
+            struct nlmsghdr *l_hdr;
+            for(l_hdr = (struct nlmsghdr *)l_buffer; NLMSG_OK(l_hdr, (unsigned int)l_read); l_hdr = (struct nlmsghdr *)NLMSG_NEXT(l_hdr, l_read))
+            {
+                if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket)
+                {
+                    continue;
+                }
+
+                if(l_hdr->nlmsg_type == NLMSG_DONE)
+                {
+                    *p_done = 1;
+                    break;
+                }
+
+                if(l_hdr->nlmsg_type == NLMSG_ERROR)
+                {
+                    uv__free(l_buffer);
+                    return NULL;
+                }
+            }
+            return l_buffer;
+        }
+
+        l_size *= 2;
+    }
+}
+
+static NetlinkList *newListItem(struct nlmsghdr *p_data, unsigned int p_size)
+{
+    NetlinkList *l_item = uv__malloc(sizeof(NetlinkList));
+    if (l_item == NULL)
+    {
+        return NULL;
+    }
+
+    l_item->m_next = NULL;
+    l_item->m_data = p_data;
+    l_item->m_size = p_size;
+    return l_item;
+}
+
+static void freeResultList(NetlinkList *p_list)
+{
+    NetlinkList *l_cur;
+    while(p_list)
+    {
+        l_cur = p_list;
+        p_list = p_list->m_next;
+        uv__free(l_cur->m_data);
+        uv__free(l_cur);
+    }
+}
+
+static NetlinkList *getResultList(int p_socket, int p_request)
+{
+    int l_size;
+    int l_done;
+    NetlinkList *l_list;
+    NetlinkList *l_end;
+
+    if(netlink_send(p_socket, p_request) < 0)
+    {
+        return NULL;
+    }
+
+    l_list = NULL;
+    l_end = NULL;
+
+    l_done = 0;
+    while(!l_done)
+    {
+        NetlinkList *l_item;
+
+        struct nlmsghdr *l_hdr = getNetlinkResponse(p_socket, &l_size, &l_done);
+        /* Error */
+        if(!l_hdr)
+        {
+            freeResultList(l_list);
+            return NULL;
+        }
+
+        l_item = newListItem(l_hdr, l_size);
+        if (!l_item)
+        {
+            freeResultList(l_list);
+            return NULL;
+        }
+        if(!l_list)
+        {
+            l_list = l_item;
+        }
+        else
+        {
+            l_end->m_next = l_item;
+        }
+        l_end = l_item;
+    }
+    return l_list;
+}
+
+static size_t maxSize(size_t a, size_t b)
+{
+    return (a > b ? a : b);
+}
+
+static size_t calcAddrLen(sa_family_t p_family, int p_dataSize)
+{
+    switch(p_family)
+    {
+        case AF_INET:
+            return sizeof(struct sockaddr_in);
+        case AF_INET6:
+            return sizeof(struct sockaddr_in6);
+        case AF_PACKET:
+            return maxSize(sizeof(struct sockaddr_ll), offsetof(struct sockaddr_ll, sll_addr) + p_dataSize);
+        default:
+            return maxSize(sizeof(struct sockaddr), offsetof(struct sockaddr, sa_data) + p_dataSize);
+    }
+}
+
+static void makeSockaddr(sa_family_t p_family, struct sockaddr *p_dest, void *p_data, size_t p_size)
+{
+    switch(p_family)
+    {
+        case AF_INET:
+            memcpy(&((struct sockaddr_in*)p_dest)->sin_addr, p_data, p_size);
+            break;
+        case AF_INET6:
+            memcpy(&((struct sockaddr_in6*)p_dest)->sin6_addr, p_data, p_size);
+            break;
+        case AF_PACKET:
+            memcpy(((struct sockaddr_ll*)p_dest)->sll_addr, p_data, p_size);
+            ((struct sockaddr_ll*)p_dest)->sll_halen = p_size;
+            break;
+        default:
+            memcpy(p_dest->sa_data, p_data, p_size);
+            break;
+    }
+    p_dest->sa_family = p_family;
+}
+
+static void addToEnd(struct ifaddrs **p_resultList, struct ifaddrs *p_entry)
+{
+    if(!*p_resultList)
+    {
+        *p_resultList = p_entry;
+    }
+    else
+    {
+        struct ifaddrs *l_cur = *p_resultList;
+        while(l_cur->ifa_next)
+        {
+            l_cur = l_cur->ifa_next;
+        }
+        l_cur->ifa_next = p_entry;
+    }
+}
+
+static int interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList)
+{
+    struct ifaddrs *l_entry;
+
+    char *l_index;
+    char *l_name;
+    char *l_addr;
+    char *l_data;
+
+    struct ifinfomsg *l_info = (struct ifinfomsg *)NLMSG_DATA(p_hdr);
+
+    size_t l_nameSize = 0;
+    size_t l_addrSize = 0;
+    size_t l_dataSize = 0;
+
+    size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg));
+    struct rtattr *l_rta;
+    for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize))
+    {
+        size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
+        switch(l_rta->rta_type)
+        {
+            case IFLA_ADDRESS:
+            case IFLA_BROADCAST:
+                l_addrSize += NLMSG_ALIGN(calcAddrLen(AF_PACKET, l_rtaDataSize));
+                break;
+            case IFLA_IFNAME:
+                l_nameSize += NLMSG_ALIGN(l_rtaSize + 1);
+                break;
+            case IFLA_STATS:
+                l_dataSize += NLMSG_ALIGN(l_rtaSize);
+                break;
+            default:
+                break;
+        }
+    }
+
+    l_entry = uv__malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize);
+    if (l_entry == NULL)
+    {
+        return -1;
+    }
+    memset(l_entry, 0, sizeof(struct ifaddrs));
+    l_entry->ifa_name = "";
+
+    l_index = ((char *)l_entry) + sizeof(struct ifaddrs);
+    l_name = l_index + sizeof(int);
+    l_addr = l_name + l_nameSize;
+    l_data = l_addr + l_addrSize;
+
+    /* Save the interface index so we can look it up when handling the
+     * addresses.
+     */
+    memcpy(l_index, &l_info->ifi_index, sizeof(int));
+
+    l_entry->ifa_flags = l_info->ifi_flags;
+
+    l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg));
+    for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize))
+    {
+        void *l_rtaData = RTA_DATA(l_rta);
+        size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
+        switch(l_rta->rta_type)
+        {
+            case IFLA_ADDRESS:
+            case IFLA_BROADCAST:
+            {
+                size_t l_addrLen = calcAddrLen(AF_PACKET, l_rtaDataSize);
+                makeSockaddr(AF_PACKET, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize);
+                ((struct sockaddr_ll *)l_addr)->sll_ifindex = l_info->ifi_index;
+                ((struct sockaddr_ll *)l_addr)->sll_hatype = l_info->ifi_type;
+                if(l_rta->rta_type == IFLA_ADDRESS)
+                {
+                    l_entry->ifa_addr = (struct sockaddr *)l_addr;
+                }
+                else
+                {
+                    l_entry->ifa_broadaddr = (struct sockaddr *)l_addr;
+                }
+                l_addr += NLMSG_ALIGN(l_addrLen);
+                break;
+            }
+            case IFLA_IFNAME:
+                strncpy(l_name, l_rtaData, l_rtaDataSize);
+                l_name[l_rtaDataSize] = '\0';
+                l_entry->ifa_name = l_name;
+                break;
+            case IFLA_STATS:
+                memcpy(l_data, l_rtaData, l_rtaDataSize);
+                l_entry->ifa_data = l_data;
+                break;
+            default:
+                break;
+        }
+    }
+
+    addToEnd(p_resultList, l_entry);
+    return 0;
+}
+
+static struct ifaddrs *findInterface(int p_index, struct ifaddrs **p_links, int p_numLinks)
+{
+    int l_num = 0;
+    struct ifaddrs *l_cur = *p_links;
+    while(l_cur && l_num < p_numLinks)
+    {
+        char *l_indexPtr = ((char *)l_cur) + sizeof(struct ifaddrs);
+        int l_index;
+        memcpy(&l_index, l_indexPtr, sizeof(int));
+        if(l_index == p_index)
+        {
+            return l_cur;
+        }
+
+        l_cur = l_cur->ifa_next;
+        ++l_num;
+    }
+    return NULL;
+}
+
+static int interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, int p_numLinks)
+{
+    struct ifaddrmsg *l_info = (struct ifaddrmsg *)NLMSG_DATA(p_hdr);
+    struct ifaddrs *l_interface = findInterface(l_info->ifa_index, p_resultList, p_numLinks);
+
+    size_t l_nameSize = 0;
+    size_t l_addrSize = 0;
+
+    int l_addedNetmask = 0;
+
+    size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg));
+    struct rtattr *l_rta;
+    struct ifaddrs *l_entry;
+
+    char *l_name;
+    char *l_addr;
+
+    for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize))
+    {
+        size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
+        if(l_info->ifa_family == AF_PACKET)
+        {
+            continue;
+        }
+
+        switch(l_rta->rta_type)
+        {
+            case IFA_ADDRESS:
+            case IFA_LOCAL:
+                if((l_info->ifa_family == AF_INET || l_info->ifa_family == AF_INET6) && !l_addedNetmask)
+                {
+                    /* Make room for netmask */
+                    l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize));
+                    l_addedNetmask = 1;
+                }
+            case IFA_BROADCAST:
+                l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize));
+                break;
+            case IFA_LABEL:
+                l_nameSize += NLMSG_ALIGN(l_rtaSize + 1);
+                break;
+            default:
+                break;
+        }
+    }
+
+    l_entry = uv__malloc(sizeof(struct ifaddrs) + l_nameSize + l_addrSize);
+    if (l_entry == NULL)
+    {
+        return -1;
+    }
+    memset(l_entry, 0, sizeof(struct ifaddrs));
+    l_entry->ifa_name = (l_interface ? l_interface->ifa_name : "");
+
+    l_name = ((char *)l_entry) + sizeof(struct ifaddrs);
+    l_addr = l_name + l_nameSize;
+
+    l_entry->ifa_flags = l_info->ifa_flags;
+    if(l_interface)
+    {
+        l_entry->ifa_flags |= l_interface->ifa_flags;
+    }
+
+    l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg));
+    for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize))
+    {
+        void *l_rtaData = RTA_DATA(l_rta);
+        size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
+        switch(l_rta->rta_type)
+        {
+            case IFA_ADDRESS:
+            case IFA_BROADCAST:
+            case IFA_LOCAL:
+            {
+                size_t l_addrLen = calcAddrLen(l_info->ifa_family, l_rtaDataSize);
+                makeSockaddr(l_info->ifa_family, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize);
+                if(l_info->ifa_family == AF_INET6)
+                {
+                    if(IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)l_rtaData) || IN6_IS_ADDR_MC_LINKLOCAL((struct in6_addr *)l_rtaData))
+                    {
+                        ((struct sockaddr_in6 *)l_addr)->sin6_scope_id = l_info->ifa_index;
+                    }
+                }
+
+                /* Apparently in a point-to-point network IFA_ADDRESS contains
+                 * the dest address and IFA_LOCAL contains the local address
+                 */
+                if(l_rta->rta_type == IFA_ADDRESS)
+                {
+                    if(l_entry->ifa_addr)
+                    {
+                        l_entry->ifa_dstaddr = (struct sockaddr *)l_addr;
+                    }
+                    else
+                    {
+                        l_entry->ifa_addr = (struct sockaddr *)l_addr;
+                    }
+                }
+                else if(l_rta->rta_type == IFA_LOCAL)
+                {
+                    if(l_entry->ifa_addr)
+                    {
+                        l_entry->ifa_dstaddr = l_entry->ifa_addr;
+                    }
+                    l_entry->ifa_addr = (struct sockaddr *)l_addr;
+                }
+                else
+                {
+                    l_entry->ifa_broadaddr = (struct sockaddr *)l_addr;
+                }
+                l_addr += NLMSG_ALIGN(l_addrLen);
+                break;
+            }
+            case IFA_LABEL:
+                strncpy(l_name, l_rtaData, l_rtaDataSize);
+                l_name[l_rtaDataSize] = '\0';
+                l_entry->ifa_name = l_name;
+                break;
+            default:
+                break;
+        }
+    }
+
+    if(l_entry->ifa_addr && (l_entry->ifa_addr->sa_family == AF_INET || l_entry->ifa_addr->sa_family == AF_INET6))
+    {
+        unsigned l_maxPrefix = (l_entry->ifa_addr->sa_family == AF_INET ? 32 : 128);
+        unsigned l_prefix = (l_info->ifa_prefixlen > l_maxPrefix ? l_maxPrefix : l_info->ifa_prefixlen);
+        char l_mask[16] = {0};
+        unsigned i;
+        for(i=0; i<(l_prefix/8); ++i)
+        {
+            l_mask[i] = 0xff;
+        }
+        if(l_prefix % 8)
+        {
+            l_mask[i] = 0xff << (8 - (l_prefix % 8));
+        }
+
+        makeSockaddr(l_entry->ifa_addr->sa_family, (struct sockaddr *)l_addr, l_mask, l_maxPrefix / 8);
+        l_entry->ifa_netmask = (struct sockaddr *)l_addr;
+    }
+
+    addToEnd(p_resultList, l_entry);
+    return 0;
+}
+
+static int interpretLinks(int p_socket, NetlinkList *p_netlinkList, struct ifaddrs **p_resultList)
+{
+
+    int l_numLinks = 0;
+    pid_t l_pid = getpid();
+    for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next)
+    {
+        unsigned int l_nlsize = p_netlinkList->m_size;
+        struct nlmsghdr *l_hdr;
+        for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
+        {
+            if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket)
+            {
+                continue;
+            }
+
+            if(l_hdr->nlmsg_type == NLMSG_DONE)
+            {
+                break;
+            }
+
+            if(l_hdr->nlmsg_type == RTM_NEWLINK)
+            {
+                if(interpretLink(l_hdr, p_resultList) == -1)
+                {
+                    return -1;
+                }
+                ++l_numLinks;
+            }
+        }
+    }
+    return l_numLinks;
+}
+
+static int interpretAddrs(int p_socket, NetlinkList *p_netlinkList, struct ifaddrs **p_resultList, int p_numLinks)
+{
+    pid_t l_pid = getpid();
+    for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next)
+    {
+        unsigned int l_nlsize = p_netlinkList->m_size;
+        struct nlmsghdr *l_hdr;
+        for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
+        {
+            if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket)
+            {
+                continue;
+            }
+
+            if(l_hdr->nlmsg_type == NLMSG_DONE)
+            {
+                break;
+            }
+
+            if(l_hdr->nlmsg_type == RTM_NEWADDR)
+            {
+                if (interpretAddr(l_hdr, p_resultList, p_numLinks) == -1)
+                {
+                    return -1;
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+int getifaddrs(struct ifaddrs **ifap)
+{
+    int l_socket;
+    int l_result;
+    int l_numLinks;
+    NetlinkList *l_linkResults;
+    NetlinkList *l_addrResults;
+
+    if(!ifap)
+    {
+        return -1;
+    }
+    *ifap = NULL;
+
+    l_socket = netlink_socket();
+    if(l_socket < 0)
+    {
+        return -1;
+    }
+
+    l_linkResults = getResultList(l_socket, RTM_GETLINK);
+    if(!l_linkResults)
+    {
+        close(l_socket);
+        return -1;
+    }
+
+    l_addrResults = getResultList(l_socket, RTM_GETADDR);
+    if(!l_addrResults)
+    {
+        close(l_socket);
+        freeResultList(l_linkResults);
+        return -1;
+    }
+
+    l_result = 0;
+    l_numLinks = interpretLinks(l_socket, l_linkResults, ifap);
+    if(l_numLinks == -1 || interpretAddrs(l_socket, l_addrResults, ifap, l_numLinks) == -1)
+    {
+        l_result = -1;
+    }
+
+    freeResultList(l_linkResults);
+    freeResultList(l_addrResults);
+    close(l_socket);
+    return l_result;
+}
+
+void freeifaddrs(struct ifaddrs *ifa)
+{
+    struct ifaddrs *l_cur;
+    while(ifa)
+    {
+        l_cur = ifa;
+        ifa = ifa->ifa_next;
+        uv__free(l_cur);
+    }
+}
diff --git a/Utilities/cmlibuv/src/unix/async.c b/Utilities/cmlibuv/src/unix/async.c
new file mode 100644
index 0000000..393cdeb
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/async.c
@@ -0,0 +1,290 @@
+/* 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 contains both the uv__async internal infrastructure and the
+ * user-facing uv_async_t functions.
+ */
+
+#include "uv.h"
+#include "internal.h"
+#include "atomic-ops.h"
+
+#include <errno.h>
+#include <stdio.h>  /* snprintf() */
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static void uv__async_event(uv_loop_t* loop,
+                            struct uv__async* w,
+                            unsigned int nevents);
+static int uv__async_eventfd(void);
+
+
+int uv_async_init(uv_loop_t* loop, uv_async_t* handle, uv_async_cb async_cb) {
+  int err;
+
+  err = uv__async_start(loop, &loop->async_watcher, uv__async_event);
+  if (err)
+    return err;
+
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_ASYNC);
+  handle->async_cb = async_cb;
+  handle->pending = 0;
+
+  QUEUE_INSERT_TAIL(&loop->async_handles, &handle->queue);
+  uv__handle_start(handle);
+
+  return 0;
+}
+
+
+int uv_async_send(uv_async_t* handle) {
+  /* Do a cheap read first. */
+  if (ACCESS_ONCE(int, handle->pending) != 0)
+    return 0;
+
+  if (cmpxchgi(&handle->pending, 0, 1) == 0)
+    uv__async_send(&handle->loop->async_watcher);
+
+  return 0;
+}
+
+
+void uv__async_close(uv_async_t* handle) {
+  QUEUE_REMOVE(&handle->queue);
+  uv__handle_stop(handle);
+}
+
+
+static void uv__async_event(uv_loop_t* loop,
+                            struct uv__async* w,
+                            unsigned int nevents) {
+  QUEUE queue;
+  QUEUE* q;
+  uv_async_t* h;
+
+  QUEUE_MOVE(&loop->async_handles, &queue);
+  while (!QUEUE_EMPTY(&queue)) {
+    q = QUEUE_HEAD(&queue);
+    h = QUEUE_DATA(q, uv_async_t, queue);
+
+    QUEUE_REMOVE(q);
+    QUEUE_INSERT_TAIL(&loop->async_handles, q);
+
+    if (cmpxchgi(&h->pending, 1, 0) == 0)
+      continue;
+
+    if (h->async_cb == NULL)
+      continue;
+    h->async_cb(h);
+  }
+}
+
+
+static void uv__async_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  struct uv__async* wa;
+  char buf[1024];
+  unsigned n;
+  ssize_t r;
+
+  n = 0;
+  for (;;) {
+    r = read(w->fd, buf, sizeof(buf));
+
+    if (r > 0)
+      n += r;
+
+    if (r == sizeof(buf))
+      continue;
+
+    if (r != -1)
+      break;
+
+    if (errno == EAGAIN || errno == EWOULDBLOCK)
+      break;
+
+    if (errno == EINTR)
+      continue;
+
+    abort();
+  }
+
+  wa = container_of(w, struct uv__async, io_watcher);
+
+#if defined(__linux__)
+  if (wa->wfd == -1) {
+    uint64_t val;
+    assert(n == sizeof(val));
+    memcpy(&val, buf, sizeof(val));  /* Avoid alignment issues. */
+    wa->cb(loop, wa, val);
+    return;
+  }
+#endif
+
+  wa->cb(loop, wa, n);
+}
+
+
+void uv__async_send(struct uv__async* wa) {
+  const void* buf;
+  ssize_t len;
+  int fd;
+  int r;
+
+  buf = "";
+  len = 1;
+  fd = wa->wfd;
+
+#if defined(__linux__)
+  if (fd == -1) {
+    static const uint64_t val = 1;
+    buf = &val;
+    len = sizeof(val);
+    fd = wa->io_watcher.fd;  /* eventfd */
+  }
+#endif
+
+  do
+    r = write(fd, buf, len);
+  while (r == -1 && errno == EINTR);
+
+  if (r == len)
+    return;
+
+  if (r == -1)
+    if (errno == EAGAIN || errno == EWOULDBLOCK)
+      return;
+
+  abort();
+}
+
+
+void uv__async_init(struct uv__async* wa) {
+  wa->io_watcher.fd = -1;
+  wa->wfd = -1;
+}
+
+
+int uv__async_start(uv_loop_t* loop, struct uv__async* wa, uv__async_cb cb) {
+  int pipefd[2];
+  int err;
+
+  if (wa->io_watcher.fd != -1)
+    return 0;
+
+  err = uv__async_eventfd();
+  if (err >= 0) {
+    pipefd[0] = err;
+    pipefd[1] = -1;
+  }
+  else if (err == -ENOSYS) {
+    err = uv__make_pipe(pipefd, UV__F_NONBLOCK);
+#if defined(__linux__)
+    /* Save a file descriptor by opening one of the pipe descriptors as
+     * read/write through the procfs.  That file descriptor can then
+     * function as both ends of the pipe.
+     */
+    if (err == 0) {
+      char buf[32];
+      int fd;
+
+      snprintf(buf, sizeof(buf), "/proc/self/fd/%d", pipefd[0]);
+      fd = uv__open_cloexec(buf, O_RDWR);
+      if (fd >= 0) {
+        uv__close(pipefd[0]);
+        uv__close(pipefd[1]);
+        pipefd[0] = fd;
+        pipefd[1] = fd;
+      }
+    }
+#endif
+  }
+
+  if (err < 0)
+    return err;
+
+  uv__io_init(&wa->io_watcher, uv__async_io, pipefd[0]);
+  uv__io_start(loop, &wa->io_watcher, POLLIN);
+  wa->wfd = pipefd[1];
+  wa->cb = cb;
+
+  return 0;
+}
+
+
+void uv__async_stop(uv_loop_t* loop, struct uv__async* wa) {
+  if (wa->io_watcher.fd == -1)
+    return;
+
+  if (wa->wfd != -1) {
+    if (wa->wfd != wa->io_watcher.fd)
+      uv__close(wa->wfd);
+    wa->wfd = -1;
+  }
+
+  uv__io_stop(loop, &wa->io_watcher, POLLIN);
+  uv__close(wa->io_watcher.fd);
+  wa->io_watcher.fd = -1;
+}
+
+
+static int uv__async_eventfd() {
+#if defined(__linux__)
+  static int no_eventfd2;
+  static int no_eventfd;
+  int fd;
+
+  if (no_eventfd2)
+    goto skip_eventfd2;
+
+  fd = uv__eventfd2(0, UV__EFD_CLOEXEC | UV__EFD_NONBLOCK);
+  if (fd != -1)
+    return fd;
+
+  if (errno != ENOSYS)
+    return -errno;
+
+  no_eventfd2 = 1;
+
+skip_eventfd2:
+
+  if (no_eventfd)
+    goto skip_eventfd;
+
+  fd = uv__eventfd(0);
+  if (fd != -1) {
+    uv__cloexec(fd, 1);
+    uv__nonblock(fd, 1);
+    return fd;
+  }
+
+  if (errno != ENOSYS)
+    return -errno;
+
+  no_eventfd = 1;
+
+skip_eventfd:
+
+#endif
+
+  return -ENOSYS;
+}
diff --git a/Utilities/cmlibuv/src/unix/atomic-ops.h b/Utilities/cmlibuv/src/unix/atomic-ops.h
new file mode 100644
index 0000000..815e355
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/atomic-ops.h
@@ -0,0 +1,88 @@
+/* Copyright (c) 2013, Ben Noordhuis <info at 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_ATOMIC_OPS_H_
+#define UV_ATOMIC_OPS_H_
+
+#include "internal.h"  /* UV_UNUSED */
+
+#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
+#include <atomic.h>
+#define __sync_val_compare_and_swap(p, o, n) atomic_cas_ptr(p, o, n)
+#endif
+
+UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval));
+UV_UNUSED(static long cmpxchgl(long* ptr, long oldval, long newval));
+UV_UNUSED(static void cpu_relax(void));
+
+/* Prefer hand-rolled assembly over the gcc builtins because the latter also
+ * issue full memory barriers.
+ */
+UV_UNUSED(static int cmpxchgi(int* ptr, int oldval, int newval)) {
+#if defined(__i386__) || defined(__x86_64__)
+  int out;
+  __asm__ __volatile__ ("lock; cmpxchg %2, %1;"
+                        : "=a" (out), "+m" (*(volatile int*) ptr)
+                        : "r" (newval), "0" (oldval)
+                        : "memory");
+  return out;
+#elif defined(_AIX) && defined(__xlC__)
+  const int out = (*(volatile int*) ptr);
+  __compare_and_swap(ptr, &oldval, newval);
+  return out;
+#elif defined(__MVS__)
+  return __plo_CS(ptr, (unsigned int*) ptr,
+                  oldval, (unsigned int*) &newval);
+#else
+  return __sync_val_compare_and_swap(ptr, oldval, newval);
+#endif
+}
+
+UV_UNUSED(static long cmpxchgl(long* ptr, long oldval, long newval)) {
+#if defined(__i386__) || defined(__x86_64__)
+  long out;
+  __asm__ __volatile__ ("lock; cmpxchg %2, %1;"
+                        : "=a" (out), "+m" (*(volatile long*) ptr)
+                        : "r" (newval), "0" (oldval)
+                        : "memory");
+  return out;
+#elif defined(_AIX) && defined(__xlC__)
+  const long out = (*(volatile int*) ptr);
+# if defined(__64BIT__)
+  __compare_and_swaplp(ptr, &oldval, newval);
+# else
+  __compare_and_swap(ptr, &oldval, newval);
+# endif /* if defined(__64BIT__) */
+  return out;
+#elif defined (__MVS__)
+# ifdef _LP64
+  return __plo_CSGR(ptr, (unsigned long long*) ptr,
+                    oldval, (unsigned long long*) &newval);
+# else
+  return __plo_CS(ptr, (unsigned int*) ptr,
+                  oldval, (unsigned int*) &newval);
+# endif
+#else
+  return __sync_val_compare_and_swap(ptr, oldval, newval);
+#endif
+}
+
+UV_UNUSED(static void cpu_relax(void)) {
+#if defined(__i386__) || defined(__x86_64__)
+  __asm__ __volatile__ ("rep; nop");  /* a.k.a. PAUSE */
+#endif
+}
+
+#endif  /* UV_ATOMIC_OPS_H_ */
diff --git a/Utilities/cmlibuv/src/unix/core.c b/Utilities/cmlibuv/src/unix/core.c
new file mode 100644
index 0000000..d88fc1d
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/core.c
@@ -0,0 +1,1238 @@
+/* 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 "internal.h"
+
+#include <stddef.h> /* NULL */
+#include <stdio.h> /* printf */
+#include <stdlib.h>
+#include <string.h> /* strerror */
+#include <errno.h>
+#include <assert.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
+#include <sys/uio.h> /* writev */
+#include <sys/resource.h> /* getrusage */
+#include <pwd.h>
+
+#ifdef __sun
+# include <sys/filio.h>
+# include <sys/types.h>
+# include <sys/wait.h>
+#endif
+
+#ifdef __APPLE__
+# include <mach-o/dyld.h> /* _NSGetExecutablePath */
+# include <sys/filio.h>
+# if defined(O_CLOEXEC)
+#  define UV__O_CLOEXEC O_CLOEXEC
+# endif
+#endif
+
+#if defined(__DragonFly__)      || \
+    defined(__FreeBSD__)        || \
+    defined(__FreeBSD_kernel__)
+# include <sys/sysctl.h>
+# include <sys/filio.h>
+# include <sys/wait.h>
+# define UV__O_CLOEXEC O_CLOEXEC
+# if defined(__FreeBSD__) && __FreeBSD__ >= 10
+#  define uv__accept4 accept4
+#  define UV__SOCK_NONBLOCK SOCK_NONBLOCK
+#  define UV__SOCK_CLOEXEC  SOCK_CLOEXEC
+# endif
+# if !defined(F_DUP2FD_CLOEXEC) && defined(_F_DUP2FD_CLOEXEC)
+#  define F_DUP2FD_CLOEXEC  _F_DUP2FD_CLOEXEC
+# endif
+#endif
+
+#if defined(__ANDROID_API__) && __ANDROID_API__ < 21
+# include <dlfcn.h>  /* for dlsym */
+#endif
+
+#if defined(__MVS__)
+#include <sys/ioctl.h>
+#endif
+
+static int uv__run_pending(uv_loop_t* loop);
+
+/* Verify that uv_buf_t is ABI-compatible with struct iovec. */
+STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
+STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
+              sizeof(((struct iovec*) 0)->iov_base));
+STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
+              sizeof(((struct iovec*) 0)->iov_len));
+STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
+STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
+
+
+uint64_t uv_hrtime(void) {
+  return uv__hrtime(UV_CLOCK_PRECISE);
+}
+
+
+void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
+  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
+
+  handle->flags |= UV_CLOSING;
+  handle->close_cb = close_cb;
+
+  switch (handle->type) {
+  case UV_NAMED_PIPE:
+    uv__pipe_close((uv_pipe_t*)handle);
+    break;
+
+  case UV_TTY:
+    uv__stream_close((uv_stream_t*)handle);
+    break;
+
+  case UV_TCP:
+    uv__tcp_close((uv_tcp_t*)handle);
+    break;
+
+  case UV_UDP:
+    uv__udp_close((uv_udp_t*)handle);
+    break;
+
+  case UV_PREPARE:
+    uv__prepare_close((uv_prepare_t*)handle);
+    break;
+
+  case UV_CHECK:
+    uv__check_close((uv_check_t*)handle);
+    break;
+
+  case UV_IDLE:
+    uv__idle_close((uv_idle_t*)handle);
+    break;
+
+  case UV_ASYNC:
+    uv__async_close((uv_async_t*)handle);
+    break;
+
+  case UV_TIMER:
+    uv__timer_close((uv_timer_t*)handle);
+    break;
+
+  case UV_PROCESS:
+    uv__process_close((uv_process_t*)handle);
+    break;
+
+  case UV_FS_EVENT:
+    uv__fs_event_close((uv_fs_event_t*)handle);
+    break;
+
+  case UV_POLL:
+    uv__poll_close((uv_poll_t*)handle);
+    break;
+
+  case UV_FS_POLL:
+    uv__fs_poll_close((uv_fs_poll_t*)handle);
+    break;
+
+  case UV_SIGNAL:
+    uv__signal_close((uv_signal_t*) handle);
+    /* Signal handles may not be closed immediately. The signal code will */
+    /* itself close uv__make_close_pending whenever appropriate. */
+    return;
+
+  default:
+    assert(0);
+  }
+
+  uv__make_close_pending(handle);
+}
+
+int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
+  int r;
+  int fd;
+  socklen_t len;
+
+  if (handle == NULL || value == NULL)
+    return -EINVAL;
+
+  if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
+    fd = uv__stream_fd((uv_stream_t*) handle);
+  else if (handle->type == UV_UDP)
+    fd = ((uv_udp_t *) handle)->io_watcher.fd;
+  else
+    return -ENOTSUP;
+
+  len = sizeof(*value);
+
+  if (*value == 0)
+    r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
+  else
+    r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
+
+  if (r < 0)
+    return -errno;
+
+  return 0;
+}
+
+void uv__make_close_pending(uv_handle_t* handle) {
+  assert(handle->flags & UV_CLOSING);
+  assert(!(handle->flags & UV_CLOSED));
+  handle->next_closing = handle->loop->closing_handles;
+  handle->loop->closing_handles = handle;
+}
+
+int uv__getiovmax(void) {
+#if defined(IOV_MAX)
+  return IOV_MAX;
+#elif defined(_SC_IOV_MAX)
+  static int iovmax = -1;
+  if (iovmax == -1) {
+    iovmax = sysconf(_SC_IOV_MAX);
+    /* On some embedded devices (arm-linux-uclibc based ip camera),
+     * sysconf(_SC_IOV_MAX) can not get the correct value. The return
+     * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
+     */
+    if (iovmax == -1) iovmax = 1;
+  }
+  return iovmax;
+#else
+  return 1024;
+#endif
+}
+
+
+static void uv__finish_close(uv_handle_t* handle) {
+  /* Note: while the handle is in the UV_CLOSING state now, it's still possible
+   * for it to be active in the sense that uv__is_active() returns true.
+   * A good example is when the user calls uv_shutdown(), immediately followed
+   * by uv_close(). The handle is considered active at this point because the
+   * completion of the shutdown req is still pending.
+   */
+  assert(handle->flags & UV_CLOSING);
+  assert(!(handle->flags & UV_CLOSED));
+  handle->flags |= UV_CLOSED;
+
+  switch (handle->type) {
+    case UV_PREPARE:
+    case UV_CHECK:
+    case UV_IDLE:
+    case UV_ASYNC:
+    case UV_TIMER:
+    case UV_PROCESS:
+    case UV_FS_EVENT:
+    case UV_FS_POLL:
+    case UV_POLL:
+    case UV_SIGNAL:
+      break;
+
+    case UV_NAMED_PIPE:
+    case UV_TCP:
+    case UV_TTY:
+      uv__stream_destroy((uv_stream_t*)handle);
+      break;
+
+    case UV_UDP:
+      uv__udp_finish_close((uv_udp_t*)handle);
+      break;
+
+    default:
+      assert(0);
+      break;
+  }
+
+  uv__handle_unref(handle);
+  QUEUE_REMOVE(&handle->handle_queue);
+
+  if (handle->close_cb) {
+    handle->close_cb(handle);
+  }
+}
+
+
+static void uv__run_closing_handles(uv_loop_t* loop) {
+  uv_handle_t* p;
+  uv_handle_t* q;
+
+  p = loop->closing_handles;
+  loop->closing_handles = NULL;
+
+  while (p) {
+    q = p->next_closing;
+    uv__finish_close(p);
+    p = q;
+  }
+}
+
+
+int uv_is_closing(const uv_handle_t* handle) {
+  return uv__is_closing(handle);
+}
+
+
+int uv_backend_fd(const uv_loop_t* loop) {
+  return loop->backend_fd;
+}
+
+
+int uv_backend_timeout(const uv_loop_t* loop) {
+  if (loop->stop_flag != 0)
+    return 0;
+
+  if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
+    return 0;
+
+  if (!QUEUE_EMPTY(&loop->idle_handles))
+    return 0;
+
+  if (!QUEUE_EMPTY(&loop->pending_queue))
+    return 0;
+
+  if (loop->closing_handles)
+    return 0;
+
+  return uv__next_timeout(loop);
+}
+
+
+static int uv__loop_alive(const uv_loop_t* loop) {
+  return uv__has_active_handles(loop) ||
+         uv__has_active_reqs(loop) ||
+         loop->closing_handles != NULL;
+}
+
+
+int uv_loop_alive(const uv_loop_t* loop) {
+    return uv__loop_alive(loop);
+}
+
+
+int uv_run(uv_loop_t* loop, uv_run_mode mode) {
+  int timeout;
+  int r;
+  int ran_pending;
+
+  r = uv__loop_alive(loop);
+  if (!r)
+    uv__update_time(loop);
+
+  while (r != 0 && loop->stop_flag == 0) {
+    uv__update_time(loop);
+    uv__run_timers(loop);
+    ran_pending = uv__run_pending(loop);
+    uv__run_idle(loop);
+    uv__run_prepare(loop);
+
+    timeout = 0;
+    if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
+      timeout = uv_backend_timeout(loop);
+
+    uv__io_poll(loop, timeout);
+    uv__run_check(loop);
+    uv__run_closing_handles(loop);
+
+    if (mode == UV_RUN_ONCE) {
+      /* UV_RUN_ONCE implies forward progress: at least one callback must have
+       * been invoked when it returns. uv__io_poll() can return without doing
+       * I/O (meaning: no callbacks) when its timeout expires - which means we
+       * have pending timers that satisfy the forward progress constraint.
+       *
+       * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
+       * the check.
+       */
+      uv__update_time(loop);
+      uv__run_timers(loop);
+    }
+
+    r = uv__loop_alive(loop);
+    if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
+      break;
+  }
+
+  /* The if statement lets gcc compile it to a conditional store. Avoids
+   * dirtying a cache line.
+   */
+  if (loop->stop_flag != 0)
+    loop->stop_flag = 0;
+
+  return r;
+}
+
+
+void uv_update_time(uv_loop_t* loop) {
+  uv__update_time(loop);
+}
+
+
+int uv_is_active(const uv_handle_t* handle) {
+  return uv__is_active(handle);
+}
+
+
+/* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
+int uv__socket(int domain, int type, int protocol) {
+  int sockfd;
+  int err;
+
+#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
+  sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
+  if (sockfd != -1)
+    return sockfd;
+
+  if (errno != EINVAL)
+    return -errno;
+#endif
+
+  sockfd = socket(domain, type, protocol);
+  if (sockfd == -1)
+    return -errno;
+
+  err = uv__nonblock(sockfd, 1);
+  if (err == 0)
+    err = uv__cloexec(sockfd, 1);
+
+  if (err) {
+    uv__close(sockfd);
+    return err;
+  }
+
+#if defined(SO_NOSIGPIPE)
+  {
+    int on = 1;
+    setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
+  }
+#endif
+
+  return sockfd;
+}
+
+/* get a file pointer to a file in read-only and close-on-exec mode */
+FILE* uv__open_file(const char* path) {
+  int fd;
+  FILE* fp;
+
+  fd = uv__open_cloexec(path, O_RDONLY);
+  if (fd < 0)
+    return NULL;
+
+   fp = fdopen(fd, "r");
+   if (fp == NULL)
+     uv__close(fd);
+
+   return fp;
+}
+
+
+int uv__accept(int sockfd) {
+  int peerfd;
+  int err;
+
+  assert(sockfd >= 0);
+
+  while (1) {
+#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10)
+    static int no_accept4;
+
+    if (no_accept4)
+      goto skip;
+
+    peerfd = uv__accept4(sockfd,
+                         NULL,
+                         NULL,
+                         UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
+    if (peerfd != -1)
+      return peerfd;
+
+    if (errno == EINTR)
+      continue;
+
+    if (errno != ENOSYS)
+      return -errno;
+
+    no_accept4 = 1;
+skip:
+#endif
+
+    peerfd = accept(sockfd, NULL, NULL);
+    if (peerfd == -1) {
+      if (errno == EINTR)
+        continue;
+      return -errno;
+    }
+
+    err = uv__cloexec(peerfd, 1);
+    if (err == 0)
+      err = uv__nonblock(peerfd, 1);
+
+    if (err) {
+      uv__close(peerfd);
+      return err;
+    }
+
+    return peerfd;
+  }
+}
+
+
+int uv__close_nocheckstdio(int fd) {
+  int saved_errno;
+  int rc;
+
+  assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
+
+  saved_errno = errno;
+  rc = close(fd);
+  if (rc == -1) {
+    rc = -errno;
+    if (rc == -EINTR || rc == -EINPROGRESS)
+      rc = 0;    /* The close is in progress, not an error. */
+    errno = saved_errno;
+  }
+
+  return rc;
+}
+
+
+int uv__close(int fd) {
+  assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
+  return uv__close_nocheckstdio(fd);
+}
+
+
+int uv__nonblock_ioctl(int fd, int set) {
+  int r;
+
+  do
+    r = ioctl(fd, FIONBIO, &set);
+  while (r == -1 && errno == EINTR);
+
+  if (r)
+    return -errno;
+
+  return 0;
+}
+
+
+int uv__cloexec_ioctl(int fd, int set) {
+  int r;
+
+  do
+    r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
+  while (r == -1 && errno == EINTR);
+
+  if (r)
+    return -errno;
+
+  return 0;
+}
+
+
+int uv__nonblock_fcntl(int fd, int set) {
+  int flags;
+  int r;
+
+  do
+    r = fcntl(fd, F_GETFL);
+  while (r == -1 && errno == EINTR);
+
+  if (r == -1)
+    return -errno;
+
+  /* Bail out now if already set/clear. */
+  if (!!(r & O_NONBLOCK) == !!set)
+    return 0;
+
+  if (set)
+    flags = r | O_NONBLOCK;
+  else
+    flags = r & ~O_NONBLOCK;
+
+  do
+    r = fcntl(fd, F_SETFL, flags);
+  while (r == -1 && errno == EINTR);
+
+  if (r)
+    return -errno;
+
+  return 0;
+}
+
+
+int uv__cloexec_fcntl(int fd, int set) {
+  int flags;
+  int r;
+
+  do
+    r = fcntl(fd, F_GETFD);
+  while (r == -1 && errno == EINTR);
+
+  if (r == -1)
+    return -errno;
+
+  /* Bail out now if already set/clear. */
+  if (!!(r & FD_CLOEXEC) == !!set)
+    return 0;
+
+  if (set)
+    flags = r | FD_CLOEXEC;
+  else
+    flags = r & ~FD_CLOEXEC;
+
+  do
+    r = fcntl(fd, F_SETFD, flags);
+  while (r == -1 && errno == EINTR);
+
+  if (r)
+    return -errno;
+
+  return 0;
+}
+
+
+/* This function is not execve-safe, there is a race window
+ * between the call to dup() and fcntl(FD_CLOEXEC).
+ */
+int uv__dup(int fd) {
+  int err;
+
+  fd = dup(fd);
+
+  if (fd == -1)
+    return -errno;
+
+  err = uv__cloexec(fd, 1);
+  if (err) {
+    uv__close(fd);
+    return err;
+  }
+
+  return fd;
+}
+
+
+ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
+  struct cmsghdr* cmsg;
+  ssize_t rc;
+  int* pfd;
+  int* end;
+#if defined(__linux__)
+  static int no_msg_cmsg_cloexec;
+  if (no_msg_cmsg_cloexec == 0) {
+    rc = recvmsg(fd, msg, flags | 0x40000000);  /* MSG_CMSG_CLOEXEC */
+    if (rc != -1)
+      return rc;
+    if (errno != EINVAL)
+      return -errno;
+    rc = recvmsg(fd, msg, flags);
+    if (rc == -1)
+      return -errno;
+    no_msg_cmsg_cloexec = 1;
+  } else {
+    rc = recvmsg(fd, msg, flags);
+  }
+#else
+  rc = recvmsg(fd, msg, flags);
+#endif
+  if (rc == -1)
+    return -errno;
+  if (msg->msg_controllen == 0)
+    return rc;
+  for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
+    if (cmsg->cmsg_type == SCM_RIGHTS)
+      for (pfd = (int*) CMSG_DATA(cmsg),
+           end = (int*) ((char*) cmsg + cmsg->cmsg_len);
+           pfd < end;
+           pfd += 1)
+        uv__cloexec(*pfd, 1);
+  return rc;
+}
+
+
+int uv_cwd(char* buffer, size_t* size) {
+  if (buffer == NULL || size == NULL)
+    return -EINVAL;
+
+  if (getcwd(buffer, *size) == NULL)
+    return -errno;
+
+  *size = strlen(buffer);
+  if (*size > 1 && buffer[*size - 1] == '/') {
+    buffer[*size-1] = '\0';
+    (*size)--;
+  }
+
+  return 0;
+}
+
+
+int uv_chdir(const char* dir) {
+  if (chdir(dir))
+    return -errno;
+
+  return 0;
+}
+
+
+void uv_disable_stdio_inheritance(void) {
+  int fd;
+
+  /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
+   * first 16 file descriptors. After that, bail out after the first error.
+   */
+  for (fd = 0; ; fd++)
+    if (uv__cloexec(fd, 1) && fd > 15)
+      break;
+}
+
+
+int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
+  int fd_out;
+
+  switch (handle->type) {
+  case UV_TCP:
+  case UV_NAMED_PIPE:
+  case UV_TTY:
+    fd_out = uv__stream_fd((uv_stream_t*) handle);
+    break;
+
+  case UV_UDP:
+    fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
+    break;
+
+  case UV_POLL:
+    fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
+    break;
+
+  default:
+    return -EINVAL;
+  }
+
+  if (uv__is_closing(handle) || fd_out == -1)
+    return -EBADF;
+
+  *fd = fd_out;
+  return 0;
+}
+
+
+static int uv__run_pending(uv_loop_t* loop) {
+  QUEUE* q;
+  QUEUE pq;
+  uv__io_t* w;
+
+  if (QUEUE_EMPTY(&loop->pending_queue))
+    return 0;
+
+  QUEUE_MOVE(&loop->pending_queue, &pq);
+
+  while (!QUEUE_EMPTY(&pq)) {
+    q = QUEUE_HEAD(&pq);
+    QUEUE_REMOVE(q);
+    QUEUE_INIT(q);
+    w = QUEUE_DATA(q, uv__io_t, pending_queue);
+    w->cb(loop, w, POLLOUT);
+  }
+
+  return 1;
+}
+
+
+static unsigned int next_power_of_two(unsigned int val) {
+  val -= 1;
+  val |= val >> 1;
+  val |= val >> 2;
+  val |= val >> 4;
+  val |= val >> 8;
+  val |= val >> 16;
+  val += 1;
+  return val;
+}
+
+static void maybe_resize(uv_loop_t* loop, unsigned int len) {
+  uv__io_t** watchers;
+  void* fake_watcher_list;
+  void* fake_watcher_count;
+  unsigned int nwatchers;
+  unsigned int i;
+
+  if (len <= loop->nwatchers)
+    return;
+
+  /* Preserve fake watcher list and count at the end of the watchers */
+  if (loop->watchers != NULL) {
+    fake_watcher_list = loop->watchers[loop->nwatchers];
+    fake_watcher_count = loop->watchers[loop->nwatchers + 1];
+  } else {
+    fake_watcher_list = NULL;
+    fake_watcher_count = NULL;
+  }
+
+  nwatchers = next_power_of_two(len + 2) - 2;
+  watchers = uv__realloc(loop->watchers,
+                         (nwatchers + 2) * sizeof(loop->watchers[0]));
+
+  if (watchers == NULL)
+    abort();
+  for (i = loop->nwatchers; i < nwatchers; i++)
+    watchers[i] = NULL;
+  watchers[nwatchers] = fake_watcher_list;
+  watchers[nwatchers + 1] = fake_watcher_count;
+
+  loop->watchers = watchers;
+  loop->nwatchers = nwatchers;
+}
+
+
+void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
+  assert(cb != NULL);
+  assert(fd >= -1);
+  QUEUE_INIT(&w->pending_queue);
+  QUEUE_INIT(&w->watcher_queue);
+  w->cb = cb;
+  w->fd = fd;
+  w->events = 0;
+  w->pevents = 0;
+
+#if defined(UV_HAVE_KQUEUE)
+  w->rcount = 0;
+  w->wcount = 0;
+#endif /* defined(UV_HAVE_KQUEUE) */
+}
+
+
+void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
+  assert(0 != events);
+  assert(w->fd >= 0);
+  assert(w->fd < INT_MAX);
+
+  w->pevents |= events;
+  maybe_resize(loop, w->fd + 1);
+
+#if !defined(__sun)
+  /* The event ports backend needs to rearm all file descriptors on each and
+   * every tick of the event loop but the other backends allow us to
+   * short-circuit here if the event mask is unchanged.
+   */
+  if (w->events == w->pevents) {
+    if (w->events == 0 && !QUEUE_EMPTY(&w->watcher_queue)) {
+      QUEUE_REMOVE(&w->watcher_queue);
+      QUEUE_INIT(&w->watcher_queue);
+    }
+    return;
+  }
+#endif
+
+  if (QUEUE_EMPTY(&w->watcher_queue))
+    QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
+
+  if (loop->watchers[w->fd] == NULL) {
+    loop->watchers[w->fd] = w;
+    loop->nfds++;
+  }
+}
+
+
+void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
+  assert(0 != events);
+
+  if (w->fd == -1)
+    return;
+
+  assert(w->fd >= 0);
+
+  /* Happens when uv__io_stop() is called on a handle that was never started. */
+  if ((unsigned) w->fd >= loop->nwatchers)
+    return;
+
+  w->pevents &= ~events;
+
+  if (w->pevents == 0) {
+    QUEUE_REMOVE(&w->watcher_queue);
+    QUEUE_INIT(&w->watcher_queue);
+
+    if (loop->watchers[w->fd] != NULL) {
+      assert(loop->watchers[w->fd] == w);
+      assert(loop->nfds > 0);
+      loop->watchers[w->fd] = NULL;
+      loop->nfds--;
+      w->events = 0;
+    }
+  }
+  else if (QUEUE_EMPTY(&w->watcher_queue))
+    QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
+}
+
+
+void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
+  uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP);
+  QUEUE_REMOVE(&w->pending_queue);
+
+  /* Remove stale events for this file descriptor */
+  uv__platform_invalidate_fd(loop, w->fd);
+}
+
+
+void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
+  if (QUEUE_EMPTY(&w->pending_queue))
+    QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
+}
+
+
+int uv__io_active(const uv__io_t* w, unsigned int events) {
+  assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
+  assert(0 != events);
+  return 0 != (w->pevents & events);
+}
+
+
+int uv_getrusage(uv_rusage_t* rusage) {
+  struct rusage usage;
+
+  if (getrusage(RUSAGE_SELF, &usage))
+    return -errno;
+
+  rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
+  rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
+
+  rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
+  rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
+
+#if !defined(__MVS__)
+  rusage->ru_maxrss = usage.ru_maxrss;
+  rusage->ru_ixrss = usage.ru_ixrss;
+  rusage->ru_idrss = usage.ru_idrss;
+  rusage->ru_isrss = usage.ru_isrss;
+  rusage->ru_minflt = usage.ru_minflt;
+  rusage->ru_majflt = usage.ru_majflt;
+  rusage->ru_nswap = usage.ru_nswap;
+  rusage->ru_inblock = usage.ru_inblock;
+  rusage->ru_oublock = usage.ru_oublock;
+  rusage->ru_msgsnd = usage.ru_msgsnd;
+  rusage->ru_msgrcv = usage.ru_msgrcv;
+  rusage->ru_nsignals = usage.ru_nsignals;
+  rusage->ru_nvcsw = usage.ru_nvcsw;
+  rusage->ru_nivcsw = usage.ru_nivcsw;
+#endif
+
+  return 0;
+}
+
+
+int uv__open_cloexec(const char* path, int flags) {
+  int err;
+  int fd;
+
+#if defined(UV__O_CLOEXEC)
+  static int no_cloexec;
+
+  if (!no_cloexec) {
+    fd = open(path, flags | UV__O_CLOEXEC);
+    if (fd != -1)
+      return fd;
+
+    if (errno != EINVAL)
+      return -errno;
+
+    /* O_CLOEXEC not supported. */
+    no_cloexec = 1;
+  }
+#endif
+
+  fd = open(path, flags);
+  if (fd == -1)
+    return -errno;
+
+  err = uv__cloexec(fd, 1);
+  if (err) {
+    uv__close(fd);
+    return err;
+  }
+
+  return fd;
+}
+
+
+int uv__dup2_cloexec(int oldfd, int newfd) {
+  int r;
+#if defined(__FreeBSD__) && __FreeBSD__ >= 10
+  r = dup3(oldfd, newfd, O_CLOEXEC);
+  if (r == -1)
+    return -errno;
+  return r;
+#elif defined(__FreeBSD__) && defined(F_DUP2FD_CLOEXEC)
+  r = fcntl(oldfd, F_DUP2FD_CLOEXEC, newfd);
+  if (r != -1)
+    return r;
+  if (errno != EINVAL)
+    return -errno;
+  /* Fall through. */
+#elif defined(__linux__)
+  static int no_dup3;
+  if (!no_dup3) {
+    do
+      r = uv__dup3(oldfd, newfd, UV__O_CLOEXEC);
+    while (r == -1 && errno == EBUSY);
+    if (r != -1)
+      return r;
+    if (errno != ENOSYS)
+      return -errno;
+    /* Fall through. */
+    no_dup3 = 1;
+  }
+#endif
+  {
+    int err;
+    do
+      r = dup2(oldfd, newfd);
+#if defined(__linux__)
+    while (r == -1 && errno == EBUSY);
+#else
+    while (0);  /* Never retry. */
+#endif
+
+    if (r == -1)
+      return -errno;
+
+    err = uv__cloexec(newfd, 1);
+    if (err) {
+      uv__close(newfd);
+      return err;
+    }
+
+    return r;
+  }
+}
+
+
+int uv_os_homedir(char* buffer, size_t* size) {
+  uv_passwd_t pwd;
+  char* buf;
+  size_t len;
+  int r;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  /* Check if the HOME environment variable is set first */
+  buf = getenv("HOME");
+
+  if (buf != NULL) {
+    len = strlen(buf);
+
+    if (len >= *size) {
+      *size = len + 1;
+      return -ENOBUFS;
+    }
+
+    memcpy(buffer, buf, len + 1);
+    *size = len;
+
+    return 0;
+  }
+
+  /* HOME is not set, so call uv__getpwuid_r() */
+  r = uv__getpwuid_r(&pwd);
+
+  if (r != 0) {
+    return r;
+  }
+
+  len = strlen(pwd.homedir);
+
+  if (len >= *size) {
+    *size = len + 1;
+    uv_os_free_passwd(&pwd);
+    return -ENOBUFS;
+  }
+
+  memcpy(buffer, pwd.homedir, len + 1);
+  *size = len;
+  uv_os_free_passwd(&pwd);
+
+  return 0;
+}
+
+
+int uv_os_tmpdir(char* buffer, size_t* size) {
+  const char* buf;
+  size_t len;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+#define CHECK_ENV_VAR(name)                                                   \
+  do {                                                                        \
+    buf = getenv(name);                                                       \
+    if (buf != NULL)                                                          \
+      goto return_buffer;                                                     \
+  }                                                                           \
+  while (0)
+
+  /* Check the TMPDIR, TMP, TEMP, and TEMPDIR environment variables in order */
+  CHECK_ENV_VAR("TMPDIR");
+  CHECK_ENV_VAR("TMP");
+  CHECK_ENV_VAR("TEMP");
+  CHECK_ENV_VAR("TEMPDIR");
+
+#undef CHECK_ENV_VAR
+
+  /* No temp environment variables defined */
+  #if defined(__ANDROID__)
+    buf = "/data/local/tmp";
+  #else
+    buf = "/tmp";
+  #endif
+
+return_buffer:
+  len = strlen(buf);
+
+  if (len >= *size) {
+    *size = len + 1;
+    return -ENOBUFS;
+  }
+
+  /* The returned directory should not have a trailing slash. */
+  if (len > 1 && buf[len - 1] == '/') {
+    len--;
+  }
+
+  memcpy(buffer, buf, len + 1);
+  buffer[len] = '\0';
+  *size = len;
+
+  return 0;
+}
+
+
+int uv__getpwuid_r(uv_passwd_t* pwd) {
+  struct passwd pw;
+  struct passwd* result;
+  char* buf;
+  uid_t uid;
+  size_t bufsize;
+  size_t name_size;
+  size_t homedir_size;
+  size_t shell_size;
+  long initsize;
+  int r;
+#if defined(__ANDROID_API__) && __ANDROID_API__ < 21
+  int (*getpwuid_r)(uid_t, struct passwd*, char*, size_t, struct passwd**);
+
+  getpwuid_r = dlsym(RTLD_DEFAULT, "getpwuid_r");
+  if (getpwuid_r == NULL)
+    return -ENOSYS;
+#endif
+
+  if (pwd == NULL)
+    return -EINVAL;
+
+  initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
+
+  if (initsize <= 0)
+    bufsize = 4096;
+  else
+    bufsize = (size_t) initsize;
+
+  uid = geteuid();
+  buf = NULL;
+
+  for (;;) {
+    uv__free(buf);
+    buf = uv__malloc(bufsize);
+
+    if (buf == NULL)
+      return -ENOMEM;
+
+    r = getpwuid_r(uid, &pw, buf, bufsize, &result);
+
+    if (r != ERANGE)
+      break;
+
+    bufsize *= 2;
+  }
+
+  if (r != 0) {
+    uv__free(buf);
+    return -r;
+  }
+
+  if (result == NULL) {
+    uv__free(buf);
+    return -ENOENT;
+  }
+
+  /* Allocate memory for the username, shell, and home directory */
+  name_size = strlen(pw.pw_name) + 1;
+  homedir_size = strlen(pw.pw_dir) + 1;
+  shell_size = strlen(pw.pw_shell) + 1;
+  pwd->username = uv__malloc(name_size + homedir_size + shell_size);
+
+  if (pwd->username == NULL) {
+    uv__free(buf);
+    return -ENOMEM;
+  }
+
+  /* Copy the username */
+  memcpy(pwd->username, pw.pw_name, name_size);
+
+  /* Copy the home directory */
+  pwd->homedir = pwd->username + name_size;
+  memcpy(pwd->homedir, pw.pw_dir, homedir_size);
+
+  /* Copy the shell */
+  pwd->shell = pwd->homedir + homedir_size;
+  memcpy(pwd->shell, pw.pw_shell, shell_size);
+
+  /* Copy the uid and gid */
+  pwd->uid = pw.pw_uid;
+  pwd->gid = pw.pw_gid;
+
+  uv__free(buf);
+
+  return 0;
+}
+
+
+void uv_os_free_passwd(uv_passwd_t* pwd) {
+  if (pwd == NULL)
+    return;
+
+  /*
+    The memory for name, shell, and homedir are allocated in a single
+    uv__malloc() call. The base of the pointer is stored in pwd->username, so
+    that is the field that needs to be freed.
+  */
+  uv__free(pwd->username);
+  pwd->username = NULL;
+  pwd->shell = NULL;
+  pwd->homedir = NULL;
+}
+
+
+int uv_os_get_passwd(uv_passwd_t* pwd) {
+  return uv__getpwuid_r(pwd);
+}
diff --git a/Utilities/cmlibuv/src/unix/darwin-proctitle.c b/Utilities/cmlibuv/src/unix/darwin-proctitle.c
new file mode 100644
index 0000000..1142311
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/darwin-proctitle.c
@@ -0,0 +1,206 @@
+/* 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 <dlfcn.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <TargetConditionals.h>
+
+#if !TARGET_OS_IPHONE
+# include <CoreFoundation/CoreFoundation.h>
+# include <ApplicationServices/ApplicationServices.h>
+#endif
+
+
+static int uv__pthread_setname_np(const char* name) {
+  int (*dynamic_pthread_setname_np)(const char* name);
+  char namebuf[64];  /* MAXTHREADNAMESIZE */
+  int err;
+
+  /* pthread_setname_np() first appeared in OS X 10.6 and iOS 3.2. */
+  *(void **)(&dynamic_pthread_setname_np) =
+      dlsym(RTLD_DEFAULT, "pthread_setname_np");
+
+  if (dynamic_pthread_setname_np == NULL)
+    return -ENOSYS;
+
+  strncpy(namebuf, name, sizeof(namebuf) - 1);
+  namebuf[sizeof(namebuf) - 1] = '\0';
+
+  err = dynamic_pthread_setname_np(namebuf);
+  if (err)
+    return -err;
+
+  return 0;
+}
+
+
+int uv__set_process_title(const char* title) {
+#if TARGET_OS_IPHONE
+  return uv__pthread_setname_np(title);
+#else
+  CFStringRef (*pCFStringCreateWithCString)(CFAllocatorRef,
+                                            const char*,
+                                            CFStringEncoding);
+  CFBundleRef (*pCFBundleGetBundleWithIdentifier)(CFStringRef);
+  void *(*pCFBundleGetDataPointerForName)(CFBundleRef, CFStringRef);
+  void *(*pCFBundleGetFunctionPointerForName)(CFBundleRef, CFStringRef);
+  CFTypeRef (*pLSGetCurrentApplicationASN)(void);
+  OSStatus (*pLSSetApplicationInformationItem)(int,
+                                               CFTypeRef,
+                                               CFStringRef,
+                                               CFStringRef,
+                                               CFDictionaryRef*);
+  void* application_services_handle;
+  void* core_foundation_handle;
+  CFBundleRef launch_services_bundle;
+  CFStringRef* display_name_key;
+  CFDictionaryRef (*pCFBundleGetInfoDictionary)(CFBundleRef);
+  CFBundleRef (*pCFBundleGetMainBundle)(void);
+  CFBundleRef hi_services_bundle;
+  OSStatus (*pSetApplicationIsDaemon)(int);
+  CFDictionaryRef (*pLSApplicationCheckIn)(int, CFDictionaryRef);
+  void (*pLSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t,
+                                                                void*);
+  CFTypeRef asn;
+  int err;
+
+  err = -ENOENT;
+  application_services_handle = dlopen("/System/Library/Frameworks/"
+                                       "ApplicationServices.framework/"
+                                       "Versions/A/ApplicationServices",
+                                       RTLD_LAZY | RTLD_LOCAL);
+  core_foundation_handle = dlopen("/System/Library/Frameworks/"
+                                  "CoreFoundation.framework/"
+                                  "Versions/A/CoreFoundation",
+                                  RTLD_LAZY | RTLD_LOCAL);
+
+  if (application_services_handle == NULL || core_foundation_handle == NULL)
+    goto out;
+
+  *(void **)(&pCFStringCreateWithCString) =
+      dlsym(core_foundation_handle, "CFStringCreateWithCString");
+  *(void **)(&pCFBundleGetBundleWithIdentifier) =
+      dlsym(core_foundation_handle, "CFBundleGetBundleWithIdentifier");
+  *(void **)(&pCFBundleGetDataPointerForName) =
+      dlsym(core_foundation_handle, "CFBundleGetDataPointerForName");
+  *(void **)(&pCFBundleGetFunctionPointerForName) =
+      dlsym(core_foundation_handle, "CFBundleGetFunctionPointerForName");
+
+  if (pCFStringCreateWithCString == NULL ||
+      pCFBundleGetBundleWithIdentifier == NULL ||
+      pCFBundleGetDataPointerForName == NULL ||
+      pCFBundleGetFunctionPointerForName == NULL) {
+    goto out;
+  }
+
+#define S(s) pCFStringCreateWithCString(NULL, (s), kCFStringEncodingUTF8)
+
+  launch_services_bundle =
+      pCFBundleGetBundleWithIdentifier(S("com.apple.LaunchServices"));
+
+  if (launch_services_bundle == NULL)
+    goto out;
+
+  *(void **)(&pLSGetCurrentApplicationASN) =
+      pCFBundleGetFunctionPointerForName(launch_services_bundle,
+                                         S("_LSGetCurrentApplicationASN"));
+
+  if (pLSGetCurrentApplicationASN == NULL)
+    goto out;
+
+  *(void **)(&pLSSetApplicationInformationItem) =
+      pCFBundleGetFunctionPointerForName(launch_services_bundle,
+                                         S("_LSSetApplicationInformationItem"));
+
+  if (pLSSetApplicationInformationItem == NULL)
+    goto out;
+
+  display_name_key = pCFBundleGetDataPointerForName(launch_services_bundle,
+                                                    S("_kLSDisplayNameKey"));
+
+  if (display_name_key == NULL || *display_name_key == NULL)
+    goto out;
+
+  *(void **)(&pCFBundleGetInfoDictionary) = dlsym(core_foundation_handle,
+                                     "CFBundleGetInfoDictionary");
+  *(void **)(&pCFBundleGetMainBundle) = dlsym(core_foundation_handle,
+                                 "CFBundleGetMainBundle");
+  if (pCFBundleGetInfoDictionary == NULL || pCFBundleGetMainBundle == NULL)
+    goto out;
+
+  /* Black 10.9 magic, to remove (Not responding) mark in Activity Monitor */
+  hi_services_bundle =
+      pCFBundleGetBundleWithIdentifier(S("com.apple.HIServices"));
+  err = -ENOENT;
+  if (hi_services_bundle == NULL)
+    goto out;
+
+  *(void **)(&pSetApplicationIsDaemon) = pCFBundleGetFunctionPointerForName(
+      hi_services_bundle,
+      S("SetApplicationIsDaemon"));
+  *(void **)(&pLSApplicationCheckIn) = pCFBundleGetFunctionPointerForName(
+      launch_services_bundle,
+      S("_LSApplicationCheckIn"));
+  *(void **)(&pLSSetApplicationLaunchServicesServerConnectionStatus) =
+      pCFBundleGetFunctionPointerForName(
+          launch_services_bundle,
+          S("_LSSetApplicationLaunchServicesServerConnectionStatus"));
+  if (pSetApplicationIsDaemon == NULL ||
+      pLSApplicationCheckIn == NULL ||
+      pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) {
+    goto out;
+  }
+
+  if (pSetApplicationIsDaemon(1) != noErr)
+    goto out;
+
+  pLSSetApplicationLaunchServicesServerConnectionStatus(0, NULL);
+
+  /* Check into process manager?! */
+  pLSApplicationCheckIn(-2,
+                        pCFBundleGetInfoDictionary(pCFBundleGetMainBundle()));
+
+  asn = pLSGetCurrentApplicationASN();
+
+  err = -EINVAL;
+  if (pLSSetApplicationInformationItem(-2,  /* Magic value. */
+                                       asn,
+                                       *display_name_key,
+                                       S(title),
+                                       NULL) != noErr) {
+    goto out;
+  }
+
+  uv__pthread_setname_np(title);  /* Don't care if it fails. */
+  err = 0;
+
+out:
+  if (core_foundation_handle != NULL)
+    dlclose(core_foundation_handle);
+
+  if (application_services_handle != NULL)
+    dlclose(application_services_handle);
+
+  return err;
+#endif  /* !TARGET_OS_IPHONE */
+}
diff --git a/Utilities/cmlibuv/src/unix/darwin.c b/Utilities/cmlibuv/src/unix/darwin.c
new file mode 100644
index 0000000..cf95da2
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/darwin.c
@@ -0,0 +1,335 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <stdint.h>
+#include <errno.h>
+
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+#include <mach-o/dyld.h> /* _NSGetExecutablePath */
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+#include <unistd.h>  /* sysconf */
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  loop->cf_state = NULL;
+
+  if (uv__kqueue_init(loop))
+    return -errno;
+
+  return 0;
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+  uv__fsevents_loop_delete(loop);
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  static mach_timebase_info_data_t info;
+
+  if ((ACCESS_ONCE(uint32_t, info.numer) == 0 ||
+       ACCESS_ONCE(uint32_t, info.denom) == 0) &&
+      mach_timebase_info(&info) != KERN_SUCCESS)
+    abort();
+
+  return mach_absolute_time() * info.numer / info.denom;
+}
+
+
+int uv_exepath(char* buffer, size_t* size) {
+  /* realpath(exepath) may be > PATH_MAX so double it to be on the safe side. */
+  char abspath[PATH_MAX * 2 + 1];
+  char exepath[PATH_MAX + 1];
+  uint32_t exepath_size;
+  size_t abspath_size;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  exepath_size = sizeof(exepath);
+  if (_NSGetExecutablePath(exepath, &exepath_size))
+    return -EIO;
+
+  if (realpath(exepath, abspath) != abspath)
+    return -errno;
+
+  abspath_size = strlen(abspath);
+  if (abspath_size == 0)
+    return -EIO;
+
+  *size -= 1;
+  if (*size > abspath_size)
+    *size = abspath_size;
+
+  memcpy(buffer, abspath, *size);
+  buffer[*size] = '\0';
+
+  return 0;
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  vm_statistics_data_t info;
+  mach_msg_type_number_t count = sizeof(info) / sizeof(integer_t);
+
+  if (host_statistics(mach_host_self(), HOST_VM_INFO,
+                      (host_info_t)&info, &count) != KERN_SUCCESS) {
+    return -EINVAL;  /* FIXME(bnoordhuis) Translate error. */
+  }
+
+  return (uint64_t) info.free_count * sysconf(_SC_PAGESIZE);
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  uint64_t info;
+  int which[] = {CTL_HW, HW_MEMSIZE};
+  size_t size = sizeof(info);
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info;
+}
+
+
+void uv_loadavg(double avg[3]) {
+  struct loadavg info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_LOADAVG};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0) < 0) return;
+
+  avg[0] = (double) info.ldavg[0] / info.fscale;
+  avg[1] = (double) info.ldavg[1] / info.fscale;
+  avg[2] = (double) info.ldavg[2] / info.fscale;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  mach_msg_type_number_t count;
+  task_basic_info_data_t info;
+  kern_return_t err;
+
+  count = TASK_BASIC_INFO_COUNT;
+  err = task_info(mach_task_self(),
+                  TASK_BASIC_INFO,
+                  (task_info_t) &info,
+                  &count);
+  (void) &err;
+  /* task_info(TASK_BASIC_INFO) cannot really fail. Anything other than
+   * KERN_SUCCESS implies a libuv bug.
+   */
+  assert(err == KERN_SUCCESS);
+  *rss = info.resident_size;
+
+  return 0;
+}
+
+
+int uv_uptime(double* uptime) {
+  time_t now;
+  struct timeval info;
+  size_t size = sizeof(info);
+  static int which[] = {CTL_KERN, KERN_BOOTTIME};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  now = time(NULL);
+  *uptime = now - info.tv_sec;
+
+  return 0;
+}
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK),
+               multiplier = ((uint64_t)1000L / ticks);
+  char model[512];
+  uint64_t cpuspeed;
+  size_t size;
+  unsigned int i;
+  natural_t numcpus;
+  mach_msg_type_number_t msg_type;
+  processor_cpu_load_info_data_t *info;
+  uv_cpu_info_t* cpu_info;
+
+  size = sizeof(model);
+  if (sysctlbyname("machdep.cpu.brand_string", &model, &size, NULL, 0) &&
+      sysctlbyname("hw.model", &model, &size, NULL, 0)) {
+    return -errno;
+  }
+
+  size = sizeof(cpuspeed);
+  if (sysctlbyname("hw.cpufrequency", &cpuspeed, &size, NULL, 0))
+    return -errno;
+
+  if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numcpus,
+                          (processor_info_array_t*)&info,
+                          &msg_type) != KERN_SUCCESS) {
+    return -EINVAL;  /* FIXME(bnoordhuis) Translate error. */
+  }
+
+  *cpu_infos = uv__malloc(numcpus * sizeof(**cpu_infos));
+  if (!(*cpu_infos)) {
+    vm_deallocate(mach_task_self(), (vm_address_t)info, msg_type);
+    return -ENOMEM;
+  }
+
+  *count = numcpus;
+
+  for (i = 0; i < numcpus; i++) {
+    cpu_info = &(*cpu_infos)[i];
+
+    cpu_info->cpu_times.user = (uint64_t)(info[i].cpu_ticks[0]) * multiplier;
+    cpu_info->cpu_times.nice = (uint64_t)(info[i].cpu_ticks[3]) * multiplier;
+    cpu_info->cpu_times.sys = (uint64_t)(info[i].cpu_ticks[1]) * multiplier;
+    cpu_info->cpu_times.idle = (uint64_t)(info[i].cpu_ticks[2]) * multiplier;
+    cpu_info->cpu_times.irq = 0;
+
+    cpu_info->model = uv__strdup(model);
+    cpu_info->speed = cpuspeed/1000000;
+  }
+  vm_deallocate(mach_task_self(), (vm_address_t)info, msg_type);
+
+  return 0;
+}
+
+
+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) {
+  struct ifaddrs *addrs, *ent;
+  uv_interface_address_t* address;
+  int i;
+  struct sockaddr_dl *sa_addr;
+
+  if (getifaddrs(&addrs))
+    return -errno;
+
+  *count = 0;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family == AF_LINK)) {
+      continue;
+    }
+
+    (*count)++;
+  }
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    /*
+     * On Mac OS X getifaddrs returns information related to Mac Addresses for
+     * various devices, such as firewire, etc. These are not relevant here.
+     */
+    if (ent->ifa_addr->sa_family == AF_LINK)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
+
+    address++;
+  }
+
+  /* Fill in physical addresses for each interface */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != AF_LINK)) {
+      continue;
+    }
+
+    address = *addresses;
+
+    for (i = 0; i < (*count); i++) {
+      if (strcmp(address->name, ent->ifa_name) == 0) {
+        sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
+        memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+      }
+      address++;
+    }
+  }
+
+  freeifaddrs(addrs);
+
+  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/dl.c b/Utilities/cmlibuv/src/unix/dl.c
new file mode 100644
index 0000000..fc1c052
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/dl.c
@@ -0,0 +1,80 @@
+/* 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 "internal.h"
+
+#include <dlfcn.h>
+#include <errno.h>
+#include <string.h>
+#include <locale.h>
+
+static int uv__dlerror(uv_lib_t* lib);
+
+
+int uv_dlopen(const char* filename, uv_lib_t* lib) {
+  dlerror(); /* Reset error status. */
+  lib->errmsg = NULL;
+  lib->handle = dlopen(filename, RTLD_LAZY);
+  return lib->handle ? 0 : uv__dlerror(lib);
+}
+
+
+void uv_dlclose(uv_lib_t* lib) {
+  uv__free(lib->errmsg);
+  lib->errmsg = NULL;
+
+  if (lib->handle) {
+    /* Ignore errors. No good way to signal them without leaking memory. */
+    dlclose(lib->handle);
+    lib->handle = NULL;
+  }
+}
+
+
+int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr) {
+  dlerror(); /* Reset error status. */
+  *ptr = dlsym(lib->handle, name);
+  return uv__dlerror(lib);
+}
+
+
+const char* uv_dlerror(const uv_lib_t* lib) {
+  return lib->errmsg ? lib->errmsg : "no error";
+}
+
+
+static int uv__dlerror(uv_lib_t* lib) {
+  const char* errmsg;
+
+  uv__free(lib->errmsg);
+
+  errmsg = dlerror();
+
+  if (errmsg) {
+    lib->errmsg = uv__strdup(errmsg);
+    return -1;
+  }
+  else {
+    lib->errmsg = NULL;
+    return 0;
+  }
+}
diff --git a/Utilities/cmlibuv/src/unix/freebsd.c b/Utilities/cmlibuv/src/unix/freebsd.c
new file mode 100644
index 0000000..cba44a3
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/freebsd.c
@@ -0,0 +1,460 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+
+#include <kvm.h>
+#include <paths.h>
+#include <sys/user.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+#include <vm/vm_param.h> /* VM_LOADAVG */
+#include <time.h>
+#include <stdlib.h>
+#include <unistd.h> /* sysconf */
+#include <fcntl.h>
+
+#undef NANOSEC
+#define NANOSEC ((uint64_t) 1e9)
+
+#ifndef CPUSTATES
+# define CPUSTATES 5U
+#endif
+#ifndef CP_USER
+# define CP_USER 0
+# define CP_NICE 1
+# define CP_SYS 2
+# define CP_IDLE 3
+# define CP_INTR 4
+#endif
+
+static char *process_title;
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  return uv__kqueue_init(loop);
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
+}
+
+
+#ifdef __DragonFly__
+int uv_exepath(char* buffer, size_t* size) {
+  char abspath[PATH_MAX * 2 + 1];
+  ssize_t abspath_size;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  abspath_size = readlink("/proc/curproc/file", abspath, sizeof(abspath));
+  if (abspath_size < 0)
+    return -errno;
+
+  assert(abspath_size > 0);
+  *size -= 1;
+
+  if (*size > abspath_size)
+    *size = abspath_size;
+
+  memcpy(buffer, abspath, *size);
+  buffer[*size] = '\0';
+
+  return 0;
+}
+#else
+int uv_exepath(char* buffer, size_t* size) {
+  char abspath[PATH_MAX * 2 + 1];
+  int mib[4];
+  size_t abspath_size;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  mib[0] = CTL_KERN;
+  mib[1] = KERN_PROC;
+  mib[2] = KERN_PROC_PATHNAME;
+  mib[3] = -1;
+
+  abspath_size = sizeof abspath;
+  if (sysctl(mib, 4, abspath, &abspath_size, NULL, 0))
+    return -errno;
+
+  assert(abspath_size > 0);
+  abspath_size -= 1;
+  *size -= 1;
+
+  if (*size > abspath_size)
+    *size = abspath_size;
+
+  memcpy(buffer, abspath, *size);
+  buffer[*size] = '\0';
+
+  return 0;
+}
+#endif
+
+uint64_t uv_get_free_memory(void) {
+  int freecount;
+  size_t size = sizeof(freecount);
+
+  if (sysctlbyname("vm.stats.vm.v_free_count", &freecount, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) freecount * sysconf(_SC_PAGESIZE);
+
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  unsigned long info;
+  int which[] = {CTL_HW, HW_PHYSMEM};
+
+  size_t size = sizeof(info);
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info;
+}
+
+
+void uv_loadavg(double avg[3]) {
+  struct loadavg info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_LOADAVG};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0) < 0) return;
+
+  avg[0] = (double) info.ldavg[0] / info.fscale;
+  avg[1] = (double) info.ldavg[1] / info.fscale;
+  avg[2] = (double) info.ldavg[2] / info.fscale;
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+  process_title = argc ? uv__strdup(argv[0]) : NULL;
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  int oid[4];
+
+  uv__free(process_title);
+  process_title = uv__strdup(title);
+
+  oid[0] = CTL_KERN;
+  oid[1] = KERN_PROC;
+  oid[2] = KERN_PROC_ARGS;
+  oid[3] = getpid();
+
+  sysctl(oid,
+         ARRAY_SIZE(oid),
+         NULL,
+         NULL,
+         process_title,
+         strlen(process_title) + 1);
+
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  size_t len;
+
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+
+  if (process_title) {
+    len = strlen(process_title) + 1;
+
+    if (size < len)
+      return -ENOBUFS;
+
+    memcpy(buffer, process_title, len);
+  } else {
+    len = 0;
+  }
+
+  buffer[len] = '\0';
+
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  kvm_t *kd = NULL;
+  struct kinfo_proc *kinfo = NULL;
+  pid_t pid;
+  int nprocs;
+  size_t page_size = getpagesize();
+
+  pid = getpid();
+
+  kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
+  if (kd == NULL) goto error;
+
+  kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
+  if (kinfo == NULL) goto error;
+
+#ifdef __DragonFly__
+  *rss = kinfo->kp_vm_rssize * page_size;
+#else
+  *rss = kinfo->ki_rssize * page_size;
+#endif
+
+  kvm_close(kd);
+
+  return 0;
+
+error:
+  if (kd) kvm_close(kd);
+  return -EPERM;
+}
+
+
+int uv_uptime(double* uptime) {
+  int r;
+  struct timespec sp;
+  r = clock_gettime(CLOCK_MONOTONIC, &sp);
+  if (r)
+    return -errno;
+
+  *uptime = sp.tv_sec;
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK),
+               multiplier = ((uint64_t)1000L / ticks), cpuspeed, maxcpus,
+               cur = 0;
+  uv_cpu_info_t* cpu_info;
+  const char* maxcpus_key;
+  const char* cptimes_key;
+  char model[512];
+  long* cp_times;
+  int numcpus;
+  size_t size;
+  int i;
+
+#if defined(__DragonFly__)
+  /* This is not quite correct but DragonFlyBSD doesn't seem to have anything
+   * comparable to kern.smp.maxcpus or kern.cp_times (kern.cp_time is a total,
+   * not per CPU). At least this stops uv_cpu_info() from failing completely.
+   */
+  maxcpus_key = "hw.ncpu";
+  cptimes_key = "kern.cp_time";
+#else
+  maxcpus_key = "kern.smp.maxcpus";
+  cptimes_key = "kern.cp_times";
+#endif
+
+  size = sizeof(model);
+  if (sysctlbyname("hw.model", &model, &size, NULL, 0))
+    return -errno;
+
+  size = sizeof(numcpus);
+  if (sysctlbyname("hw.ncpu", &numcpus, &size, NULL, 0))
+    return -errno;
+
+  *cpu_infos = uv__malloc(numcpus * sizeof(**cpu_infos));
+  if (!(*cpu_infos))
+    return -ENOMEM;
+
+  *count = numcpus;
+
+  size = sizeof(cpuspeed);
+  if (sysctlbyname("hw.clockrate", &cpuspeed, &size, NULL, 0)) {
+    uv__free(*cpu_infos);
+    return -errno;
+  }
+
+  /* kern.cp_times on FreeBSD i386 gives an array up to maxcpus instead of
+   * ncpu.
+   */
+  size = sizeof(maxcpus);
+  if (sysctlbyname(maxcpus_key, &maxcpus, &size, NULL, 0)) {
+    uv__free(*cpu_infos);
+    return -errno;
+  }
+
+  size = maxcpus * CPUSTATES * sizeof(long);
+
+  cp_times = uv__malloc(size);
+  if (cp_times == NULL) {
+    uv__free(*cpu_infos);
+    return -ENOMEM;
+  }
+
+  if (sysctlbyname(cptimes_key, cp_times, &size, NULL, 0)) {
+    uv__free(cp_times);
+    uv__free(*cpu_infos);
+    return -errno;
+  }
+
+  for (i = 0; i < numcpus; i++) {
+    cpu_info = &(*cpu_infos)[i];
+
+    cpu_info->cpu_times.user = (uint64_t)(cp_times[CP_USER+cur]) * multiplier;
+    cpu_info->cpu_times.nice = (uint64_t)(cp_times[CP_NICE+cur]) * multiplier;
+    cpu_info->cpu_times.sys = (uint64_t)(cp_times[CP_SYS+cur]) * multiplier;
+    cpu_info->cpu_times.idle = (uint64_t)(cp_times[CP_IDLE+cur]) * multiplier;
+    cpu_info->cpu_times.irq = (uint64_t)(cp_times[CP_INTR+cur]) * multiplier;
+
+    cpu_info->model = uv__strdup(model);
+    cpu_info->speed = cpuspeed;
+
+    cur+=CPUSTATES;
+  }
+
+  uv__free(cp_times);
+  return 0;
+}
+
+
+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) {
+  struct ifaddrs *addrs, *ent;
+  uv_interface_address_t* address;
+  int i;
+  struct sockaddr_dl *sa_addr;
+
+  if (getifaddrs(&addrs))
+    return -errno;
+
+   *count = 0;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family == AF_LINK)) {
+      continue;
+    }
+
+    (*count)++;
+  }
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    /*
+     * On FreeBSD getifaddrs returns information related to the raw underlying
+     * devices. We're not interested in this information yet.
+     */
+    if (ent->ifa_addr->sa_family == AF_LINK)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
+
+    address++;
+  }
+
+  /* Fill in physical addresses for each interface */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != AF_LINK)) {
+      continue;
+    }
+
+    address = *addresses;
+
+    for (i = 0; i < (*count); i++) {
+      if (strcmp(address->name, ent->ifa_name) == 0) {
+        sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
+        memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+      }
+      address++;
+    }
+  }
+
+  freeifaddrs(addrs);
+
+  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/fs.c b/Utilities/cmlibuv/src/unix/fs.c
new file mode 100644
index 0000000..3d478b7
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/fs.c
@@ -0,0 +1,1364 @@
+/* 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.
+ */
+
+/* Caveat emptor: this file deviates from the libuv convention of returning
+ * negated errno codes. Most uv_fs_*() functions map directly to the system
+ * call of the same name. For more complex wrappers, it's easier to just
+ * return -1 with errno set. The dispatcher in uv__fs_work() takes care of
+ * getting the errno to the right place (req->result or as the return value.)
+ */
+
+#include "uv.h"
+#include "internal.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h> /* PATH_MAX */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <utime.h>
+#include <poll.h>
+
+#if defined(__DragonFly__)        ||                                      \
+    defined(__FreeBSD__)          ||                                      \
+    defined(__FreeBSD_kernel_)    ||                                      \
+    defined(__OpenBSD__)          ||                                      \
+    defined(__NetBSD__)
+# define HAVE_PREADV 1
+#else
+# define HAVE_PREADV 0
+#endif
+
+#if defined(__linux__) || defined(__sun)
+# include <sys/sendfile.h>
+#endif
+
+#define INIT(subtype)                                                         \
+  do {                                                                        \
+    req->type = UV_FS;                                                        \
+    if (cb != NULL)                                                           \
+      uv__req_init(loop, req, UV_FS);                                         \
+    req->fs_type = UV_FS_ ## subtype;                                         \
+    req->result = 0;                                                          \
+    req->ptr = NULL;                                                          \
+    req->loop = loop;                                                         \
+    req->path = NULL;                                                         \
+    req->new_path = NULL;                                                     \
+    req->cb = cb;                                                             \
+  }                                                                           \
+  while (0)
+
+#define PATH                                                                  \
+  do {                                                                        \
+    assert(path != NULL);                                                     \
+    if (cb == NULL) {                                                         \
+      req->path = path;                                                       \
+    } else {                                                                  \
+      req->path = uv__strdup(path);                                           \
+      if (req->path == NULL) {                                                \
+        uv__req_unregister(loop, req);                                        \
+        return -ENOMEM;                                                       \
+      }                                                                       \
+    }                                                                         \
+  }                                                                           \
+  while (0)
+
+#define PATH2                                                                 \
+  do {                                                                        \
+    if (cb == NULL) {                                                         \
+      req->path = path;                                                       \
+      req->new_path = new_path;                                               \
+    } else {                                                                  \
+      size_t path_len;                                                        \
+      size_t new_path_len;                                                    \
+      path_len = strlen(path) + 1;                                            \
+      new_path_len = strlen(new_path) + 1;                                    \
+      req->path = uv__malloc(path_len + new_path_len);                        \
+      if (req->path == NULL) {                                                \
+        uv__req_unregister(loop, req);                                        \
+        return -ENOMEM;                                                       \
+      }                                                                       \
+      req->new_path = req->path + path_len;                                   \
+      memcpy((void*) req->path, path, path_len);                              \
+      memcpy((void*) req->new_path, new_path, new_path_len);                  \
+    }                                                                         \
+  }                                                                           \
+  while (0)
+
+#define POST                                                                  \
+  do {                                                                        \
+    if (cb != NULL) {                                                         \
+      uv__work_submit(loop, &req->work_req, uv__fs_work, uv__fs_done);        \
+      return 0;                                                               \
+    }                                                                         \
+    else {                                                                    \
+      uv__fs_work(&req->work_req);                                            \
+      return req->result;                                                     \
+    }                                                                         \
+  }                                                                           \
+  while (0)
+
+
+static ssize_t uv__fs_fdatasync(uv_fs_t* req) {
+#if defined(__linux__) || defined(__sun) || defined(__NetBSD__)
+  return fdatasync(req->file);
+#elif defined(__APPLE__) && defined(SYS_fdatasync)
+  return syscall(SYS_fdatasync, req->file);
+#else
+  return fsync(req->file);
+#endif
+}
+
+
+static ssize_t uv__fs_futime(uv_fs_t* req) {
+#if defined(__linux__)
+  /* utimesat() has nanosecond resolution but we stick to microseconds
+   * for the sake of consistency with other platforms.
+   */
+  static int no_utimesat;
+  struct timespec ts[2];
+  struct timeval tv[2];
+  char path[sizeof("/proc/self/fd/") + 3 * sizeof(int)];
+  int r;
+
+  if (no_utimesat)
+    goto skip;
+
+  ts[0].tv_sec  = req->atime;
+  ts[0].tv_nsec = (uint64_t)(req->atime * 1000000) % 1000000 * 1000;
+  ts[1].tv_sec  = req->mtime;
+  ts[1].tv_nsec = (uint64_t)(req->mtime * 1000000) % 1000000 * 1000;
+
+  r = uv__utimesat(req->file, NULL, ts, 0);
+  if (r == 0)
+    return r;
+
+  if (errno != ENOSYS)
+    return r;
+
+  no_utimesat = 1;
+
+skip:
+
+  tv[0].tv_sec  = req->atime;
+  tv[0].tv_usec = (uint64_t)(req->atime * 1000000) % 1000000;
+  tv[1].tv_sec  = req->mtime;
+  tv[1].tv_usec = (uint64_t)(req->mtime * 1000000) % 1000000;
+  snprintf(path, sizeof(path), "/proc/self/fd/%d", (int) req->file);
+
+  r = utimes(path, tv);
+  if (r == 0)
+    return r;
+
+  switch (errno) {
+  case ENOENT:
+    if (fcntl(req->file, F_GETFL) == -1 && errno == EBADF)
+      break;
+    /* Fall through. */
+
+  case EACCES:
+  case ENOTDIR:
+    errno = ENOSYS;
+    break;
+  }
+
+  return r;
+
+#elif defined(__APPLE__)                                                      \
+    || defined(__DragonFly__)                                                 \
+    || defined(__FreeBSD__)                                                   \
+    || defined(__FreeBSD_kernel__)                                            \
+    || defined(__NetBSD__)                                                    \
+    || defined(__OpenBSD__)                                                   \
+    || defined(__sun)
+  struct timeval tv[2];
+  tv[0].tv_sec  = req->atime;
+  tv[0].tv_usec = (uint64_t)(req->atime * 1000000) % 1000000;
+  tv[1].tv_sec  = req->mtime;
+  tv[1].tv_usec = (uint64_t)(req->mtime * 1000000) % 1000000;
+# if defined(__sun)
+  return futimesat(req->file, NULL, tv);
+# else
+  return futimes(req->file, tv);
+# endif
+#elif defined(_AIX71)
+  struct timespec ts[2];
+  ts[0].tv_sec  = req->atime;
+  ts[0].tv_nsec = (uint64_t)(req->atime * 1000000) % 1000000 * 1000;
+  ts[1].tv_sec  = req->mtime;
+  ts[1].tv_nsec = (uint64_t)(req->mtime * 1000000) % 1000000 * 1000;
+  return futimens(req->file, ts);
+#elif defined(__MVS__)
+  attrib_t atr;
+  memset(&atr, 0, sizeof(atr));
+  atr.att_mtimechg = 1;
+  atr.att_atimechg = 1;
+  atr.att_mtime = req->mtime;
+  atr.att_atime = req->atime;
+  return __fchattr(req->file, &atr, sizeof(atr));
+#else
+  errno = ENOSYS;
+  return -1;
+#endif
+}
+
+
+static ssize_t uv__fs_mkdtemp(uv_fs_t* req) {
+  return mkdtemp((char*) req->path) ? 0 : -1;
+}
+
+
+static ssize_t uv__fs_open(uv_fs_t* req) {
+  static int no_cloexec_support;
+  int r;
+
+  /* Try O_CLOEXEC before entering locks */
+  if (no_cloexec_support == 0) {
+#ifdef O_CLOEXEC
+    r = open(req->path, req->flags | O_CLOEXEC, req->mode);
+    if (r >= 0)
+      return r;
+    if (errno != EINVAL)
+      return r;
+    no_cloexec_support = 1;
+#endif  /* O_CLOEXEC */
+  }
+
+  if (req->cb != NULL)
+    uv_rwlock_rdlock(&req->loop->cloexec_lock);
+
+  r = open(req->path, req->flags, req->mode);
+
+  /* In case of failure `uv__cloexec` will leave error in `errno`,
+   * so it is enough to just set `r` to `-1`.
+   */
+  if (r >= 0 && uv__cloexec(r, 1) != 0) {
+    r = uv__close(r);
+    if (r != 0)
+      abort();
+    r = -1;
+  }
+
+  if (req->cb != NULL)
+    uv_rwlock_rdunlock(&req->loop->cloexec_lock);
+
+  return r;
+}
+
+
+static ssize_t uv__fs_read(uv_fs_t* req) {
+#if defined(__linux__)
+  static int no_preadv;
+#endif
+  ssize_t result;
+
+#if defined(_AIX)
+  struct stat buf;
+  if(fstat(req->file, &buf))
+    return -1;
+  if(S_ISDIR(buf.st_mode)) {
+    errno = EISDIR;
+    return -1;
+  }
+#endif /* defined(_AIX) */
+  if (req->off < 0) {
+    if (req->nbufs == 1)
+      result = read(req->file, req->bufs[0].base, req->bufs[0].len);
+    else
+      result = readv(req->file, (struct iovec*) req->bufs, req->nbufs);
+  } else {
+    if (req->nbufs == 1) {
+      result = pread(req->file, req->bufs[0].base, req->bufs[0].len, req->off);
+      goto done;
+    }
+
+#if HAVE_PREADV
+    result = preadv(req->file, (struct iovec*) req->bufs, req->nbufs, req->off);
+#else
+# if defined(__linux__)
+    if (no_preadv) retry:
+# endif
+    {
+      off_t nread;
+      size_t index;
+
+      nread = 0;
+      index = 0;
+      result = 1;
+      do {
+        if (req->bufs[index].len > 0) {
+          result = pread(req->file,
+                         req->bufs[index].base,
+                         req->bufs[index].len,
+                         req->off + nread);
+          if (result > 0)
+            nread += result;
+        }
+        index++;
+      } while (index < req->nbufs && result > 0);
+      if (nread > 0)
+        result = nread;
+    }
+# if defined(__linux__)
+    else {
+      result = uv__preadv(req->file,
+                          (struct iovec*)req->bufs,
+                          req->nbufs,
+                          req->off);
+      if (result == -1 && errno == ENOSYS) {
+        no_preadv = 1;
+        goto retry;
+      }
+    }
+# endif
+#endif
+  }
+
+done:
+  return result;
+}
+
+
+#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_8)
+#define UV_CONST_DIRENT uv__dirent_t
+#else
+#define UV_CONST_DIRENT const uv__dirent_t
+#endif
+
+
+static int uv__fs_scandir_filter(UV_CONST_DIRENT* dent) {
+  return strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0;
+}
+
+
+static int uv__fs_scandir_sort(UV_CONST_DIRENT** a, UV_CONST_DIRENT** b) {
+  return strcmp((*a)->d_name, (*b)->d_name);
+}
+
+
+static ssize_t uv__fs_scandir(uv_fs_t* req) {
+  uv__dirent_t **dents;
+  int saved_errno;
+  int n;
+
+  dents = NULL;
+  n = scandir(req->path, &dents, uv__fs_scandir_filter, uv__fs_scandir_sort);
+
+  /* NOTE: We will use nbufs as an index field */
+  req->nbufs = 0;
+
+  if (n == 0)
+    goto out; /* osx still needs to deallocate some memory */
+  else if (n == -1)
+    return n;
+
+  req->ptr = dents;
+
+  return n;
+
+out:
+  saved_errno = errno;
+  if (dents != NULL) {
+    int i;
+
+    /* Memory was allocated using the system allocator, so use free() here. */
+    for (i = 0; i < n; i++)
+      free(dents[i]);
+    free(dents);
+  }
+  errno = saved_errno;
+
+  req->ptr = NULL;
+
+  return n;
+}
+
+
+static ssize_t uv__fs_pathmax_size(const char* path) {
+  ssize_t pathmax;
+
+  pathmax = pathconf(path, _PC_PATH_MAX);
+
+  if (pathmax == -1) {
+#if defined(PATH_MAX)
+    return PATH_MAX;
+#else
+#error "PATH_MAX undefined in the current platform"
+#endif
+  }
+
+  return pathmax;
+}
+
+static ssize_t uv__fs_readlink(uv_fs_t* req) {
+  ssize_t len;
+  char* buf;
+
+  len = uv__fs_pathmax_size(req->path);
+  buf = uv__malloc(len + 1);
+
+  if (buf == NULL) {
+    errno = ENOMEM;
+    return -1;
+  }
+
+  len = readlink(req->path, buf, len);
+
+  if (len == -1) {
+    uv__free(buf);
+    return -1;
+  }
+
+  buf[len] = '\0';
+  req->ptr = buf;
+
+  return 0;
+}
+
+static ssize_t uv__fs_realpath(uv_fs_t* req) {
+  ssize_t len;
+  char* buf;
+
+  len = uv__fs_pathmax_size(req->path);
+  buf = uv__malloc(len + 1);
+
+  if (buf == NULL) {
+    errno = ENOMEM;
+    return -1;
+  }
+
+  if (realpath(req->path, buf) == NULL) {
+    uv__free(buf);
+    return -1;
+  }
+
+  req->ptr = buf;
+
+  return 0;
+}
+
+static ssize_t uv__fs_sendfile_emul(uv_fs_t* req) {
+  struct pollfd pfd;
+  int use_pread;
+  off_t offset;
+  ssize_t nsent;
+  ssize_t nread;
+  ssize_t nwritten;
+  size_t buflen;
+  size_t len;
+  ssize_t n;
+  int in_fd;
+  int out_fd;
+  char buf[8192];
+
+  len = req->bufsml[0].len;
+  in_fd = req->flags;
+  out_fd = req->file;
+  offset = req->off;
+  use_pread = 1;
+
+  /* Here are the rules regarding errors:
+   *
+   * 1. Read errors are reported only if nsent==0, otherwise we return nsent.
+   *    The user needs to know that some data has already been sent, to stop
+   *    them from sending it twice.
+   *
+   * 2. Write errors are always reported. Write errors are bad because they
+   *    mean data loss: we've read data but now we can't write it out.
+   *
+   * We try to use pread() and fall back to regular read() if the source fd
+   * doesn't support positional reads, for example when it's a pipe fd.
+   *
+   * If we get EAGAIN when writing to the target fd, we poll() on it until
+   * it becomes writable again.
+   *
+   * FIXME: If we get a write error when use_pread==1, it should be safe to
+   *        return the number of sent bytes instead of an error because pread()
+   *        is, in theory, idempotent. However, special files in /dev or /proc
+   *        may support pread() but not necessarily return the same data on
+   *        successive reads.
+   *
+   * FIXME: There is no way now to signal that we managed to send *some* data
+   *        before a write error.
+   */
+  for (nsent = 0; (size_t) nsent < len; ) {
+    buflen = len - nsent;
+
+    if (buflen > sizeof(buf))
+      buflen = sizeof(buf);
+
+    do
+      if (use_pread)
+        nread = pread(in_fd, buf, buflen, offset);
+      else
+        nread = read(in_fd, buf, buflen);
+    while (nread == -1 && errno == EINTR);
+
+    if (nread == 0)
+      goto out;
+
+    if (nread == -1) {
+      if (use_pread && nsent == 0 && (errno == EIO || errno == ESPIPE)) {
+        use_pread = 0;
+        continue;
+      }
+
+      if (nsent == 0)
+        nsent = -1;
+
+      goto out;
+    }
+
+    for (nwritten = 0; nwritten < nread; ) {
+      do
+        n = write(out_fd, buf + nwritten, nread - nwritten);
+      while (n == -1 && errno == EINTR);
+
+      if (n != -1) {
+        nwritten += n;
+        continue;
+      }
+
+      if (errno != EAGAIN && errno != EWOULDBLOCK) {
+        nsent = -1;
+        goto out;
+      }
+
+      pfd.fd = out_fd;
+      pfd.events = POLLOUT;
+      pfd.revents = 0;
+
+      do
+        n = poll(&pfd, 1, -1);
+      while (n == -1 && errno == EINTR);
+
+      if (n == -1 || (pfd.revents & ~POLLOUT) != 0) {
+        errno = EIO;
+        nsent = -1;
+        goto out;
+      }
+    }
+
+    offset += nread;
+    nsent += nread;
+  }
+
+out:
+  if (nsent != -1)
+    req->off = offset;
+
+  return nsent;
+}
+
+
+static ssize_t uv__fs_sendfile(uv_fs_t* req) {
+  int in_fd;
+  int out_fd;
+
+  in_fd = req->flags;
+  out_fd = req->file;
+
+#if defined(__linux__) || defined(__sun)
+  {
+    off_t off;
+    ssize_t r;
+
+    off = req->off;
+    r = sendfile(out_fd, in_fd, &off, req->bufsml[0].len);
+
+    /* sendfile() on SunOS returns EINVAL if the target fd is not a socket but
+     * it still writes out data. Fortunately, we can detect it by checking if
+     * the offset has been updated.
+     */
+    if (r != -1 || off > req->off) {
+      r = off - req->off;
+      req->off = off;
+      return r;
+    }
+
+    if (errno == EINVAL ||
+        errno == EIO ||
+        errno == ENOTSOCK ||
+        errno == EXDEV) {
+      errno = 0;
+      return uv__fs_sendfile_emul(req);
+    }
+
+    return -1;
+  }
+#elif defined(__APPLE__)           || \
+      defined(__DragonFly__)       || \
+      defined(__FreeBSD__)         || \
+      defined(__FreeBSD_kernel__)
+  {
+    off_t len;
+    ssize_t r;
+
+    /* sendfile() on FreeBSD and Darwin returns EAGAIN if the target fd is in
+     * non-blocking mode and not all data could be written. If a non-zero
+     * number of bytes have been sent, we don't consider it an error.
+     */
+
+#if defined(__FreeBSD__) || defined(__DragonFly__)
+    len = 0;
+    r = sendfile(in_fd, out_fd, req->off, req->bufsml[0].len, NULL, &len, 0);
+#elif defined(__FreeBSD_kernel__)
+    len = 0;
+    r = bsd_sendfile(in_fd,
+                     out_fd,
+                     req->off,
+                     req->bufsml[0].len,
+                     NULL,
+                     &len,
+                     0);
+#else
+    /* The darwin sendfile takes len as an input for the length to send,
+     * so make sure to initialize it with the caller's value. */
+    len = req->bufsml[0].len;
+    r = sendfile(in_fd, out_fd, req->off, &len, NULL, 0);
+#endif
+
+     /*
+     * The man page for sendfile(2) on DragonFly states that `len` contains
+     * a meaningful value ONLY in case of EAGAIN and EINTR.
+     * Nothing is said about it's value in case of other errors, so better
+     * not depend on the potential wrong assumption that is was not modified
+     * by the syscall.
+     */
+    if (r == 0 || ((errno == EAGAIN || errno == EINTR) && len != 0)) {
+      req->off += len;
+      return (ssize_t) len;
+    }
+
+    if (errno == EINVAL ||
+        errno == EIO ||
+        errno == ENOTSOCK ||
+        errno == EXDEV) {
+      errno = 0;
+      return uv__fs_sendfile_emul(req);
+    }
+
+    return -1;
+  }
+#else
+  /* Squelch compiler warnings. */
+  (void) &in_fd;
+  (void) &out_fd;
+
+  return uv__fs_sendfile_emul(req);
+#endif
+}
+
+
+static ssize_t uv__fs_utime(uv_fs_t* req) {
+  struct utimbuf buf;
+  buf.actime = req->atime;
+  buf.modtime = req->mtime;
+  return utime(req->path, &buf); /* TODO use utimes() where available */
+}
+
+
+static ssize_t uv__fs_write(uv_fs_t* req) {
+#if defined(__linux__)
+  static int no_pwritev;
+#endif
+  ssize_t r;
+
+  /* Serialize writes on OS X, concurrent write() and pwrite() calls result in
+   * data loss. We can't use a per-file descriptor lock, the descriptor may be
+   * a dup().
+   */
+#if defined(__APPLE__)
+  static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+
+  if (pthread_mutex_lock(&lock))
+    abort();
+#endif
+
+  if (req->off < 0) {
+    if (req->nbufs == 1)
+      r = write(req->file, req->bufs[0].base, req->bufs[0].len);
+    else
+      r = writev(req->file, (struct iovec*) req->bufs, req->nbufs);
+  } else {
+    if (req->nbufs == 1) {
+      r = pwrite(req->file, req->bufs[0].base, req->bufs[0].len, req->off);
+      goto done;
+    }
+#if HAVE_PREADV
+    r = pwritev(req->file, (struct iovec*) req->bufs, req->nbufs, req->off);
+#else
+# if defined(__linux__)
+    if (no_pwritev) retry:
+# endif
+    {
+      off_t written;
+      size_t index;
+
+      written = 0;
+      index = 0;
+      r = 0;
+      do {
+        if (req->bufs[index].len > 0) {
+          r = pwrite(req->file,
+                     req->bufs[index].base,
+                     req->bufs[index].len,
+                     req->off + written);
+          if (r > 0)
+            written += r;
+        }
+        index++;
+      } while (index < req->nbufs && r >= 0);
+      if (written > 0)
+        r = written;
+    }
+# if defined(__linux__)
+    else {
+      r = uv__pwritev(req->file,
+                      (struct iovec*) req->bufs,
+                      req->nbufs,
+                      req->off);
+      if (r == -1 && errno == ENOSYS) {
+        no_pwritev = 1;
+        goto retry;
+      }
+    }
+# endif
+#endif
+  }
+
+done:
+#if defined(__APPLE__)
+  if (pthread_mutex_unlock(&lock))
+    abort();
+#endif
+
+  return r;
+}
+
+static void uv__to_stat(struct stat* src, uv_stat_t* dst) {
+  dst->st_dev = src->st_dev;
+  dst->st_mode = src->st_mode;
+  dst->st_nlink = src->st_nlink;
+  dst->st_uid = src->st_uid;
+  dst->st_gid = src->st_gid;
+  dst->st_rdev = src->st_rdev;
+  dst->st_ino = src->st_ino;
+  dst->st_size = src->st_size;
+  dst->st_blksize = src->st_blksize;
+  dst->st_blocks = src->st_blocks;
+
+#if defined(__APPLE__)
+  dst->st_atim.tv_sec = src->st_atimespec.tv_sec;
+  dst->st_atim.tv_nsec = src->st_atimespec.tv_nsec;
+  dst->st_mtim.tv_sec = src->st_mtimespec.tv_sec;
+  dst->st_mtim.tv_nsec = src->st_mtimespec.tv_nsec;
+  dst->st_ctim.tv_sec = src->st_ctimespec.tv_sec;
+  dst->st_ctim.tv_nsec = src->st_ctimespec.tv_nsec;
+  dst->st_birthtim.tv_sec = src->st_birthtimespec.tv_sec;
+  dst->st_birthtim.tv_nsec = src->st_birthtimespec.tv_nsec;
+  dst->st_flags = src->st_flags;
+  dst->st_gen = src->st_gen;
+#elif defined(__ANDROID__)
+  dst->st_atim.tv_sec = src->st_atime;
+  dst->st_atim.tv_nsec = src->st_atimensec;
+  dst->st_mtim.tv_sec = src->st_mtime;
+  dst->st_mtim.tv_nsec = src->st_mtimensec;
+  dst->st_ctim.tv_sec = src->st_ctime;
+  dst->st_ctim.tv_nsec = src->st_ctimensec;
+  dst->st_birthtim.tv_sec = src->st_ctime;
+  dst->st_birthtim.tv_nsec = src->st_ctimensec;
+  dst->st_flags = 0;
+  dst->st_gen = 0;
+#elif !defined(_AIX) && (       \
+    defined(_GNU_SOURCE)     || \
+    defined(_BSD_SOURCE)     || \
+    defined(_SVID_SOURCE)    || \
+    defined(_XOPEN_SOURCE)   || \
+    defined(_DEFAULT_SOURCE))
+  dst->st_atim.tv_sec = src->st_atim.tv_sec;
+  dst->st_atim.tv_nsec = src->st_atim.tv_nsec;
+  dst->st_mtim.tv_sec = src->st_mtim.tv_sec;
+  dst->st_mtim.tv_nsec = src->st_mtim.tv_nsec;
+  dst->st_ctim.tv_sec = src->st_ctim.tv_sec;
+  dst->st_ctim.tv_nsec = src->st_ctim.tv_nsec;
+# if defined(__DragonFly__)  || \
+     defined(__FreeBSD__)    || \
+     defined(__OpenBSD__)    || \
+     defined(__NetBSD__)
+  dst->st_birthtim.tv_sec = src->st_birthtim.tv_sec;
+  dst->st_birthtim.tv_nsec = src->st_birthtim.tv_nsec;
+  dst->st_flags = src->st_flags;
+  dst->st_gen = src->st_gen;
+# else
+  dst->st_birthtim.tv_sec = src->st_ctim.tv_sec;
+  dst->st_birthtim.tv_nsec = src->st_ctim.tv_nsec;
+  dst->st_flags = 0;
+  dst->st_gen = 0;
+# endif
+#else
+  dst->st_atim.tv_sec = src->st_atime;
+  dst->st_atim.tv_nsec = 0;
+  dst->st_mtim.tv_sec = src->st_mtime;
+  dst->st_mtim.tv_nsec = 0;
+  dst->st_ctim.tv_sec = src->st_ctime;
+  dst->st_ctim.tv_nsec = 0;
+  dst->st_birthtim.tv_sec = src->st_ctime;
+  dst->st_birthtim.tv_nsec = 0;
+  dst->st_flags = 0;
+  dst->st_gen = 0;
+#endif
+}
+
+
+static int uv__fs_stat(const char *path, uv_stat_t *buf) {
+  struct stat pbuf;
+  int ret;
+
+  ret = stat(path, &pbuf);
+  if (ret == 0)
+    uv__to_stat(&pbuf, buf);
+
+  return ret;
+}
+
+
+static int uv__fs_lstat(const char *path, uv_stat_t *buf) {
+  struct stat pbuf;
+  int ret;
+
+  ret = lstat(path, &pbuf);
+  if (ret == 0)
+    uv__to_stat(&pbuf, buf);
+
+  return ret;
+}
+
+
+static int uv__fs_fstat(int fd, uv_stat_t *buf) {
+  struct stat pbuf;
+  int ret;
+
+  ret = fstat(fd, &pbuf);
+  if (ret == 0)
+    uv__to_stat(&pbuf, buf);
+
+  return ret;
+}
+
+
+typedef ssize_t (*uv__fs_buf_iter_processor)(uv_fs_t* req);
+static ssize_t uv__fs_buf_iter(uv_fs_t* req, uv__fs_buf_iter_processor process) {
+  unsigned int iovmax;
+  unsigned int nbufs;
+  uv_buf_t* bufs;
+  ssize_t total;
+  ssize_t result;
+
+  iovmax = uv__getiovmax();
+  nbufs = req->nbufs;
+  bufs = req->bufs;
+  total = 0;
+
+  while (nbufs > 0) {
+    req->nbufs = nbufs;
+    if (req->nbufs > iovmax)
+      req->nbufs = iovmax;
+
+    result = process(req);
+    if (result <= 0) {
+      if (total == 0)
+        total = result;
+      break;
+    }
+
+    if (req->off >= 0)
+      req->off += result;
+
+    req->bufs += req->nbufs;
+    nbufs -= req->nbufs;
+    total += result;
+  }
+
+  if (errno == EINTR && total == -1)
+    return total;
+
+  if (bufs != req->bufsml)
+    uv__free(bufs);
+
+  req->bufs = NULL;
+  req->nbufs = 0;
+
+  return total;
+}
+
+
+static void uv__fs_work(struct uv__work* w) {
+  int retry_on_eintr;
+  uv_fs_t* req;
+  ssize_t r;
+
+  req = container_of(w, uv_fs_t, work_req);
+  retry_on_eintr = !(req->fs_type == UV_FS_CLOSE);
+
+  do {
+    errno = 0;
+
+#define X(type, action)                                                       \
+  case UV_FS_ ## type:                                                        \
+    r = action;                                                               \
+    break;
+
+    switch (req->fs_type) {
+    X(ACCESS, access(req->path, req->flags));
+    X(CHMOD, chmod(req->path, req->mode));
+    X(CHOWN, chown(req->path, req->uid, req->gid));
+    X(CLOSE, close(req->file));
+    X(FCHMOD, fchmod(req->file, req->mode));
+    X(FCHOWN, fchown(req->file, req->uid, req->gid));
+    X(FDATASYNC, uv__fs_fdatasync(req));
+    X(FSTAT, uv__fs_fstat(req->file, &req->statbuf));
+    X(FSYNC, fsync(req->file));
+    X(FTRUNCATE, ftruncate(req->file, req->off));
+    X(FUTIME, uv__fs_futime(req));
+    X(LSTAT, uv__fs_lstat(req->path, &req->statbuf));
+    X(LINK, link(req->path, req->new_path));
+    X(MKDIR, mkdir(req->path, req->mode));
+    X(MKDTEMP, uv__fs_mkdtemp(req));
+    X(OPEN, uv__fs_open(req));
+    X(READ, uv__fs_buf_iter(req, uv__fs_read));
+    X(SCANDIR, uv__fs_scandir(req));
+    X(READLINK, uv__fs_readlink(req));
+    X(REALPATH, uv__fs_realpath(req));
+    X(RENAME, rename(req->path, req->new_path));
+    X(RMDIR, rmdir(req->path));
+    X(SENDFILE, uv__fs_sendfile(req));
+    X(STAT, uv__fs_stat(req->path, &req->statbuf));
+    X(SYMLINK, symlink(req->path, req->new_path));
+    X(UNLINK, unlink(req->path));
+    X(UTIME, uv__fs_utime(req));
+    X(WRITE, uv__fs_buf_iter(req, uv__fs_write));
+    default: abort();
+    }
+#undef X
+  } while (r == -1 && errno == EINTR && retry_on_eintr);
+
+  if (r == -1)
+    req->result = -errno;
+  else
+    req->result = r;
+
+  if (r == 0 && (req->fs_type == UV_FS_STAT ||
+                 req->fs_type == UV_FS_FSTAT ||
+                 req->fs_type == UV_FS_LSTAT)) {
+    req->ptr = &req->statbuf;
+  }
+}
+
+
+static void uv__fs_done(struct uv__work* w, int status) {
+  uv_fs_t* req;
+
+  req = container_of(w, uv_fs_t, work_req);
+  uv__req_unregister(req->loop, req);
+
+  if (status == -ECANCELED) {
+    assert(req->result == 0);
+    req->result = -ECANCELED;
+  }
+
+  req->cb(req);
+}
+
+
+int uv_fs_access(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 const char* path,
+                 int flags,
+                 uv_fs_cb cb) {
+  INIT(ACCESS);
+  PATH;
+  req->flags = flags;
+  POST;
+}
+
+
+int uv_fs_chmod(uv_loop_t* loop,
+                uv_fs_t* req,
+                const char* path,
+                int mode,
+                uv_fs_cb cb) {
+  INIT(CHMOD);
+  PATH;
+  req->mode = mode;
+  POST;
+}
+
+
+int uv_fs_chown(uv_loop_t* loop,
+                uv_fs_t* req,
+                const char* path,
+                uv_uid_t uid,
+                uv_gid_t gid,
+                uv_fs_cb cb) {
+  INIT(CHOWN);
+  PATH;
+  req->uid = uid;
+  req->gid = gid;
+  POST;
+}
+
+
+int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) {
+  INIT(CLOSE);
+  req->file = file;
+  POST;
+}
+
+
+int uv_fs_fchmod(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 uv_file file,
+                 int mode,
+                 uv_fs_cb cb) {
+  INIT(FCHMOD);
+  req->file = file;
+  req->mode = mode;
+  POST;
+}
+
+
+int uv_fs_fchown(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 uv_file file,
+                 uv_uid_t uid,
+                 uv_gid_t gid,
+                 uv_fs_cb cb) {
+  INIT(FCHOWN);
+  req->file = file;
+  req->uid = uid;
+  req->gid = gid;
+  POST;
+}
+
+
+int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) {
+  INIT(FDATASYNC);
+  req->file = file;
+  POST;
+}
+
+
+int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) {
+  INIT(FSTAT);
+  req->file = file;
+  POST;
+}
+
+
+int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) {
+  INIT(FSYNC);
+  req->file = file;
+  POST;
+}
+
+
+int uv_fs_ftruncate(uv_loop_t* loop,
+                    uv_fs_t* req,
+                    uv_file file,
+                    int64_t off,
+                    uv_fs_cb cb) {
+  INIT(FTRUNCATE);
+  req->file = file;
+  req->off = off;
+  POST;
+}
+
+
+int uv_fs_futime(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 uv_file file,
+                 double atime,
+                 double mtime,
+                 uv_fs_cb cb) {
+  INIT(FUTIME);
+  req->file = file;
+  req->atime = atime;
+  req->mtime = mtime;
+  POST;
+}
+
+
+int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  INIT(LSTAT);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_link(uv_loop_t* loop,
+               uv_fs_t* req,
+               const char* path,
+               const char* new_path,
+               uv_fs_cb cb) {
+  INIT(LINK);
+  PATH2;
+  POST;
+}
+
+
+int uv_fs_mkdir(uv_loop_t* loop,
+                uv_fs_t* req,
+                const char* path,
+                int mode,
+                uv_fs_cb cb) {
+  INIT(MKDIR);
+  PATH;
+  req->mode = mode;
+  POST;
+}
+
+
+int uv_fs_mkdtemp(uv_loop_t* loop,
+                  uv_fs_t* req,
+                  const char* tpl,
+                  uv_fs_cb cb) {
+  INIT(MKDTEMP);
+  req->path = uv__strdup(tpl);
+  if (req->path == NULL) {
+    if (cb != NULL)
+      uv__req_unregister(loop, req);
+    return -ENOMEM;
+  }
+  POST;
+}
+
+
+int uv_fs_open(uv_loop_t* loop,
+               uv_fs_t* req,
+               const char* path,
+               int flags,
+               int mode,
+               uv_fs_cb cb) {
+  INIT(OPEN);
+  PATH;
+  req->flags = flags;
+  req->mode = mode;
+  POST;
+}
+
+
+int uv_fs_read(uv_loop_t* loop, uv_fs_t* req,
+               uv_file file,
+               const uv_buf_t bufs[],
+               unsigned int nbufs,
+               int64_t off,
+               uv_fs_cb cb) {
+  if (bufs == NULL || nbufs == 0)
+    return -EINVAL;
+
+  INIT(READ);
+  req->file = file;
+
+  req->nbufs = nbufs;
+  req->bufs = req->bufsml;
+  if (nbufs > ARRAY_SIZE(req->bufsml))
+    req->bufs = uv__malloc(nbufs * sizeof(*bufs));
+
+  if (req->bufs == NULL) {
+    if (cb != NULL)
+      uv__req_unregister(loop, req);
+    return -ENOMEM;
+  }
+
+  memcpy(req->bufs, bufs, nbufs * sizeof(*bufs));
+
+  req->off = off;
+  POST;
+}
+
+
+int uv_fs_scandir(uv_loop_t* loop,
+                  uv_fs_t* req,
+                  const char* path,
+                  int flags,
+                  uv_fs_cb cb) {
+  INIT(SCANDIR);
+  PATH;
+  req->flags = flags;
+  POST;
+}
+
+
+int uv_fs_readlink(uv_loop_t* loop,
+                   uv_fs_t* req,
+                   const char* path,
+                   uv_fs_cb cb) {
+  INIT(READLINK);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_realpath(uv_loop_t* loop,
+                  uv_fs_t* req,
+                  const char * path,
+                  uv_fs_cb cb) {
+  INIT(REALPATH);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_rename(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 const char* path,
+                 const char* new_path,
+                 uv_fs_cb cb) {
+  INIT(RENAME);
+  PATH2;
+  POST;
+}
+
+
+int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  INIT(RMDIR);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_sendfile(uv_loop_t* loop,
+                   uv_fs_t* req,
+                   uv_file out_fd,
+                   uv_file in_fd,
+                   int64_t off,
+                   size_t len,
+                   uv_fs_cb cb) {
+  INIT(SENDFILE);
+  req->flags = in_fd; /* hack */
+  req->file = out_fd;
+  req->off = off;
+  req->bufsml[0].len = len;
+  POST;
+}
+
+
+int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  INIT(STAT);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_symlink(uv_loop_t* loop,
+                  uv_fs_t* req,
+                  const char* path,
+                  const char* new_path,
+                  int flags,
+                  uv_fs_cb cb) {
+  INIT(SYMLINK);
+  PATH2;
+  req->flags = flags;
+  POST;
+}
+
+
+int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  INIT(UNLINK);
+  PATH;
+  POST;
+}
+
+
+int uv_fs_utime(uv_loop_t* loop,
+                uv_fs_t* req,
+                const char* path,
+                double atime,
+                double mtime,
+                uv_fs_cb cb) {
+  INIT(UTIME);
+  PATH;
+  req->atime = atime;
+  req->mtime = mtime;
+  POST;
+}
+
+
+int uv_fs_write(uv_loop_t* loop,
+                uv_fs_t* req,
+                uv_file file,
+                const uv_buf_t bufs[],
+                unsigned int nbufs,
+                int64_t off,
+                uv_fs_cb cb) {
+  if (bufs == NULL || nbufs == 0)
+    return -EINVAL;
+
+  INIT(WRITE);
+  req->file = file;
+
+  req->nbufs = nbufs;
+  req->bufs = req->bufsml;
+  if (nbufs > ARRAY_SIZE(req->bufsml))
+    req->bufs = uv__malloc(nbufs * sizeof(*bufs));
+
+  if (req->bufs == NULL) {
+    if (cb != NULL)
+      uv__req_unregister(loop, req);
+    return -ENOMEM;
+  }
+
+  memcpy(req->bufs, bufs, nbufs * sizeof(*bufs));
+
+  req->off = off;
+  POST;
+}
+
+
+void uv_fs_req_cleanup(uv_fs_t* req) {
+  /* Only necessary for asychronous requests, i.e., requests with a callback.
+   * Synchronous ones don't copy their arguments and have req->path and
+   * req->new_path pointing to user-owned memory.  UV_FS_MKDTEMP is the
+   * exception to the rule, it always allocates memory.
+   */
+  if (req->path != NULL && (req->cb != NULL || req->fs_type == UV_FS_MKDTEMP))
+    uv__free((void*) req->path);  /* Memory is shared with req->new_path. */
+
+  req->path = NULL;
+  req->new_path = NULL;
+
+  if (req->fs_type == UV_FS_SCANDIR && req->ptr != NULL)
+    uv__fs_scandir_cleanup(req);
+
+  if (req->ptr != &req->statbuf)
+    uv__free(req->ptr);
+  req->ptr = NULL;
+}
diff --git a/Utilities/cmlibuv/src/unix/fsevents.c b/Utilities/cmlibuv/src/unix/fsevents.c
new file mode 100644
index 0000000..d331a13
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/fsevents.c
@@ -0,0 +1,904 @@
+/* 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 "internal.h"
+
+#if TARGET_OS_IPHONE
+
+/* iOS (currently) doesn't provide the FSEvents-API (nor CoreServices) */
+
+int uv__fsevents_init(uv_fs_event_t* handle) {
+  return 0;
+}
+
+
+int uv__fsevents_close(uv_fs_event_t* handle) {
+  return 0;
+}
+
+
+void uv__fsevents_loop_delete(uv_loop_t* loop) {
+}
+
+#else /* TARGET_OS_IPHONE */
+
+#include <dlfcn.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <pthread.h>
+
+#include <CoreFoundation/CFRunLoop.h>
+#include <CoreServices/CoreServices.h>
+
+/* These are macros to avoid "initializer element is not constant" errors
+ * with old versions of gcc.
+ */
+#define kFSEventsModified (kFSEventStreamEventFlagItemFinderInfoMod |         \
+                           kFSEventStreamEventFlagItemModified |              \
+                           kFSEventStreamEventFlagItemInodeMetaMod |          \
+                           kFSEventStreamEventFlagItemChangeOwner |           \
+                           kFSEventStreamEventFlagItemXattrMod)
+
+#define kFSEventsRenamed  (kFSEventStreamEventFlagItemCreated |               \
+                           kFSEventStreamEventFlagItemRemoved |               \
+                           kFSEventStreamEventFlagItemRenamed)
+
+#define kFSEventsSystem   (kFSEventStreamEventFlagUserDropped |               \
+                           kFSEventStreamEventFlagKernelDropped |             \
+                           kFSEventStreamEventFlagEventIdsWrapped |           \
+                           kFSEventStreamEventFlagHistoryDone |               \
+                           kFSEventStreamEventFlagMount |                     \
+                           kFSEventStreamEventFlagUnmount |                   \
+                           kFSEventStreamEventFlagRootChanged)
+
+typedef struct uv__fsevents_event_s uv__fsevents_event_t;
+typedef struct uv__cf_loop_signal_s uv__cf_loop_signal_t;
+typedef struct uv__cf_loop_state_s uv__cf_loop_state_t;
+
+enum uv__cf_loop_signal_type_e {
+  kUVCFLoopSignalRegular,
+  kUVCFLoopSignalClosing
+};
+typedef enum uv__cf_loop_signal_type_e uv__cf_loop_signal_type_t;
+
+struct uv__cf_loop_signal_s {
+  QUEUE member;
+  uv_fs_event_t* handle;
+  uv__cf_loop_signal_type_t type;
+};
+
+struct uv__fsevents_event_s {
+  QUEUE member;
+  int events;
+  char path[1];
+};
+
+struct uv__cf_loop_state_s {
+  CFRunLoopRef loop;
+  CFRunLoopSourceRef signal_source;
+  int fsevent_need_reschedule;
+  FSEventStreamRef fsevent_stream;
+  uv_sem_t fsevent_sem;
+  uv_mutex_t fsevent_mutex;
+  void* fsevent_handles[2];
+  unsigned int fsevent_handle_count;
+};
+
+/* Forward declarations */
+static void uv__cf_loop_cb(void* arg);
+static void* uv__cf_loop_runner(void* arg);
+static int uv__cf_loop_signal(uv_loop_t* loop,
+                              uv_fs_event_t* handle,
+                              uv__cf_loop_signal_type_t type);
+
+/* Lazy-loaded by uv__fsevents_global_init(). */
+static CFArrayRef (*pCFArrayCreate)(CFAllocatorRef,
+                                    const void**,
+                                    CFIndex,
+                                    const CFArrayCallBacks*);
+static void (*pCFRelease)(CFTypeRef);
+static void (*pCFRunLoopAddSource)(CFRunLoopRef,
+                                   CFRunLoopSourceRef,
+                                   CFStringRef);
+static CFRunLoopRef (*pCFRunLoopGetCurrent)(void);
+static void (*pCFRunLoopRemoveSource)(CFRunLoopRef,
+                                      CFRunLoopSourceRef,
+                                      CFStringRef);
+static void (*pCFRunLoopRun)(void);
+static CFRunLoopSourceRef (*pCFRunLoopSourceCreate)(CFAllocatorRef,
+                                                    CFIndex,
+                                                    CFRunLoopSourceContext*);
+static void (*pCFRunLoopSourceSignal)(CFRunLoopSourceRef);
+static void (*pCFRunLoopStop)(CFRunLoopRef);
+static void (*pCFRunLoopWakeUp)(CFRunLoopRef);
+static CFStringRef (*pCFStringCreateWithFileSystemRepresentation)(
+    CFAllocatorRef,
+    const char*);
+static CFStringEncoding (*pCFStringGetSystemEncoding)(void);
+static CFStringRef (*pkCFRunLoopDefaultMode);
+static FSEventStreamRef (*pFSEventStreamCreate)(CFAllocatorRef,
+                                                FSEventStreamCallback,
+                                                FSEventStreamContext*,
+                                                CFArrayRef,
+                                                FSEventStreamEventId,
+                                                CFTimeInterval,
+                                                FSEventStreamCreateFlags);
+static void (*pFSEventStreamFlushSync)(FSEventStreamRef);
+static void (*pFSEventStreamInvalidate)(FSEventStreamRef);
+static void (*pFSEventStreamRelease)(FSEventStreamRef);
+static void (*pFSEventStreamScheduleWithRunLoop)(FSEventStreamRef,
+                                                 CFRunLoopRef,
+                                                 CFStringRef);
+static Boolean (*pFSEventStreamStart)(FSEventStreamRef);
+static void (*pFSEventStreamStop)(FSEventStreamRef);
+
+#define UV__FSEVENTS_PROCESS(handle, block)                                   \
+    do {                                                                      \
+      QUEUE events;                                                           \
+      QUEUE* q;                                                               \
+      uv__fsevents_event_t* event;                                            \
+      int err;                                                                \
+      uv_mutex_lock(&(handle)->cf_mutex);                                     \
+      /* Split-off all events and empty original queue */                     \
+      QUEUE_MOVE(&(handle)->cf_events, &events);                              \
+      /* Get error (if any) and zero original one */                          \
+      err = (handle)->cf_error;                                               \
+      (handle)->cf_error = 0;                                                 \
+      uv_mutex_unlock(&(handle)->cf_mutex);                                   \
+      /* Loop through events, deallocating each after processing */           \
+      while (!QUEUE_EMPTY(&events)) {                                         \
+        q = QUEUE_HEAD(&events);                                              \
+        event = QUEUE_DATA(q, uv__fsevents_event_t, member);                  \
+        QUEUE_REMOVE(q);                                                      \
+        /* NOTE: Checking uv__is_active() is required here, because handle    \
+         * callback may close handle and invoking it after it will lead to    \
+         * incorrect behaviour */                                             \
+        if (!uv__is_closing((handle)) && uv__is_active((handle)))             \
+          block                                                               \
+        /* Free allocated data */                                             \
+        uv__free(event);                                                      \
+      }                                                                       \
+      if (err != 0 && !uv__is_closing((handle)) && uv__is_active((handle)))   \
+        (handle)->cb((handle), NULL, 0, err);                                 \
+    } while (0)
+
+
+/* Runs in UV loop's thread, when there're events to report to handle */
+static void uv__fsevents_cb(uv_async_t* cb) {
+  uv_fs_event_t* handle;
+
+  handle = cb->data;
+
+  UV__FSEVENTS_PROCESS(handle, {
+    handle->cb(handle, event->path[0] ? event->path : NULL, event->events, 0);
+  });
+}
+
+
+/* Runs in CF thread, pushed event into handle's event list */
+static void uv__fsevents_push_event(uv_fs_event_t* handle,
+                                    QUEUE* events,
+                                    int err) {
+  assert(events != NULL || err != 0);
+  uv_mutex_lock(&handle->cf_mutex);
+
+  /* Concatenate two queues */
+  if (events != NULL)
+    QUEUE_ADD(&handle->cf_events, events);
+
+  /* Propagate error */
+  if (err != 0)
+    handle->cf_error = err;
+  uv_mutex_unlock(&handle->cf_mutex);
+
+  uv_async_send(handle->cf_cb);
+}
+
+
+/* Runs in CF thread, when there're events in FSEventStream */
+static void uv__fsevents_event_cb(ConstFSEventStreamRef streamRef,
+                                  void* info,
+                                  size_t numEvents,
+                                  void* eventPaths,
+                                  const FSEventStreamEventFlags eventFlags[],
+                                  const FSEventStreamEventId eventIds[]) {
+  size_t i;
+  int len;
+  char** paths;
+  char* path;
+  char* pos;
+  uv_fs_event_t* handle;
+  QUEUE* q;
+  uv_loop_t* loop;
+  uv__cf_loop_state_t* state;
+  uv__fsevents_event_t* event;
+  QUEUE head;
+
+  loop = info;
+  state = loop->cf_state;
+  assert(state != NULL);
+  paths = eventPaths;
+
+  /* For each handle */
+  uv_mutex_lock(&state->fsevent_mutex);
+  QUEUE_FOREACH(q, &state->fsevent_handles) {
+    handle = QUEUE_DATA(q, uv_fs_event_t, cf_member);
+    QUEUE_INIT(&head);
+
+    /* Process and filter out events */
+    for (i = 0; i < numEvents; i++) {
+      /* Ignore system events */
+      if (eventFlags[i] & kFSEventsSystem)
+        continue;
+
+      path = paths[i];
+      len = strlen(path);
+
+      /* Filter out paths that are outside handle's request */
+      if (strncmp(path, handle->realpath, handle->realpath_len) != 0)
+        continue;
+
+      if (handle->realpath_len > 1 || *handle->realpath != '/') {
+        path += handle->realpath_len;
+        len -= handle->realpath_len;
+
+        /* Skip forward slash */
+        if (*path != '\0') {
+          path++;
+          len--;
+        }
+      }
+
+#ifdef MAC_OS_X_VERSION_10_7
+      /* Ignore events with path equal to directory itself */
+      if (len == 0)
+        continue;
+#endif /* MAC_OS_X_VERSION_10_7 */
+
+      /* Do not emit events from subdirectories (without option set) */
+      if ((handle->cf_flags & UV_FS_EVENT_RECURSIVE) == 0 && *path != 0) {
+        pos = strchr(path + 1, '/');
+        if (pos != NULL)
+          continue;
+      }
+
+#ifndef MAC_OS_X_VERSION_10_7
+      path = "";
+      len = 0;
+#endif /* MAC_OS_X_VERSION_10_7 */
+
+      event = uv__malloc(sizeof(*event) + len);
+      if (event == NULL)
+        break;
+
+      memset(event, 0, sizeof(*event));
+      memcpy(event->path, path, len + 1);
+
+      if ((eventFlags[i] & kFSEventsModified) != 0 &&
+          (eventFlags[i] & kFSEventsRenamed) == 0)
+        event->events = UV_CHANGE;
+      else
+        event->events = UV_RENAME;
+
+      QUEUE_INSERT_TAIL(&head, &event->member);
+    }
+
+    if (!QUEUE_EMPTY(&head))
+      uv__fsevents_push_event(handle, &head, 0);
+  }
+  uv_mutex_unlock(&state->fsevent_mutex);
+}
+
+
+/* Runs in CF thread */
+static int uv__fsevents_create_stream(uv_loop_t* loop, CFArrayRef paths) {
+  uv__cf_loop_state_t* state;
+  FSEventStreamContext ctx;
+  FSEventStreamRef ref;
+  CFAbsoluteTime latency;
+  FSEventStreamCreateFlags flags;
+
+  /* Initialize context */
+  ctx.version = 0;
+  ctx.info = loop;
+  ctx.retain = NULL;
+  ctx.release = NULL;
+  ctx.copyDescription = NULL;
+
+  latency = 0.05;
+
+  /* Explanation of selected flags:
+   * 1. NoDefer - without this flag, events that are happening continuously
+   *    (i.e. each event is happening after time interval less than `latency`,
+   *    counted from previous event), will be deferred and passed to callback
+   *    once they'll either fill whole OS buffer, or when this continuous stream
+   *    will stop (i.e. there'll be delay between events, bigger than
+   *    `latency`).
+   *    Specifying this flag will invoke callback after `latency` time passed
+   *    since event.
+   * 2. FileEvents - fire callback for file changes too (by default it is firing
+   *    it only for directory changes).
+   */
+  flags = kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents;
+
+  /*
+   * NOTE: It might sound like a good idea to remember last seen StreamEventId,
+   * but in reality one dir might have last StreamEventId less than, the other,
+   * that is being watched now. Which will cause FSEventStream API to report
+   * changes to files from the past.
+   */
+  ref = pFSEventStreamCreate(NULL,
+                             &uv__fsevents_event_cb,
+                             &ctx,
+                             paths,
+                             kFSEventStreamEventIdSinceNow,
+                             latency,
+                             flags);
+  assert(ref != NULL);
+
+  state = loop->cf_state;
+  pFSEventStreamScheduleWithRunLoop(ref,
+                                    state->loop,
+                                    *pkCFRunLoopDefaultMode);
+  if (!pFSEventStreamStart(ref)) {
+    pFSEventStreamInvalidate(ref);
+    pFSEventStreamRelease(ref);
+    return -EMFILE;
+  }
+
+  state->fsevent_stream = ref;
+  return 0;
+}
+
+
+/* Runs in CF thread */
+static void uv__fsevents_destroy_stream(uv_loop_t* loop) {
+  uv__cf_loop_state_t* state;
+
+  state = loop->cf_state;
+
+  if (state->fsevent_stream == NULL)
+    return;
+
+  /* Flush all accumulated events */
+  pFSEventStreamFlushSync(state->fsevent_stream);
+
+  /* Stop emitting events */
+  pFSEventStreamStop(state->fsevent_stream);
+
+  /* Release stream */
+  pFSEventStreamInvalidate(state->fsevent_stream);
+  pFSEventStreamRelease(state->fsevent_stream);
+  state->fsevent_stream = NULL;
+}
+
+
+/* Runs in CF thread, when there're new fsevent handles to add to stream */
+static void uv__fsevents_reschedule(uv_fs_event_t* handle,
+                                    uv__cf_loop_signal_type_t type) {
+  uv__cf_loop_state_t* state;
+  QUEUE* q;
+  uv_fs_event_t* curr;
+  CFArrayRef cf_paths;
+  CFStringRef* paths;
+  unsigned int i;
+  int err;
+  unsigned int path_count;
+
+  state = handle->loop->cf_state;
+  paths = NULL;
+  cf_paths = NULL;
+  err = 0;
+  /* NOTE: `i` is used in deallocation loop below */
+  i = 0;
+
+  /* Optimization to prevent O(n^2) time spent when starting to watch
+   * many files simultaneously
+   */
+  uv_mutex_lock(&state->fsevent_mutex);
+  if (state->fsevent_need_reschedule == 0) {
+    uv_mutex_unlock(&state->fsevent_mutex);
+    goto final;
+  }
+  state->fsevent_need_reschedule = 0;
+  uv_mutex_unlock(&state->fsevent_mutex);
+
+  /* Destroy previous FSEventStream */
+  uv__fsevents_destroy_stream(handle->loop);
+
+  /* Any failure below will be a memory failure */
+  err = -ENOMEM;
+
+  /* Create list of all watched paths */
+  uv_mutex_lock(&state->fsevent_mutex);
+  path_count = state->fsevent_handle_count;
+  if (path_count != 0) {
+    paths = uv__malloc(sizeof(*paths) * path_count);
+    if (paths == NULL) {
+      uv_mutex_unlock(&state->fsevent_mutex);
+      goto final;
+    }
+
+    q = &state->fsevent_handles;
+    for (; i < path_count; i++) {
+      q = QUEUE_NEXT(q);
+      assert(q != &state->fsevent_handles);
+      curr = QUEUE_DATA(q, uv_fs_event_t, cf_member);
+
+      assert(curr->realpath != NULL);
+      paths[i] =
+          pCFStringCreateWithFileSystemRepresentation(NULL, curr->realpath);
+      if (paths[i] == NULL) {
+        uv_mutex_unlock(&state->fsevent_mutex);
+        goto final;
+      }
+    }
+  }
+  uv_mutex_unlock(&state->fsevent_mutex);
+  err = 0;
+
+  if (path_count != 0) {
+    /* Create new FSEventStream */
+    cf_paths = pCFArrayCreate(NULL, (const void**) paths, path_count, NULL);
+    if (cf_paths == NULL) {
+      err = -ENOMEM;
+      goto final;
+    }
+    err = uv__fsevents_create_stream(handle->loop, cf_paths);
+  }
+
+final:
+  /* Deallocate all paths in case of failure */
+  if (err != 0) {
+    if (cf_paths == NULL) {
+      while (i != 0)
+        pCFRelease(paths[--i]);
+      uv__free(paths);
+    } else {
+      /* CFArray takes ownership of both strings and original C-array */
+      pCFRelease(cf_paths);
+    }
+
+    /* Broadcast error to all handles */
+    uv_mutex_lock(&state->fsevent_mutex);
+    QUEUE_FOREACH(q, &state->fsevent_handles) {
+      curr = QUEUE_DATA(q, uv_fs_event_t, cf_member);
+      uv__fsevents_push_event(curr, NULL, err);
+    }
+    uv_mutex_unlock(&state->fsevent_mutex);
+  }
+
+  /*
+   * Main thread will block until the removal of handle from the list,
+   * we must tell it when we're ready.
+   *
+   * NOTE: This is coupled with `uv_sem_wait()` in `uv__fsevents_close`
+   */
+  if (type == kUVCFLoopSignalClosing)
+    uv_sem_post(&state->fsevent_sem);
+}
+
+
+static int uv__fsevents_global_init(void) {
+  static pthread_mutex_t global_init_mutex = PTHREAD_MUTEX_INITIALIZER;
+  static void* core_foundation_handle;
+  static void* core_services_handle;
+  int err;
+
+  err = 0;
+  pthread_mutex_lock(&global_init_mutex);
+  if (core_foundation_handle != NULL)
+    goto out;
+
+  /* The libraries are never unloaded because we currently don't have a good
+   * mechanism for keeping a reference count. It's unlikely to be an issue
+   * but if it ever becomes one, we can turn the dynamic library handles into
+   * per-event loop properties and have the dynamic linker keep track for us.
+   */
+  err = -ENOSYS;
+  core_foundation_handle = dlopen("/System/Library/Frameworks/"
+                                  "CoreFoundation.framework/"
+                                  "Versions/A/CoreFoundation",
+                                  RTLD_LAZY | RTLD_LOCAL);
+  if (core_foundation_handle == NULL)
+    goto out;
+
+  core_services_handle = dlopen("/System/Library/Frameworks/"
+                                "CoreServices.framework/"
+                                "Versions/A/CoreServices",
+                                RTLD_LAZY | RTLD_LOCAL);
+  if (core_services_handle == NULL)
+    goto out;
+
+  err = -ENOENT;
+#define V(handle, symbol)                                                     \
+  do {                                                                        \
+    *(void **)(&p ## symbol) = dlsym((handle), #symbol);                      \
+    if (p ## symbol == NULL)                                                  \
+      goto out;                                                               \
+  }                                                                           \
+  while (0)
+  V(core_foundation_handle, CFArrayCreate);
+  V(core_foundation_handle, CFRelease);
+  V(core_foundation_handle, CFRunLoopAddSource);
+  V(core_foundation_handle, CFRunLoopGetCurrent);
+  V(core_foundation_handle, CFRunLoopRemoveSource);
+  V(core_foundation_handle, CFRunLoopRun);
+  V(core_foundation_handle, CFRunLoopSourceCreate);
+  V(core_foundation_handle, CFRunLoopSourceSignal);
+  V(core_foundation_handle, CFRunLoopStop);
+  V(core_foundation_handle, CFRunLoopWakeUp);
+  V(core_foundation_handle, CFStringCreateWithFileSystemRepresentation);
+  V(core_foundation_handle, CFStringGetSystemEncoding);
+  V(core_foundation_handle, kCFRunLoopDefaultMode);
+  V(core_services_handle, FSEventStreamCreate);
+  V(core_services_handle, FSEventStreamFlushSync);
+  V(core_services_handle, FSEventStreamInvalidate);
+  V(core_services_handle, FSEventStreamRelease);
+  V(core_services_handle, FSEventStreamScheduleWithRunLoop);
+  V(core_services_handle, FSEventStreamStart);
+  V(core_services_handle, FSEventStreamStop);
+#undef V
+  err = 0;
+
+out:
+  if (err && core_services_handle != NULL) {
+    dlclose(core_services_handle);
+    core_services_handle = NULL;
+  }
+
+  if (err && core_foundation_handle != NULL) {
+    dlclose(core_foundation_handle);
+    core_foundation_handle = NULL;
+  }
+
+  pthread_mutex_unlock(&global_init_mutex);
+  return err;
+}
+
+
+/* Runs in UV loop */
+static int uv__fsevents_loop_init(uv_loop_t* loop) {
+  CFRunLoopSourceContext ctx;
+  uv__cf_loop_state_t* state;
+  pthread_attr_t attr_storage;
+  pthread_attr_t* attr;
+  int err;
+
+  if (loop->cf_state != NULL)
+    return 0;
+
+  err = uv__fsevents_global_init();
+  if (err)
+    return err;
+
+  state = uv__calloc(1, sizeof(*state));
+  if (state == NULL)
+    return -ENOMEM;
+
+  err = uv_mutex_init(&loop->cf_mutex);
+  if (err)
+    goto fail_mutex_init;
+
+  err = uv_sem_init(&loop->cf_sem, 0);
+  if (err)
+    goto fail_sem_init;
+
+  QUEUE_INIT(&loop->cf_signals);
+
+  err = uv_sem_init(&state->fsevent_sem, 0);
+  if (err)
+    goto fail_fsevent_sem_init;
+
+  err = uv_mutex_init(&state->fsevent_mutex);
+  if (err)
+    goto fail_fsevent_mutex_init;
+
+  QUEUE_INIT(&state->fsevent_handles);
+  state->fsevent_need_reschedule = 0;
+  state->fsevent_handle_count = 0;
+
+  memset(&ctx, 0, sizeof(ctx));
+  ctx.info = loop;
+  ctx.perform = uv__cf_loop_cb;
+  state->signal_source = pCFRunLoopSourceCreate(NULL, 0, &ctx);
+  if (state->signal_source == NULL) {
+    err = -ENOMEM;
+    goto fail_signal_source_create;
+  }
+
+  /* In the unlikely event that pthread_attr_init() fails, create the thread
+   * with the default stack size. We'll use a little more address space but
+   * that in itself is not a fatal error.
+   */
+  attr = &attr_storage;
+  if (pthread_attr_init(attr))
+    attr = NULL;
+
+  if (attr != NULL)
+    if (pthread_attr_setstacksize(attr, 4 * PTHREAD_STACK_MIN))
+      abort();
+
+  loop->cf_state = state;
+
+  /* uv_thread_t is an alias for pthread_t. */
+  err = -pthread_create(&loop->cf_thread, attr, uv__cf_loop_runner, loop);
+
+  if (attr != NULL)
+    pthread_attr_destroy(attr);
+
+  if (err)
+    goto fail_thread_create;
+
+  /* Synchronize threads */
+  uv_sem_wait(&loop->cf_sem);
+  return 0;
+
+fail_thread_create:
+  loop->cf_state = NULL;
+
+fail_signal_source_create:
+  uv_mutex_destroy(&state->fsevent_mutex);
+
+fail_fsevent_mutex_init:
+  uv_sem_destroy(&state->fsevent_sem);
+
+fail_fsevent_sem_init:
+  uv_sem_destroy(&loop->cf_sem);
+
+fail_sem_init:
+  uv_mutex_destroy(&loop->cf_mutex);
+
+fail_mutex_init:
+  uv__free(state);
+  return err;
+}
+
+
+/* Runs in UV loop */
+void uv__fsevents_loop_delete(uv_loop_t* loop) {
+  uv__cf_loop_signal_t* s;
+  uv__cf_loop_state_t* state;
+  QUEUE* q;
+
+  if (loop->cf_state == NULL)
+    return;
+
+  if (uv__cf_loop_signal(loop, NULL, kUVCFLoopSignalRegular) != 0)
+    abort();
+
+  uv_thread_join(&loop->cf_thread);
+  uv_sem_destroy(&loop->cf_sem);
+  uv_mutex_destroy(&loop->cf_mutex);
+
+  /* Free any remaining data */
+  while (!QUEUE_EMPTY(&loop->cf_signals)) {
+    q = QUEUE_HEAD(&loop->cf_signals);
+    s = QUEUE_DATA(q, uv__cf_loop_signal_t, member);
+    QUEUE_REMOVE(q);
+    uv__free(s);
+  }
+
+  /* Destroy state */
+  state = loop->cf_state;
+  uv_sem_destroy(&state->fsevent_sem);
+  uv_mutex_destroy(&state->fsevent_mutex);
+  pCFRelease(state->signal_source);
+  uv__free(state);
+  loop->cf_state = NULL;
+}
+
+
+/* Runs in CF thread. This is the CF loop's body */
+static void* uv__cf_loop_runner(void* arg) {
+  uv_loop_t* loop;
+  uv__cf_loop_state_t* state;
+
+  loop = arg;
+  state = loop->cf_state;
+  state->loop = pCFRunLoopGetCurrent();
+
+  pCFRunLoopAddSource(state->loop,
+                      state->signal_source,
+                      *pkCFRunLoopDefaultMode);
+
+  uv_sem_post(&loop->cf_sem);
+
+  pCFRunLoopRun();
+  pCFRunLoopRemoveSource(state->loop,
+                         state->signal_source,
+                         *pkCFRunLoopDefaultMode);
+
+  return NULL;
+}
+
+
+/* Runs in CF thread, executed after `uv__cf_loop_signal()` */
+static void uv__cf_loop_cb(void* arg) {
+  uv_loop_t* loop;
+  uv__cf_loop_state_t* state;
+  QUEUE* item;
+  QUEUE split_head;
+  uv__cf_loop_signal_t* s;
+
+  loop = arg;
+  state = loop->cf_state;
+
+  uv_mutex_lock(&loop->cf_mutex);
+  QUEUE_MOVE(&loop->cf_signals, &split_head);
+  uv_mutex_unlock(&loop->cf_mutex);
+
+  while (!QUEUE_EMPTY(&split_head)) {
+    item = QUEUE_HEAD(&split_head);
+    QUEUE_REMOVE(item);
+
+    s = QUEUE_DATA(item, uv__cf_loop_signal_t, member);
+
+    /* This was a termination signal */
+    if (s->handle == NULL)
+      pCFRunLoopStop(state->loop);
+    else
+      uv__fsevents_reschedule(s->handle, s->type);
+
+    uv__free(s);
+  }
+}
+
+
+/* Runs in UV loop to notify CF thread */
+int uv__cf_loop_signal(uv_loop_t* loop,
+                       uv_fs_event_t* handle,
+                       uv__cf_loop_signal_type_t type) {
+  uv__cf_loop_signal_t* item;
+  uv__cf_loop_state_t* state;
+
+  item = uv__malloc(sizeof(*item));
+  if (item == NULL)
+    return -ENOMEM;
+
+  item->handle = handle;
+  item->type = type;
+
+  uv_mutex_lock(&loop->cf_mutex);
+  QUEUE_INSERT_TAIL(&loop->cf_signals, &item->member);
+  uv_mutex_unlock(&loop->cf_mutex);
+
+  state = loop->cf_state;
+  assert(state != NULL);
+  pCFRunLoopSourceSignal(state->signal_source);
+  pCFRunLoopWakeUp(state->loop);
+
+  return 0;
+}
+
+
+/* Runs in UV loop to initialize handle */
+int uv__fsevents_init(uv_fs_event_t* handle) {
+  int err;
+  uv__cf_loop_state_t* state;
+
+  err = uv__fsevents_loop_init(handle->loop);
+  if (err)
+    return err;
+
+  /* Get absolute path to file */
+  handle->realpath = realpath(handle->path, NULL);
+  if (handle->realpath == NULL)
+    return -errno;
+  handle->realpath_len = strlen(handle->realpath);
+
+  /* Initialize event queue */
+  QUEUE_INIT(&handle->cf_events);
+  handle->cf_error = 0;
+
+  /*
+   * Events will occur in other thread.
+   * Initialize callback for getting them back into event loop's thread
+   */
+  handle->cf_cb = uv__malloc(sizeof(*handle->cf_cb));
+  if (handle->cf_cb == NULL) {
+    err = -ENOMEM;
+    goto fail_cf_cb_malloc;
+  }
+
+  handle->cf_cb->data = handle;
+  uv_async_init(handle->loop, handle->cf_cb, uv__fsevents_cb);
+  handle->cf_cb->flags |= UV__HANDLE_INTERNAL;
+  uv_unref((uv_handle_t*) handle->cf_cb);
+
+  err = uv_mutex_init(&handle->cf_mutex);
+  if (err)
+    goto fail_cf_mutex_init;
+
+  /* Insert handle into the list */
+  state = handle->loop->cf_state;
+  uv_mutex_lock(&state->fsevent_mutex);
+  QUEUE_INSERT_TAIL(&state->fsevent_handles, &handle->cf_member);
+  state->fsevent_handle_count++;
+  state->fsevent_need_reschedule = 1;
+  uv_mutex_unlock(&state->fsevent_mutex);
+
+  /* Reschedule FSEventStream */
+  assert(handle != NULL);
+  err = uv__cf_loop_signal(handle->loop, handle, kUVCFLoopSignalRegular);
+  if (err)
+    goto fail_loop_signal;
+
+  return 0;
+
+fail_loop_signal:
+  uv_mutex_destroy(&handle->cf_mutex);
+
+fail_cf_mutex_init:
+  uv__free(handle->cf_cb);
+  handle->cf_cb = NULL;
+
+fail_cf_cb_malloc:
+  uv__free(handle->realpath);
+  handle->realpath = NULL;
+  handle->realpath_len = 0;
+
+  return err;
+}
+
+
+/* Runs in UV loop to de-initialize handle */
+int uv__fsevents_close(uv_fs_event_t* handle) {
+  int err;
+  uv__cf_loop_state_t* state;
+
+  if (handle->cf_cb == NULL)
+    return -EINVAL;
+
+  /* Remove handle from  the list */
+  state = handle->loop->cf_state;
+  uv_mutex_lock(&state->fsevent_mutex);
+  QUEUE_REMOVE(&handle->cf_member);
+  state->fsevent_handle_count--;
+  state->fsevent_need_reschedule = 1;
+  uv_mutex_unlock(&state->fsevent_mutex);
+
+  /* Reschedule FSEventStream */
+  assert(handle != NULL);
+  err = uv__cf_loop_signal(handle->loop, handle, kUVCFLoopSignalClosing);
+  if (err)
+    return -err;
+
+  /* Wait for deinitialization */
+  uv_sem_wait(&state->fsevent_sem);
+
+  uv_close((uv_handle_t*) handle->cf_cb, (uv_close_cb) uv__free);
+  handle->cf_cb = NULL;
+
+  /* Free data in queue */
+  UV__FSEVENTS_PROCESS(handle, {
+    /* NOP */
+  });
+
+  uv_mutex_destroy(&handle->cf_mutex);
+  uv__free(handle->realpath);
+  handle->realpath = NULL;
+  handle->realpath_len = 0;
+
+  return 0;
+}
+
+#endif /* TARGET_OS_IPHONE */
diff --git a/Utilities/cmlibuv/src/unix/getaddrinfo.c b/Utilities/cmlibuv/src/unix/getaddrinfo.c
new file mode 100644
index 0000000..2049aea
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/getaddrinfo.c
@@ -0,0 +1,202 @@
+/* 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.
+ */
+
+/* Expose glibc-specific EAI_* error codes. Needs to be defined before we
+ * include any headers.
+ */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+#endif
+
+#include "uv.h"
+#include "internal.h"
+
+#include <errno.h>
+#include <stddef.h> /* NULL */
+#include <stdlib.h>
+#include <string.h>
+
+/* EAI_* constants. */
+#include <netdb.h>
+
+
+int uv__getaddrinfo_translate_error(int sys_err) {
+  switch (sys_err) {
+  case 0: return 0;
+#if defined(EAI_ADDRFAMILY)
+  case EAI_ADDRFAMILY: return UV_EAI_ADDRFAMILY;
+#endif
+#if defined(EAI_AGAIN)
+  case EAI_AGAIN: return UV_EAI_AGAIN;
+#endif
+#if defined(EAI_BADFLAGS)
+  case EAI_BADFLAGS: return UV_EAI_BADFLAGS;
+#endif
+#if defined(EAI_BADHINTS)
+  case EAI_BADHINTS: return UV_EAI_BADHINTS;
+#endif
+#if defined(EAI_CANCELED)
+  case EAI_CANCELED: return UV_EAI_CANCELED;
+#endif
+#if defined(EAI_FAIL)
+  case EAI_FAIL: return UV_EAI_FAIL;
+#endif
+#if defined(EAI_FAMILY)
+  case EAI_FAMILY: return UV_EAI_FAMILY;
+#endif
+#if defined(EAI_MEMORY)
+  case EAI_MEMORY: return UV_EAI_MEMORY;
+#endif
+#if defined(EAI_NODATA)
+  case EAI_NODATA: return UV_EAI_NODATA;
+#endif
+#if defined(EAI_NONAME)
+# if !defined(EAI_NODATA) || EAI_NODATA != EAI_NONAME
+  case EAI_NONAME: return UV_EAI_NONAME;
+# endif
+#endif
+#if defined(EAI_OVERFLOW)
+  case EAI_OVERFLOW: return UV_EAI_OVERFLOW;
+#endif
+#if defined(EAI_PROTOCOL)
+  case EAI_PROTOCOL: return UV_EAI_PROTOCOL;
+#endif
+#if defined(EAI_SERVICE)
+  case EAI_SERVICE: return UV_EAI_SERVICE;
+#endif
+#if defined(EAI_SOCKTYPE)
+  case EAI_SOCKTYPE: return UV_EAI_SOCKTYPE;
+#endif
+#if defined(EAI_SYSTEM)
+  case EAI_SYSTEM: return -errno;
+#endif
+  }
+  assert(!"unknown EAI_* error code");
+  abort();
+  return 0;  /* Pacify compiler. */
+}
+
+
+static void uv__getaddrinfo_work(struct uv__work* w) {
+  uv_getaddrinfo_t* req;
+  int err;
+
+  req = container_of(w, uv_getaddrinfo_t, work_req);
+  err = getaddrinfo(req->hostname, req->service, req->hints, &req->addrinfo);
+  req->retcode = uv__getaddrinfo_translate_error(err);
+}
+
+
+static void uv__getaddrinfo_done(struct uv__work* w, int status) {
+  uv_getaddrinfo_t* req;
+
+  req = container_of(w, uv_getaddrinfo_t, work_req);
+  uv__req_unregister(req->loop, req);
+
+  /* See initialization in uv_getaddrinfo(). */
+  if (req->hints)
+    uv__free(req->hints);
+  else if (req->service)
+    uv__free(req->service);
+  else if (req->hostname)
+    uv__free(req->hostname);
+  else
+    assert(0);
+
+  req->hints = NULL;
+  req->service = NULL;
+  req->hostname = NULL;
+
+  if (status == -ECANCELED) {
+    assert(req->retcode == 0);
+    req->retcode = UV_EAI_CANCELED;
+  }
+
+  if (req->cb)
+    req->cb(req, req->retcode, req->addrinfo);
+}
+
+
+int uv_getaddrinfo(uv_loop_t* loop,
+                   uv_getaddrinfo_t* req,
+                   uv_getaddrinfo_cb cb,
+                   const char* hostname,
+                   const char* service,
+                   const struct addrinfo* hints) {
+  size_t hostname_len;
+  size_t service_len;
+  size_t hints_len;
+  size_t len;
+  char* buf;
+
+  if (req == NULL || (hostname == NULL && service == NULL))
+    return -EINVAL;
+
+  hostname_len = hostname ? strlen(hostname) + 1 : 0;
+  service_len = service ? strlen(service) + 1 : 0;
+  hints_len = hints ? sizeof(*hints) : 0;
+  buf = uv__malloc(hostname_len + service_len + hints_len);
+
+  if (buf == NULL)
+    return -ENOMEM;
+
+  uv__req_init(loop, req, UV_GETADDRINFO);
+  req->loop = loop;
+  req->cb = cb;
+  req->addrinfo = NULL;
+  req->hints = NULL;
+  req->service = NULL;
+  req->hostname = NULL;
+  req->retcode = 0;
+
+  /* order matters, see uv_getaddrinfo_done() */
+  len = 0;
+
+  if (hints) {
+    req->hints = memcpy(buf + len, hints, sizeof(*hints));
+    len += sizeof(*hints);
+  }
+
+  if (service) {
+    req->service = memcpy(buf + len, service, service_len);
+    len += service_len;
+  }
+
+  if (hostname)
+    req->hostname = memcpy(buf + len, hostname, hostname_len);
+
+  if (cb) {
+    uv__work_submit(loop,
+                    &req->work_req,
+                    uv__getaddrinfo_work,
+                    uv__getaddrinfo_done);
+    return 0;
+  } else {
+    uv__getaddrinfo_work(&req->work_req);
+    uv__getaddrinfo_done(&req->work_req, 0);
+    return req->retcode;
+  }
+}
+
+
+void uv_freeaddrinfo(struct addrinfo* ai) {
+  if (ai)
+    freeaddrinfo(ai);
+}
diff --git a/Utilities/cmlibuv/src/unix/getnameinfo.c b/Utilities/cmlibuv/src/unix/getnameinfo.c
new file mode 100644
index 0000000..b2879d6
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/getnameinfo.c
@@ -0,0 +1,120 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+
+static void uv__getnameinfo_work(struct uv__work* w) {
+  uv_getnameinfo_t* req;
+  int err;
+  socklen_t salen;
+
+  req = container_of(w, uv_getnameinfo_t, work_req);
+
+  if (req->storage.ss_family == AF_INET)
+    salen = sizeof(struct sockaddr_in);
+  else if (req->storage.ss_family == AF_INET6)
+    salen = sizeof(struct sockaddr_in6);
+  else
+    abort();
+
+  err = getnameinfo((struct sockaddr*) &req->storage,
+                    salen,
+                    req->host,
+                    sizeof(req->host),
+                    req->service,
+                    sizeof(req->service),
+                    req->flags);
+  req->retcode = uv__getaddrinfo_translate_error(err);
+}
+
+static void uv__getnameinfo_done(struct uv__work* w, int status) {
+  uv_getnameinfo_t* req;
+  char* host;
+  char* service;
+
+  req = container_of(w, uv_getnameinfo_t, work_req);
+  uv__req_unregister(req->loop, req);
+  host = service = NULL;
+
+  if (status == -ECANCELED) {
+    assert(req->retcode == 0);
+    req->retcode = UV_EAI_CANCELED;
+  } else if (req->retcode == 0) {
+    host = req->host;
+    service = req->service;
+  }
+
+  if (req->getnameinfo_cb)
+    req->getnameinfo_cb(req, req->retcode, host, service);
+}
+
+/*
+* Entry point for getnameinfo
+* return 0 if a callback will be made
+* return error code if validation fails
+*/
+int uv_getnameinfo(uv_loop_t* loop,
+                   uv_getnameinfo_t* req,
+                   uv_getnameinfo_cb getnameinfo_cb,
+                   const struct sockaddr* addr,
+                   int flags) {
+  if (req == NULL || addr == NULL)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET) {
+    memcpy(&req->storage,
+           addr,
+           sizeof(struct sockaddr_in));
+  } else if (addr->sa_family == AF_INET6) {
+    memcpy(&req->storage,
+           addr,
+           sizeof(struct sockaddr_in6));
+  } else {
+    return UV_EINVAL;
+  }
+
+  uv__req_init(loop, (uv_req_t*)req, UV_GETNAMEINFO);
+
+  req->getnameinfo_cb = getnameinfo_cb;
+  req->flags = flags;
+  req->type = UV_GETNAMEINFO;
+  req->loop = loop;
+  req->retcode = 0;
+
+  if (getnameinfo_cb) {
+    uv__work_submit(loop,
+                    &req->work_req,
+                    uv__getnameinfo_work,
+                    uv__getnameinfo_done);
+    return 0;
+  } else {
+    uv__getnameinfo_work(&req->work_req);
+    uv__getnameinfo_done(&req->work_req, 0);
+    return req->retcode;
+  }
+}
diff --git a/Utilities/cmlibuv/src/unix/internal.h b/Utilities/cmlibuv/src/unix/internal.h
new file mode 100644
index 0000000..2570026
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/internal.h
@@ -0,0 +1,322 @@
+/* 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_INTERNAL_H_
+#define UV_UNIX_INTERNAL_H_
+
+#include "uv-common.h"
+
+#include <assert.h>
+#include <stdlib.h> /* abort */
+#include <string.h> /* strrchr */
+#include <fcntl.h>  /* O_CLOEXEC, may be */
+#include <stdio.h>
+
+#if defined(__STRICT_ANSI__)
+# define inline __inline
+#endif
+
+#if defined(__linux__)
+# include "linux-syscalls.h"
+#endif /* __linux__ */
+
+#if defined(__sun)
+# include <sys/port.h>
+# include <port.h>
+#endif /* __sun */
+
+#if defined(_AIX)
+# define reqevents events
+# define rtnevents revents
+# include <sys/poll.h>
+#else
+# include <poll.h>
+#endif /* _AIX */
+
+#if defined(__ANDROID__)
+int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset);
+# ifdef pthread_sigmask
+# undef pthread_sigmask
+# endif
+# define pthread_sigmask(how, set, oldset) uv__pthread_sigmask(how, set, oldset)
+#endif
+
+#define ACCESS_ONCE(type, var)                                                \
+  (*(volatile type*) &(var))
+
+#define ROUND_UP(a, b)                                                        \
+  ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a))
+
+#define UNREACHABLE()                                                         \
+  do {                                                                        \
+    assert(0 && "unreachable code");                                          \
+    abort();                                                                  \
+  }                                                                           \
+  while (0)
+
+#define SAVE_ERRNO(block)                                                     \
+  do {                                                                        \
+    int _saved_errno = errno;                                                 \
+    do { block; } while (0);                                                  \
+    errno = _saved_errno;                                                     \
+  }                                                                           \
+  while (0)
+
+/* The __clang__ and __INTEL_COMPILER checks are superfluous because they
+ * define __GNUC__. They are here to convey to you, dear reader, that these
+ * macros are enabled when compiling with clang or icc.
+ */
+#if defined(__clang__) ||                                                     \
+    defined(__GNUC__) ||                                                      \
+    defined(__INTEL_COMPILER) ||                                              \
+    defined(__SUNPRO_C)
+# define UV_DESTRUCTOR(declaration) __attribute__((destructor)) declaration
+# define UV_UNUSED(declaration)     __attribute__((unused)) declaration
+#else
+# define UV_DESTRUCTOR(declaration) declaration
+# define UV_UNUSED(declaration)     declaration
+#endif
+
+/* Leans on the fact that, on Linux, POLLRDHUP == EPOLLRDHUP. */
+#ifdef POLLRDHUP
+# define UV__POLLRDHUP POLLRDHUP
+#else
+# define UV__POLLRDHUP 0x2000
+#endif
+
+#if !defined(O_CLOEXEC) && defined(__FreeBSD__)
+/*
+ * It may be that we are just missing `__POSIX_VISIBLE >= 200809`.
+ * Try using fixed value const and give up, if it doesn't work
+ */
+# define O_CLOEXEC 0x00100000
+#endif
+
+typedef struct uv__stream_queued_fds_s uv__stream_queued_fds_t;
+
+/* handle flags */
+enum {
+  UV_CLOSING              = 0x01,   /* uv_close() called but not finished. */
+  UV_CLOSED               = 0x02,   /* close(2) finished. */
+  UV_STREAM_READING       = 0x04,   /* uv_read_start() called. */
+  UV_STREAM_SHUTTING      = 0x08,   /* uv_shutdown() called but not complete. */
+  UV_STREAM_SHUT          = 0x10,   /* Write side closed. */
+  UV_STREAM_READABLE      = 0x20,   /* The stream is readable */
+  UV_STREAM_WRITABLE      = 0x40,   /* The stream is writable */
+  UV_STREAM_BLOCKING      = 0x80,   /* Synchronous writes. */
+  UV_STREAM_READ_PARTIAL  = 0x100,  /* read(2) read less than requested. */
+  UV_STREAM_READ_EOF      = 0x200,  /* read(2) read EOF. */
+  UV_TCP_NODELAY          = 0x400,  /* Disable Nagle. */
+  UV_TCP_KEEPALIVE        = 0x800,  /* Turn on keep-alive. */
+  UV_TCP_SINGLE_ACCEPT    = 0x1000, /* Only accept() when idle. */
+  UV_HANDLE_IPV6          = 0x10000, /* Handle is bound to a IPv6 socket. */
+  UV_UDP_PROCESSING       = 0x20000, /* Handle is running the send callback queue. */
+  UV_HANDLE_BOUND         = 0x40000  /* Handle is bound to an address and port */
+};
+
+/* loop flags */
+enum {
+  UV_LOOP_BLOCK_SIGPROF = 1
+};
+
+typedef enum {
+  UV_CLOCK_PRECISE = 0,  /* Use the highest resolution clock available. */
+  UV_CLOCK_FAST = 1      /* Use the fastest clock with <= 1ms granularity. */
+} uv_clocktype_t;
+
+struct uv__stream_queued_fds_s {
+  unsigned int size;
+  unsigned int offset;
+  int fds[1];
+};
+
+
+#if defined(_AIX) || \
+    defined(__APPLE__) || \
+    defined(__DragonFly__) || \
+    defined(__FreeBSD__) || \
+    defined(__FreeBSD_kernel__) || \
+    defined(__linux__)
+#define uv__cloexec uv__cloexec_ioctl
+#define uv__nonblock uv__nonblock_ioctl
+#else
+#define uv__cloexec uv__cloexec_fcntl
+#define uv__nonblock uv__nonblock_fcntl
+#endif
+
+/* core */
+int uv__cloexec_ioctl(int fd, int set);
+int uv__cloexec_fcntl(int fd, int set);
+int uv__nonblock_ioctl(int fd, int set);
+int uv__nonblock_fcntl(int fd, int set);
+int uv__close(int fd);
+int uv__close_nocheckstdio(int fd);
+int uv__socket(int domain, int type, int protocol);
+int uv__dup(int fd);
+ssize_t uv__recvmsg(int fd, struct msghdr *msg, int flags);
+void uv__make_close_pending(uv_handle_t* handle);
+int uv__getiovmax(void);
+
+void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd);
+void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events);
+void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events);
+void uv__io_close(uv_loop_t* loop, uv__io_t* w);
+void uv__io_feed(uv_loop_t* loop, uv__io_t* w);
+int uv__io_active(const uv__io_t* w, unsigned int events);
+int uv__io_check_fd(uv_loop_t* loop, int fd);
+void uv__io_poll(uv_loop_t* loop, int timeout); /* in milliseconds or -1 */
+
+/* async */
+void uv__async_send(struct uv__async* wa);
+void uv__async_init(struct uv__async* wa);
+int uv__async_start(uv_loop_t* loop, struct uv__async* wa, uv__async_cb cb);
+void uv__async_stop(uv_loop_t* loop, struct uv__async* wa);
+
+/* loop */
+void uv__run_idle(uv_loop_t* loop);
+void uv__run_check(uv_loop_t* loop);
+void uv__run_prepare(uv_loop_t* loop);
+
+/* stream */
+void uv__stream_init(uv_loop_t* loop, uv_stream_t* stream,
+    uv_handle_type type);
+int uv__stream_open(uv_stream_t*, int fd, int flags);
+void uv__stream_destroy(uv_stream_t* stream);
+#if defined(__APPLE__)
+int uv__stream_try_select(uv_stream_t* stream, int* fd);
+#endif /* defined(__APPLE__) */
+void uv__server_io(uv_loop_t* loop, uv__io_t* w, unsigned int events);
+int uv__accept(int sockfd);
+int uv__dup2_cloexec(int oldfd, int newfd);
+int uv__open_cloexec(const char* path, int flags);
+
+/* tcp */
+int uv_tcp_listen(uv_tcp_t* tcp, int backlog, uv_connection_cb cb);
+int uv__tcp_nodelay(int fd, int on);
+int uv__tcp_keepalive(int fd, int on, unsigned int delay);
+
+/* pipe */
+int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb);
+
+/* timer */
+void uv__run_timers(uv_loop_t* loop);
+int uv__next_timeout(const uv_loop_t* loop);
+
+/* signal */
+void uv__signal_close(uv_signal_t* handle);
+void uv__signal_global_once_init(void);
+void uv__signal_loop_cleanup(uv_loop_t* loop);
+
+/* platform specific */
+uint64_t uv__hrtime(uv_clocktype_t type);
+int uv__kqueue_init(uv_loop_t* loop);
+int uv__platform_loop_init(uv_loop_t* loop);
+void uv__platform_loop_delete(uv_loop_t* loop);
+void uv__platform_invalidate_fd(uv_loop_t* loop, int fd);
+
+/* various */
+void uv__async_close(uv_async_t* handle);
+void uv__check_close(uv_check_t* handle);
+void uv__fs_event_close(uv_fs_event_t* handle);
+void uv__idle_close(uv_idle_t* handle);
+void uv__pipe_close(uv_pipe_t* handle);
+void uv__poll_close(uv_poll_t* handle);
+void uv__prepare_close(uv_prepare_t* handle);
+void uv__process_close(uv_process_t* handle);
+void uv__stream_close(uv_stream_t* handle);
+void uv__tcp_close(uv_tcp_t* handle);
+void uv__timer_close(uv_timer_t* handle);
+void uv__udp_close(uv_udp_t* handle);
+void uv__udp_finish_close(uv_udp_t* handle);
+uv_handle_type uv__handle_type(int fd);
+FILE* uv__open_file(const char* path);
+int uv__getpwuid_r(uv_passwd_t* pwd);
+
+
+#if defined(__APPLE__)
+int uv___stream_fd(const uv_stream_t* handle);
+#define uv__stream_fd(handle) (uv___stream_fd((const uv_stream_t*) (handle)))
+#else
+#define uv__stream_fd(handle) ((handle)->io_watcher.fd)
+#endif /* defined(__APPLE__) */
+
+#ifdef UV__O_NONBLOCK
+# define UV__F_NONBLOCK UV__O_NONBLOCK
+#else
+# define UV__F_NONBLOCK 1
+#endif
+
+int uv__make_socketpair(int fds[2], int flags);
+int uv__make_pipe(int fds[2], int flags);
+
+#if defined(__APPLE__)
+#include <AvailabilityMacros.h>
+
+int uv__fsevents_init(uv_fs_event_t* handle);
+int uv__fsevents_close(uv_fs_event_t* handle);
+void uv__fsevents_loop_delete(uv_loop_t* loop);
+
+/* OSX < 10.7 has no file events, polyfill them */
+#ifndef MAC_OS_X_VERSION_10_7
+
+static const int kFSEventStreamCreateFlagFileEvents = 0x00000010;
+static const int kFSEventStreamEventFlagItemCreated = 0x00000100;
+static const int kFSEventStreamEventFlagItemRemoved = 0x00000200;
+static const int kFSEventStreamEventFlagItemInodeMetaMod = 0x00000400;
+static const int kFSEventStreamEventFlagItemRenamed = 0x00000800;
+static const int kFSEventStreamEventFlagItemModified = 0x00001000;
+static const int kFSEventStreamEventFlagItemFinderInfoMod = 0x00002000;
+static const int kFSEventStreamEventFlagItemChangeOwner = 0x00004000;
+static const int kFSEventStreamEventFlagItemXattrMod = 0x00008000;
+static const int kFSEventStreamEventFlagItemIsFile = 0x00010000;
+static const int kFSEventStreamEventFlagItemIsDir = 0x00020000;
+static const int kFSEventStreamEventFlagItemIsSymlink = 0x00040000;
+
+#endif /* __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070 */
+
+#endif /* defined(__APPLE__) */
+
+UV_UNUSED(static void uv__req_init(uv_loop_t* loop,
+                                   uv_req_t* req,
+                                   uv_req_type type)) {
+  req->type = type;
+  uv__req_register(loop, req);
+}
+#define uv__req_init(loop, req, type) \
+  uv__req_init((loop), (uv_req_t*)(req), (type))
+
+UV_UNUSED(static void uv__update_time(uv_loop_t* loop)) {
+  /* Use a fast time source if available.  We only need millisecond precision.
+   */
+  loop->time = uv__hrtime(UV_CLOCK_FAST) / 1000000;
+}
+
+UV_UNUSED(static char* uv__basename_r(const char* path)) {
+  char* s;
+
+  s = strrchr(path, '/');
+  if (s == NULL)
+    return (char*) path;
+
+  return s + 1;
+}
+
+#endif /* UV_UNIX_INTERNAL_H_ */
diff --git a/Utilities/cmlibuv/src/unix/kqueue.c b/Utilities/cmlibuv/src/unix/kqueue.c
new file mode 100644
index 0000000..fffd462
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/kqueue.c
@@ -0,0 +1,463 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include <sys/sysctl.h>
+#include <sys/types.h>
+#include <sys/event.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <time.h>
+
+static void uv__fs_event(uv_loop_t* loop, uv__io_t* w, unsigned int fflags);
+
+
+int uv__kqueue_init(uv_loop_t* loop) {
+  loop->backend_fd = kqueue();
+  if (loop->backend_fd == -1)
+    return -errno;
+
+  uv__cloexec(loop->backend_fd, 1);
+
+  return 0;
+}
+
+
+int uv__io_check_fd(uv_loop_t* loop, int fd) {
+  struct kevent ev;
+  int rc;
+
+  rc = 0;
+  EV_SET(&ev, fd, EVFILT_READ, EV_ADD, 0, 0, 0);
+  if (kevent(loop->backend_fd, &ev, 1, NULL, 0, NULL))
+    rc = -errno;
+
+  EV_SET(&ev, fd, EVFILT_READ, EV_DELETE, 0, 0, 0);
+  if (rc == 0)
+    if (kevent(loop->backend_fd, &ev, 1, NULL, 0, NULL))
+      abort();
+
+  return rc;
+}
+
+
+void uv__io_poll(uv_loop_t* loop, int timeout) {
+  struct kevent events[1024];
+  struct kevent* ev;
+  struct timespec spec;
+  unsigned int nevents;
+  unsigned int revents;
+  QUEUE* q;
+  uv__io_t* w;
+  sigset_t* pset;
+  sigset_t set;
+  uint64_t base;
+  uint64_t diff;
+  int have_signals;
+  int filter;
+  int fflags;
+  int count;
+  int nfds;
+  int fd;
+  int op;
+  int i;
+
+  if (loop->nfds == 0) {
+    assert(QUEUE_EMPTY(&loop->watcher_queue));
+    return;
+  }
+
+  nevents = 0;
+
+  while (!QUEUE_EMPTY(&loop->watcher_queue)) {
+    q = QUEUE_HEAD(&loop->watcher_queue);
+    QUEUE_REMOVE(q);
+    QUEUE_INIT(q);
+
+    w = QUEUE_DATA(q, uv__io_t, watcher_queue);
+    assert(w->pevents != 0);
+    assert(w->fd >= 0);
+    assert(w->fd < (int) loop->nwatchers);
+
+    if ((w->events & POLLIN) == 0 && (w->pevents & POLLIN) != 0) {
+      filter = EVFILT_READ;
+      fflags = 0;
+      op = EV_ADD;
+
+      if (w->cb == uv__fs_event) {
+        filter = EVFILT_VNODE;
+        fflags = NOTE_ATTRIB | NOTE_WRITE  | NOTE_RENAME
+               | NOTE_DELETE | NOTE_EXTEND | NOTE_REVOKE;
+        op = EV_ADD | EV_ONESHOT; /* Stop the event from firing repeatedly. */
+      }
+
+      EV_SET(events + nevents, w->fd, filter, op, fflags, 0, 0);
+
+      if (++nevents == ARRAY_SIZE(events)) {
+        if (kevent(loop->backend_fd, events, nevents, NULL, 0, NULL))
+          abort();
+        nevents = 0;
+      }
+    }
+
+    if ((w->events & POLLOUT) == 0 && (w->pevents & POLLOUT) != 0) {
+      EV_SET(events + nevents, w->fd, EVFILT_WRITE, EV_ADD, 0, 0, 0);
+
+      if (++nevents == ARRAY_SIZE(events)) {
+        if (kevent(loop->backend_fd, events, nevents, NULL, 0, NULL))
+          abort();
+        nevents = 0;
+      }
+    }
+
+    w->events = w->pevents;
+  }
+
+  pset = NULL;
+  if (loop->flags & UV_LOOP_BLOCK_SIGPROF) {
+    pset = &set;
+    sigemptyset(pset);
+    sigaddset(pset, SIGPROF);
+  }
+
+  assert(timeout >= -1);
+  base = loop->time;
+  count = 48; /* Benchmarks suggest this gives the best throughput. */
+
+  for (;; nevents = 0) {
+    if (timeout != -1) {
+      spec.tv_sec = timeout / 1000;
+      spec.tv_nsec = (timeout % 1000) * 1000000;
+    }
+
+    if (pset != NULL)
+      pthread_sigmask(SIG_BLOCK, pset, NULL);
+
+    nfds = kevent(loop->backend_fd,
+                  events,
+                  nevents,
+                  events,
+                  ARRAY_SIZE(events),
+                  timeout == -1 ? NULL : &spec);
+
+    if (pset != NULL)
+      pthread_sigmask(SIG_UNBLOCK, pset, NULL);
+
+    /* Update loop->time unconditionally. It's tempting to skip the update when
+     * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
+     * operating system didn't reschedule our process while in the syscall.
+     */
+    SAVE_ERRNO(uv__update_time(loop));
+
+    if (nfds == 0) {
+      assert(timeout != -1);
+      return;
+    }
+
+    if (nfds == -1) {
+      if (errno != EINTR)
+        abort();
+
+      if (timeout == 0)
+        return;
+
+      if (timeout == -1)
+        continue;
+
+      /* Interrupted by a signal. Update timeout and poll again. */
+      goto update_timeout;
+    }
+
+    have_signals = 0;
+    nevents = 0;
+
+    assert(loop->watchers != NULL);
+    loop->watchers[loop->nwatchers] = (void*) events;
+    loop->watchers[loop->nwatchers + 1] = (void*) (uintptr_t) nfds;
+    for (i = 0; i < nfds; i++) {
+      ev = events + i;
+      fd = ev->ident;
+      /* Skip invalidated events, see uv__platform_invalidate_fd */
+      if (fd == -1)
+        continue;
+      w = loop->watchers[fd];
+
+      if (w == NULL) {
+        /* File descriptor that we've stopped watching, disarm it. */
+        /* TODO batch up */
+        struct kevent events[1];
+
+        EV_SET(events + 0, fd, ev->filter, EV_DELETE, 0, 0, 0);
+        if (kevent(loop->backend_fd, events, 1, NULL, 0, NULL))
+          if (errno != EBADF && errno != ENOENT)
+            abort();
+
+        continue;
+      }
+
+      if (ev->filter == EVFILT_VNODE) {
+        assert(w->events == POLLIN);
+        assert(w->pevents == POLLIN);
+        w->cb(loop, w, ev->fflags); /* XXX always uv__fs_event() */
+        nevents++;
+        continue;
+      }
+
+      revents = 0;
+
+      if (ev->filter == EVFILT_READ) {
+        if (w->pevents & POLLIN) {
+          revents |= POLLIN;
+          w->rcount = ev->data;
+        } else {
+          /* TODO batch up */
+          struct kevent events[1];
+          EV_SET(events + 0, fd, ev->filter, EV_DELETE, 0, 0, 0);
+          if (kevent(loop->backend_fd, events, 1, NULL, 0, NULL))
+            if (errno != ENOENT)
+              abort();
+        }
+      }
+
+      if (ev->filter == EVFILT_WRITE) {
+        if (w->pevents & POLLOUT) {
+          revents |= POLLOUT;
+          w->wcount = ev->data;
+        } else {
+          /* TODO batch up */
+          struct kevent events[1];
+          EV_SET(events + 0, fd, ev->filter, EV_DELETE, 0, 0, 0);
+          if (kevent(loop->backend_fd, events, 1, NULL, 0, NULL))
+            if (errno != ENOENT)
+              abort();
+        }
+      }
+
+      if (ev->flags & EV_ERROR)
+        revents |= POLLERR;
+
+      if ((ev->flags & EV_EOF) && (w->pevents & UV__POLLRDHUP))
+        revents |= UV__POLLRDHUP;
+
+      if (revents == 0)
+        continue;
+
+      /* Run signal watchers last.  This also affects child process watchers
+       * because those are implemented in terms of signal watchers.
+       */
+      if (w == &loop->signal_io_watcher)
+        have_signals = 1;
+      else
+        w->cb(loop, w, revents);
+
+      nevents++;
+    }
+
+    if (have_signals != 0)
+      loop->signal_io_watcher.cb(loop, &loop->signal_io_watcher, POLLIN);
+
+    loop->watchers[loop->nwatchers] = NULL;
+    loop->watchers[loop->nwatchers + 1] = NULL;
+
+    if (have_signals != 0)
+      return;  /* Event loop should cycle now so don't poll again. */
+
+    if (nevents != 0) {
+      if (nfds == ARRAY_SIZE(events) && --count != 0) {
+        /* Poll for more events but don't block this time. */
+        timeout = 0;
+        continue;
+      }
+      return;
+    }
+
+    if (timeout == 0)
+      return;
+
+    if (timeout == -1)
+      continue;
+
+update_timeout:
+    assert(timeout > 0);
+
+    diff = loop->time - base;
+    if (diff >= (uint64_t) timeout)
+      return;
+
+    timeout -= diff;
+  }
+}
+
+
+void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) {
+  struct kevent* events;
+  uintptr_t i;
+  uintptr_t nfds;
+
+  assert(loop->watchers != NULL);
+
+  events = (struct kevent*) loop->watchers[loop->nwatchers];
+  nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
+  if (events == NULL)
+    return;
+
+  /* Invalidate events with same file descriptor */
+  for (i = 0; i < nfds; i++)
+    if ((int) events[i].ident == fd)
+      events[i].ident = -1;
+}
+
+
+static void uv__fs_event(uv_loop_t* loop, uv__io_t* w, unsigned int fflags) {
+  uv_fs_event_t* handle;
+  struct kevent ev;
+  int events;
+  const char* path;
+#if defined(F_GETPATH)
+  /* MAXPATHLEN == PATH_MAX but the former is what XNU calls it internally. */
+  char pathbuf[MAXPATHLEN];
+#endif
+
+  handle = container_of(w, uv_fs_event_t, event_watcher);
+
+  if (fflags & (NOTE_ATTRIB | NOTE_EXTEND))
+    events = UV_CHANGE;
+  else
+    events = UV_RENAME;
+
+  path = NULL;
+#if defined(F_GETPATH)
+  /* Also works when the file has been unlinked from the file system. Passing
+   * in the path when the file has been deleted is arguably a little strange
+   * but it's consistent with what the inotify backend does.
+   */
+  if (fcntl(handle->event_watcher.fd, F_GETPATH, pathbuf) == 0)
+    path = uv__basename_r(pathbuf);
+#endif
+  handle->cb(handle, path, events, 0);
+
+  if (handle->event_watcher.fd == -1)
+    return;
+
+  /* Watcher operates in one-shot mode, re-arm it. */
+  fflags = NOTE_ATTRIB | NOTE_WRITE  | NOTE_RENAME
+         | NOTE_DELETE | NOTE_EXTEND | NOTE_REVOKE;
+
+  EV_SET(&ev, w->fd, EVFILT_VNODE, EV_ADD | EV_ONESHOT, fflags, 0, 0);
+
+  if (kevent(loop->backend_fd, &ev, 1, NULL, 0, NULL))
+    abort();
+}
+
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_EVENT);
+  return 0;
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* path,
+                      unsigned int flags) {
+#if defined(__APPLE__)
+  struct stat statbuf;
+#endif /* defined(__APPLE__) */
+  int fd;
+
+  if (uv__is_active(handle))
+    return -EINVAL;
+
+  /* TODO open asynchronously - but how do we report back errors? */
+  fd = open(path, O_RDONLY);
+  if (fd == -1)
+    return -errno;
+
+  uv__handle_start(handle);
+  uv__io_init(&handle->event_watcher, uv__fs_event, fd);
+  handle->path = uv__strdup(path);
+  handle->cb = cb;
+
+#if defined(__APPLE__)
+  /* Nullify field to perform checks later */
+  handle->cf_cb = NULL;
+  handle->realpath = NULL;
+  handle->realpath_len = 0;
+  handle->cf_flags = flags;
+
+  if (fstat(fd, &statbuf))
+    goto fallback;
+  /* FSEvents works only with directories */
+  if (!(statbuf.st_mode & S_IFDIR))
+    goto fallback;
+
+  /* The fallback fd is no longer needed */
+  uv__close(fd);
+  handle->event_watcher.fd = -1;
+
+  return uv__fsevents_init(handle);
+
+fallback:
+#endif /* defined(__APPLE__) */
+
+  uv__io_start(handle->loop, &handle->event_watcher, POLLIN);
+
+  return 0;
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+  if (!uv__is_active(handle))
+    return 0;
+
+  uv__handle_stop(handle);
+
+#if defined(__APPLE__)
+  if (uv__fsevents_close(handle))
+#endif /* defined(__APPLE__) */
+  {
+    uv__io_close(handle->loop, &handle->event_watcher);
+  }
+
+  uv__free(handle->path);
+  handle->path = NULL;
+
+  if (handle->event_watcher.fd != -1) {
+    /* When FSEvents is used, we don't use the event_watcher's fd under certain
+     * confitions. (see uv_fs_event_start) */
+    uv__close(handle->event_watcher.fd);
+    handle->event_watcher.fd = -1;
+  }
+
+  return 0;
+}
+
+
+void uv__fs_event_close(uv_fs_event_t* handle) {
+  uv_fs_event_stop(handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/linux-core.c b/Utilities/cmlibuv/src/unix/linux-core.c
new file mode 100644
index 0000000..58dd813
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/linux-core.c
@@ -0,0 +1,985 @@
+/* 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.
+ */
+
+/* We lean on the fact that POLL{IN,OUT,ERR,HUP} correspond with their
+ * EPOLL* counterparts.  We use the POLL* variants in this file because that
+ * is what libuv uses elsewhere and it avoids a dependency on <sys/epoll.h>.
+ */
+
+#include "uv.h"
+#include "internal.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <net/if.h>
+#include <sys/param.h>
+#include <sys/prctl.h>
+#include <sys/sysinfo.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <time.h>
+
+#define HAVE_IFADDRS_H 1
+
+#ifdef __UCLIBC__
+# if __UCLIBC_MAJOR__ < 0 && __UCLIBC_MINOR__ < 9 && __UCLIBC_SUBLEVEL__ < 32
+#  undef HAVE_IFADDRS_H
+# endif
+#endif
+
+#ifdef HAVE_IFADDRS_H
+# if defined(__ANDROID__)
+#  include "android-ifaddrs.h"
+# else
+#  include <ifaddrs.h>
+# endif
+# include <sys/socket.h>
+# include <net/ethernet.h>
+# include <netpacket/packet.h>
+#endif /* HAVE_IFADDRS_H */
+
+/* Available from 2.6.32 onwards. */
+#ifndef CLOCK_MONOTONIC_COARSE
+# define CLOCK_MONOTONIC_COARSE 6
+#endif
+
+/* This is rather annoying: CLOCK_BOOTTIME lives in <linux/time.h> but we can't
+ * include that file because it conflicts with <time.h>. We'll just have to
+ * define it ourselves.
+ */
+#ifndef CLOCK_BOOTTIME
+# define CLOCK_BOOTTIME 7
+#endif
+
+static int read_models(unsigned int numcpus, uv_cpu_info_t* ci);
+static int read_times(FILE* statfile_fp,
+                      unsigned int numcpus,
+                      uv_cpu_info_t* ci);
+static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci);
+static unsigned long read_cpufreq(unsigned int cpunum);
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  int fd;
+
+  fd = uv__epoll_create1(UV__EPOLL_CLOEXEC);
+
+  /* epoll_create1() can fail either because it's not implemented (old kernel)
+   * or because it doesn't understand the EPOLL_CLOEXEC flag.
+   */
+  if (fd == -1 && (errno == ENOSYS || errno == EINVAL)) {
+    fd = uv__epoll_create(256);
+
+    if (fd != -1)
+      uv__cloexec(fd, 1);
+  }
+
+  loop->backend_fd = fd;
+  loop->inotify_fd = -1;
+  loop->inotify_watchers = NULL;
+
+  if (fd == -1)
+    return -errno;
+
+  return 0;
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+  if (loop->inotify_fd == -1) return;
+  uv__io_stop(loop, &loop->inotify_read_watcher, POLLIN);
+  uv__close(loop->inotify_fd);
+  loop->inotify_fd = -1;
+}
+
+
+void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) {
+  struct uv__epoll_event* events;
+  struct uv__epoll_event dummy;
+  uintptr_t i;
+  uintptr_t nfds;
+
+  assert(loop->watchers != NULL);
+
+  events = (struct uv__epoll_event*) loop->watchers[loop->nwatchers];
+  nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
+  if (events != NULL)
+    /* Invalidate events with same file descriptor */
+    for (i = 0; i < nfds; i++)
+      if ((int) events[i].data == fd)
+        events[i].data = -1;
+
+  /* Remove the file descriptor from the epoll.
+   * This avoids a problem where the same file description remains open
+   * in another process, causing repeated junk epoll events.
+   *
+   * We pass in a dummy epoll_event, to work around a bug in old kernels.
+   */
+  if (loop->backend_fd >= 0) {
+    /* Work around a bug in kernels 3.10 to 3.19 where passing a struct that
+     * has the EPOLLWAKEUP flag set generates spurious audit syslog warnings.
+     */
+    memset(&dummy, 0, sizeof(dummy));
+    uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, &dummy);
+  }
+}
+
+
+int uv__io_check_fd(uv_loop_t* loop, int fd) {
+  struct uv__epoll_event e;
+  int rc;
+
+  e.events = POLLIN;
+  e.data = -1;
+
+  rc = 0;
+  if (uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_ADD, fd, &e))
+    if (errno != EEXIST)
+      rc = -errno;
+
+  if (rc == 0)
+    if (uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, &e))
+      abort();
+
+  return rc;
+}
+
+
+void uv__io_poll(uv_loop_t* loop, int timeout) {
+  /* A bug in kernels < 2.6.37 makes timeouts larger than ~30 minutes
+   * effectively infinite on 32 bits architectures.  To avoid blocking
+   * indefinitely, we cap the timeout and poll again if necessary.
+   *
+   * Note that "30 minutes" is a simplification because it depends on
+   * the value of CONFIG_HZ.  The magic constant assumes CONFIG_HZ=1200,
+   * that being the largest value I have seen in the wild (and only once.)
+   */
+  static const int max_safe_timeout = 1789569;
+  static int no_epoll_pwait;
+  static int no_epoll_wait;
+  struct uv__epoll_event events[1024];
+  struct uv__epoll_event* pe;
+  struct uv__epoll_event e;
+  int real_timeout;
+  QUEUE* q;
+  uv__io_t* w;
+  sigset_t sigset;
+  uint64_t sigmask;
+  uint64_t base;
+  int have_signals;
+  int nevents;
+  int count;
+  int nfds;
+  int fd;
+  int op;
+  int i;
+
+  if (loop->nfds == 0) {
+    assert(QUEUE_EMPTY(&loop->watcher_queue));
+    return;
+  }
+
+  while (!QUEUE_EMPTY(&loop->watcher_queue)) {
+    q = QUEUE_HEAD(&loop->watcher_queue);
+    QUEUE_REMOVE(q);
+    QUEUE_INIT(q);
+
+    w = QUEUE_DATA(q, uv__io_t, watcher_queue);
+    assert(w->pevents != 0);
+    assert(w->fd >= 0);
+    assert(w->fd < (int) loop->nwatchers);
+
+    e.events = w->pevents;
+    e.data = w->fd;
+
+    if (w->events == 0)
+      op = UV__EPOLL_CTL_ADD;
+    else
+      op = UV__EPOLL_CTL_MOD;
+
+    /* XXX Future optimization: do EPOLL_CTL_MOD lazily if we stop watching
+     * events, skip the syscall and squelch the events after epoll_wait().
+     */
+    if (uv__epoll_ctl(loop->backend_fd, op, w->fd, &e)) {
+      if (errno != EEXIST)
+        abort();
+
+      assert(op == UV__EPOLL_CTL_ADD);
+
+      /* We've reactivated a file descriptor that's been watched before. */
+      if (uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_MOD, w->fd, &e))
+        abort();
+    }
+
+    w->events = w->pevents;
+  }
+
+  sigmask = 0;
+  if (loop->flags & UV_LOOP_BLOCK_SIGPROF) {
+    sigemptyset(&sigset);
+    sigaddset(&sigset, SIGPROF);
+    sigmask |= 1 << (SIGPROF - 1);
+  }
+
+  assert(timeout >= -1);
+  base = loop->time;
+  count = 48; /* Benchmarks suggest this gives the best throughput. */
+  real_timeout = timeout;
+
+  for (;;) {
+    /* See the comment for max_safe_timeout for an explanation of why
+     * this is necessary.  Executive summary: kernel bug workaround.
+     */
+    if (sizeof(int32_t) == sizeof(long) && timeout >= max_safe_timeout)
+      timeout = max_safe_timeout;
+
+    if (sigmask != 0 && no_epoll_pwait != 0)
+      if (pthread_sigmask(SIG_BLOCK, &sigset, NULL))
+        abort();
+
+    if (no_epoll_wait != 0 || (sigmask != 0 && no_epoll_pwait == 0)) {
+      nfds = uv__epoll_pwait(loop->backend_fd,
+                             events,
+                             ARRAY_SIZE(events),
+                             timeout,
+                             sigmask);
+      if (nfds == -1 && errno == ENOSYS)
+        no_epoll_pwait = 1;
+    } else {
+      nfds = uv__epoll_wait(loop->backend_fd,
+                            events,
+                            ARRAY_SIZE(events),
+                            timeout);
+      if (nfds == -1 && errno == ENOSYS)
+        no_epoll_wait = 1;
+    }
+
+    if (sigmask != 0 && no_epoll_pwait != 0)
+      if (pthread_sigmask(SIG_UNBLOCK, &sigset, NULL))
+        abort();
+
+    /* Update loop->time unconditionally. It's tempting to skip the update when
+     * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
+     * operating system didn't reschedule our process while in the syscall.
+     */
+    SAVE_ERRNO(uv__update_time(loop));
+
+    if (nfds == 0) {
+      assert(timeout != -1);
+
+      if (timeout == 0)
+        return;
+
+      /* We may have been inside the system call for longer than |timeout|
+       * milliseconds so we need to update the timestamp to avoid drift.
+       */
+      goto update_timeout;
+    }
+
+    if (nfds == -1) {
+      if (errno == ENOSYS) {
+        /* epoll_wait() or epoll_pwait() failed, try the other system call. */
+        assert(no_epoll_wait == 0 || no_epoll_pwait == 0);
+        continue;
+      }
+
+      if (errno != EINTR)
+        abort();
+
+      if (timeout == -1)
+        continue;
+
+      if (timeout == 0)
+        return;
+
+      /* Interrupted by a signal. Update timeout and poll again. */
+      goto update_timeout;
+    }
+
+    have_signals = 0;
+    nevents = 0;
+
+    assert(loop->watchers != NULL);
+    loop->watchers[loop->nwatchers] = (void*) events;
+    loop->watchers[loop->nwatchers + 1] = (void*) (uintptr_t) nfds;
+    for (i = 0; i < nfds; i++) {
+      pe = events + i;
+      fd = pe->data;
+
+      /* Skip invalidated events, see uv__platform_invalidate_fd */
+      if (fd == -1)
+        continue;
+
+      assert(fd >= 0);
+      assert((unsigned) fd < loop->nwatchers);
+
+      w = loop->watchers[fd];
+
+      if (w == NULL) {
+        /* File descriptor that we've stopped watching, disarm it.
+         *
+         * Ignore all errors because we may be racing with another thread
+         * when the file descriptor is closed.
+         */
+        uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, pe);
+        continue;
+      }
+
+      /* Give users only events they're interested in. Prevents spurious
+       * callbacks when previous callback invocation in this loop has stopped
+       * the current watcher. Also, filters out events that users has not
+       * requested us to watch.
+       */
+      pe->events &= w->pevents | POLLERR | POLLHUP;
+
+      /* Work around an epoll quirk where it sometimes reports just the
+       * EPOLLERR or EPOLLHUP event.  In order to force the event loop to
+       * move forward, we merge in the read/write events that the watcher
+       * is interested in; uv__read() and uv__write() will then deal with
+       * the error or hangup in the usual fashion.
+       *
+       * Note to self: happens when epoll reports EPOLLIN|EPOLLHUP, the user
+       * reads the available data, calls uv_read_stop(), then sometime later
+       * calls uv_read_start() again.  By then, libuv has forgotten about the
+       * hangup and the kernel won't report EPOLLIN again because there's
+       * nothing left to read.  If anything, libuv is to blame here.  The
+       * current hack is just a quick bandaid; to properly fix it, libuv
+       * needs to remember the error/hangup event.  We should get that for
+       * free when we switch over to edge-triggered I/O.
+       */
+      if (pe->events == POLLERR || pe->events == POLLHUP)
+        pe->events |= w->pevents & (POLLIN | POLLOUT);
+
+      if (pe->events != 0) {
+        /* Run signal watchers last.  This also affects child process watchers
+         * because those are implemented in terms of signal watchers.
+         */
+        if (w == &loop->signal_io_watcher)
+          have_signals = 1;
+        else
+          w->cb(loop, w, pe->events);
+
+        nevents++;
+      }
+    }
+
+    if (have_signals != 0)
+      loop->signal_io_watcher.cb(loop, &loop->signal_io_watcher, POLLIN);
+
+    loop->watchers[loop->nwatchers] = NULL;
+    loop->watchers[loop->nwatchers + 1] = NULL;
+
+    if (have_signals != 0)
+      return;  /* Event loop should cycle now so don't poll again. */
+
+    if (nevents != 0) {
+      if (nfds == ARRAY_SIZE(events) && --count != 0) {
+        /* Poll for more events but don't block this time. */
+        timeout = 0;
+        continue;
+      }
+      return;
+    }
+
+    if (timeout == 0)
+      return;
+
+    if (timeout == -1)
+      continue;
+
+update_timeout:
+    assert(timeout > 0);
+
+    real_timeout -= (loop->time - base);
+    if (real_timeout <= 0)
+      return;
+
+    timeout = real_timeout;
+  }
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  static clock_t fast_clock_id = -1;
+  struct timespec t;
+  clock_t clock_id;
+
+  /* Prefer CLOCK_MONOTONIC_COARSE if available but only when it has
+   * millisecond granularity or better.  CLOCK_MONOTONIC_COARSE is
+   * serviced entirely from the vDSO, whereas CLOCK_MONOTONIC may
+   * decide to make a costly system call.
+   */
+  /* TODO(bnoordhuis) Use CLOCK_MONOTONIC_COARSE for UV_CLOCK_PRECISE
+   * when it has microsecond granularity or better (unlikely).
+   */
+  if (type == UV_CLOCK_FAST && fast_clock_id == -1) {
+    if (clock_getres(CLOCK_MONOTONIC_COARSE, &t) == 0 &&
+        t.tv_nsec <= 1 * 1000 * 1000) {
+      fast_clock_id = CLOCK_MONOTONIC_COARSE;
+    } else {
+      fast_clock_id = CLOCK_MONOTONIC;
+    }
+  }
+
+  clock_id = CLOCK_MONOTONIC;
+  if (type == UV_CLOCK_FAST)
+    clock_id = fast_clock_id;
+
+  if (clock_gettime(clock_id, &t))
+    return 0;  /* Not really possible. */
+
+  return t.tv_sec * (uint64_t) 1e9 + t.tv_nsec;
+}
+
+
+void uv_loadavg(double avg[3]) {
+  struct sysinfo info;
+
+  if (sysinfo(&info) < 0) return;
+
+  avg[0] = (double) info.loads[0] / 65536.0;
+  avg[1] = (double) info.loads[1] / 65536.0;
+  avg[2] = (double) info.loads[2] / 65536.0;
+}
+
+
+int uv_exepath(char* buffer, size_t* size) {
+  ssize_t n;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  n = *size - 1;
+  if (n > 0)
+    n = readlink("/proc/self/exe", buffer, n);
+
+  if (n == -1)
+    return -errno;
+
+  buffer[n] = '\0';
+  *size = n;
+
+  return 0;
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  struct sysinfo info;
+
+  if (sysinfo(&info) == 0)
+    return (uint64_t) info.freeram * info.mem_unit;
+  return 0;
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  struct sysinfo info;
+
+  if (sysinfo(&info) == 0)
+    return (uint64_t) info.totalram * info.mem_unit;
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  char buf[1024];
+  const char* s;
+  ssize_t n;
+  long val;
+  int fd;
+  int i;
+
+  do
+    fd = open("/proc/self/stat", O_RDONLY);
+  while (fd == -1 && errno == EINTR);
+
+  if (fd == -1)
+    return -errno;
+
+  do
+    n = read(fd, buf, sizeof(buf) - 1);
+  while (n == -1 && errno == EINTR);
+
+  uv__close(fd);
+  if (n == -1)
+    return -errno;
+  buf[n] = '\0';
+
+  s = strchr(buf, ' ');
+  if (s == NULL)
+    goto err;
+
+  s += 1;
+  if (*s != '(')
+    goto err;
+
+  s = strchr(s, ')');
+  if (s == NULL)
+    goto err;
+
+  for (i = 1; i <= 22; i++) {
+    s = strchr(s + 1, ' ');
+    if (s == NULL)
+      goto err;
+  }
+
+  errno = 0;
+  val = strtol(s, NULL, 10);
+  if (errno != 0)
+    goto err;
+  if (val < 0)
+    goto err;
+
+  *rss = val * getpagesize();
+  return 0;
+
+err:
+  return -EINVAL;
+}
+
+
+int uv_uptime(double* uptime) {
+  static volatile int no_clock_boottime;
+  struct timespec now;
+  int r;
+
+  /* Try CLOCK_BOOTTIME first, fall back to CLOCK_MONOTONIC if not available
+   * (pre-2.6.39 kernels). CLOCK_MONOTONIC doesn't increase when the system
+   * is suspended.
+   */
+  if (no_clock_boottime) {
+    retry: r = clock_gettime(CLOCK_MONOTONIC, &now);
+  }
+  else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
+    no_clock_boottime = 1;
+    goto retry;
+  }
+
+  if (r)
+    return -errno;
+
+  *uptime = now.tv_sec;
+  return 0;
+}
+
+
+static int uv__cpu_num(FILE* statfile_fp, unsigned int* numcpus) {
+  unsigned int num;
+  char buf[1024];
+
+  if (!fgets(buf, sizeof(buf), statfile_fp))
+    return -EIO;
+
+  num = 0;
+  while (fgets(buf, sizeof(buf), statfile_fp)) {
+    if (strncmp(buf, "cpu", 3))
+      break;
+    num++;
+  }
+
+  if (num == 0)
+    return -EIO;
+
+  *numcpus = num;
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  unsigned int numcpus;
+  uv_cpu_info_t* ci;
+  int err;
+  FILE* statfile_fp;
+
+  *cpu_infos = NULL;
+  *count = 0;
+
+  statfile_fp = uv__open_file("/proc/stat");
+  if (statfile_fp == NULL)
+    return -errno;
+
+  err = uv__cpu_num(statfile_fp, &numcpus);
+  if (err < 0)
+    goto out;
+
+  err = -ENOMEM;
+  ci = uv__calloc(numcpus, sizeof(*ci));
+  if (ci == NULL)
+    goto out;
+
+  err = read_models(numcpus, ci);
+  if (err == 0)
+    err = read_times(statfile_fp, numcpus, ci);
+
+  if (err) {
+    uv_free_cpu_info(ci, numcpus);
+    goto out;
+  }
+
+  /* read_models() on x86 also reads the CPU speed from /proc/cpuinfo.
+   * We don't check for errors here. Worst case, the field is left zero.
+   */
+  if (ci[0].speed == 0)
+    read_speeds(numcpus, ci);
+
+  *cpu_infos = ci;
+  *count = numcpus;
+  err = 0;
+
+out:
+
+  if (fclose(statfile_fp))
+    if (errno != EINTR && errno != EINPROGRESS)
+      abort();
+
+  return err;
+}
+
+
+static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
+  unsigned int num;
+
+  for (num = 0; num < numcpus; num++)
+    ci[num].speed = read_cpufreq(num) / 1000;
+}
+
+
+/* Also reads the CPU frequency on x86. The other architectures only have
+ * a BogoMIPS field, which may not be very accurate.
+ *
+ * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
+ */
+static int read_models(unsigned int numcpus, uv_cpu_info_t* ci) {
+  static const char model_marker[] = "model name\t: ";
+  static const char speed_marker[] = "cpu MHz\t\t: ";
+  const char* inferred_model;
+  unsigned int model_idx;
+  unsigned int speed_idx;
+  char buf[1024];
+  char* model;
+  FILE* fp;
+
+  /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
+  (void) &model_marker;
+  (void) &speed_marker;
+  (void) &speed_idx;
+  (void) &model;
+  (void) &buf;
+  (void) &fp;
+
+  model_idx = 0;
+  speed_idx = 0;
+
+#if defined(__arm__) || \
+    defined(__i386__) || \
+    defined(__mips__) || \
+    defined(__x86_64__)
+  fp = uv__open_file("/proc/cpuinfo");
+  if (fp == NULL)
+    return -errno;
+
+  while (fgets(buf, sizeof(buf), fp)) {
+    if (model_idx < numcpus) {
+      if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
+        model = buf + sizeof(model_marker) - 1;
+        model = uv__strndup(model, strlen(model) - 1);  /* Strip newline. */
+        if (model == NULL) {
+          fclose(fp);
+          return -ENOMEM;
+        }
+        ci[model_idx++].model = model;
+        continue;
+      }
+    }
+#if defined(__arm__) || defined(__mips__)
+    if (model_idx < numcpus) {
+#if defined(__arm__)
+      /* Fallback for pre-3.8 kernels. */
+      static const char model_marker[] = "Processor\t: ";
+#else	/* defined(__mips__) */
+      static const char model_marker[] = "cpu model\t\t: ";
+#endif
+      if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
+        model = buf + sizeof(model_marker) - 1;
+        model = uv__strndup(model, strlen(model) - 1);  /* Strip newline. */
+        if (model == NULL) {
+          fclose(fp);
+          return -ENOMEM;
+        }
+        ci[model_idx++].model = model;
+        continue;
+      }
+    }
+#else  /* !__arm__ && !__mips__ */
+    if (speed_idx < numcpus) {
+      if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
+        ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
+        continue;
+      }
+    }
+#endif  /* __arm__ || __mips__ */
+  }
+
+  fclose(fp);
+#endif  /* __arm__ || __i386__ || __mips__ || __x86_64__ */
+
+  /* Now we want to make sure that all the models contain *something* because
+   * it's not safe to leave them as null. Copy the last entry unless there
+   * isn't one, in that case we simply put "unknown" into everything.
+   */
+  inferred_model = "unknown";
+  if (model_idx > 0)
+    inferred_model = ci[model_idx - 1].model;
+
+  while (model_idx < numcpus) {
+    model = uv__strndup(inferred_model, strlen(inferred_model));
+    if (model == NULL)
+      return -ENOMEM;
+    ci[model_idx++].model = model;
+  }
+
+  return 0;
+}
+
+
+static int read_times(FILE* statfile_fp,
+                      unsigned int numcpus,
+                      uv_cpu_info_t* ci) {
+  unsigned long clock_ticks;
+  struct uv_cpu_times_s ts;
+  unsigned long user;
+  unsigned long nice;
+  unsigned long sys;
+  unsigned long idle;
+  unsigned long dummy;
+  unsigned long irq;
+  unsigned int num;
+  unsigned int len;
+  char buf[1024];
+
+  clock_ticks = sysconf(_SC_CLK_TCK);
+  assert(clock_ticks != (unsigned long) -1);
+  assert(clock_ticks != 0);
+
+  rewind(statfile_fp);
+
+  if (!fgets(buf, sizeof(buf), statfile_fp))
+    abort();
+
+  num = 0;
+
+  while (fgets(buf, sizeof(buf), statfile_fp)) {
+    if (num >= numcpus)
+      break;
+
+    if (strncmp(buf, "cpu", 3))
+      break;
+
+    /* skip "cpu<num> " marker */
+    {
+      unsigned int n;
+      int r = sscanf(buf, "cpu%u ", &n);
+      assert(r == 1);
+      (void) r;  /* silence build warning */
+      for (len = sizeof("cpu0"); n /= 10; len++);
+    }
+
+    /* Line contains user, nice, system, idle, iowait, irq, softirq, steal,
+     * guest, guest_nice but we're only interested in the first four + irq.
+     *
+     * Don't use %*s to skip fields or %ll to read straight into the uint64_t
+     * fields, they're not allowed in C89 mode.
+     */
+    if (6 != sscanf(buf + len,
+                    "%lu %lu %lu %lu %lu %lu",
+                    &user,
+                    &nice,
+                    &sys,
+                    &idle,
+                    &dummy,
+                    &irq))
+      abort();
+
+    ts.user = clock_ticks * user;
+    ts.nice = clock_ticks * nice;
+    ts.sys  = clock_ticks * sys;
+    ts.idle = clock_ticks * idle;
+    ts.irq  = clock_ticks * irq;
+    ci[num++].cpu_times = ts;
+  }
+  assert(num == numcpus);
+
+  return 0;
+}
+
+
+static unsigned long read_cpufreq(unsigned int cpunum) {
+  unsigned long val;
+  char buf[1024];
+  FILE* fp;
+
+  snprintf(buf,
+           sizeof(buf),
+           "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
+           cpunum);
+
+  fp = uv__open_file(buf);
+  if (fp == NULL)
+    return 0;
+
+  if (fscanf(fp, "%lu", &val) != 1)
+    val = 0;
+
+  fclose(fp);
+
+  return val;
+}
+
+
+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) {
+#ifndef HAVE_IFADDRS_H
+  return -ENOSYS;
+#else
+  struct ifaddrs *addrs, *ent;
+  uv_interface_address_t* address;
+  int i;
+  struct sockaddr_ll *sll;
+
+  if (getifaddrs(&addrs))
+    return -errno;
+
+  *count = 0;
+  *addresses = NULL;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family == PF_PACKET)) {
+      continue;
+    }
+
+    (*count)++;
+  }
+
+  if (*count == 0)
+    return 0;
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    /*
+     * On Linux getifaddrs returns information related to the raw underlying
+     * devices. We're not interested in this information yet.
+     */
+    if (ent->ifa_addr->sa_family == PF_PACKET)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
+
+    address++;
+  }
+
+  /* Fill in physical addresses for each interface */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != PF_PACKET)) {
+      continue;
+    }
+
+    address = *addresses;
+
+    for (i = 0; i < (*count); i++) {
+      if (strcmp(address->name, ent->ifa_name) == 0) {
+        sll = (struct sockaddr_ll*)ent->ifa_addr;
+        memcpy(address->phys_addr, sll->sll_addr, sizeof(address->phys_addr));
+      }
+      address++;
+    }
+  }
+
+  freeifaddrs(addrs);
+
+  return 0;
+#endif
+}
+
+
+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);
+}
+
+
+void uv__set_process_title(const char* title) {
+#if defined(PR_SET_NAME)
+  prctl(PR_SET_NAME, title);  /* Only copies first 16 characters. */
+#endif
+}
diff --git a/Utilities/cmlibuv/src/unix/linux-inotify.c b/Utilities/cmlibuv/src/unix/linux-inotify.c
new file mode 100644
index 0000000..4708c05
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/linux-inotify.c
@@ -0,0 +1,285 @@
+/* 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 "tree.h"
+#include "internal.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/types.h>
+#include <unistd.h>
+
+struct watcher_list {
+  RB_ENTRY(watcher_list) entry;
+  QUEUE watchers;
+  int iterating;
+  char* path;
+  int wd;
+};
+
+struct watcher_root {
+  struct watcher_list* rbh_root;
+};
+#define CAST(p) ((struct watcher_root*)(p))
+
+
+static int compare_watchers(const struct watcher_list* a,
+                            const struct watcher_list* b) {
+  if (a->wd < b->wd) return -1;
+  if (a->wd > b->wd) return 1;
+  return 0;
+}
+
+
+RB_GENERATE_STATIC(watcher_root, watcher_list, entry, compare_watchers)
+
+
+static void uv__inotify_read(uv_loop_t* loop,
+                             uv__io_t* w,
+                             unsigned int revents);
+
+
+static int new_inotify_fd(void) {
+  int err;
+  int fd;
+
+  fd = uv__inotify_init1(UV__IN_NONBLOCK | UV__IN_CLOEXEC);
+  if (fd != -1)
+    return fd;
+
+  if (errno != ENOSYS)
+    return -errno;
+
+  fd = uv__inotify_init();
+  if (fd == -1)
+    return -errno;
+
+  err = uv__cloexec(fd, 1);
+  if (err == 0)
+    err = uv__nonblock(fd, 1);
+
+  if (err) {
+    uv__close(fd);
+    return err;
+  }
+
+  return fd;
+}
+
+
+static int init_inotify(uv_loop_t* loop) {
+  int err;
+
+  if (loop->inotify_fd != -1)
+    return 0;
+
+  err = new_inotify_fd();
+  if (err < 0)
+    return err;
+
+  loop->inotify_fd = err;
+  uv__io_init(&loop->inotify_read_watcher, uv__inotify_read, loop->inotify_fd);
+  uv__io_start(loop, &loop->inotify_read_watcher, POLLIN);
+
+  return 0;
+}
+
+
+static struct watcher_list* find_watcher(uv_loop_t* loop, int wd) {
+  struct watcher_list w;
+  w.wd = wd;
+  return RB_FIND(watcher_root, CAST(&loop->inotify_watchers), &w);
+}
+
+static void maybe_free_watcher_list(struct watcher_list* w, uv_loop_t* loop) {
+  /* if the watcher_list->watchers is being iterated over, we can't free it. */
+  if ((!w->iterating) && QUEUE_EMPTY(&w->watchers)) {
+    /* No watchers left for this path. Clean up. */
+    RB_REMOVE(watcher_root, CAST(&loop->inotify_watchers), w);
+    uv__inotify_rm_watch(loop->inotify_fd, w->wd);
+    uv__free(w);
+  }
+}
+
+static void uv__inotify_read(uv_loop_t* loop,
+                             uv__io_t* dummy,
+                             unsigned int events) {
+  const struct uv__inotify_event* e;
+  struct watcher_list* w;
+  uv_fs_event_t* h;
+  QUEUE queue;
+  QUEUE* q;
+  const char* path;
+  ssize_t size;
+  const char *p;
+  /* needs to be large enough for sizeof(inotify_event) + strlen(path) */
+  char buf[4096];
+
+  while (1) {
+    do
+      size = read(loop->inotify_fd, buf, sizeof(buf));
+    while (size == -1 && errno == EINTR);
+
+    if (size == -1) {
+      assert(errno == EAGAIN || errno == EWOULDBLOCK);
+      break;
+    }
+
+    assert(size > 0); /* pre-2.6.21 thing, size=0 == read buffer too small */
+
+    /* Now we have one or more inotify_event structs. */
+    for (p = buf; p < buf + size; p += sizeof(*e) + e->len) {
+      e = (const struct uv__inotify_event*)p;
+
+      events = 0;
+      if (e->mask & (UV__IN_ATTRIB|UV__IN_MODIFY))
+        events |= UV_CHANGE;
+      if (e->mask & ~(UV__IN_ATTRIB|UV__IN_MODIFY))
+        events |= UV_RENAME;
+
+      w = find_watcher(loop, e->wd);
+      if (w == NULL)
+        continue; /* Stale event, no watchers left. */
+
+      /* inotify does not return the filename when monitoring a single file
+       * for modifications. Repurpose the filename for API compatibility.
+       * I'm not convinced this is a good thing, maybe it should go.
+       */
+      path = e->len ? (const char*) (e + 1) : uv__basename_r(w->path);
+
+      /* We're about to iterate over the queue and call user's callbacks.
+       * What can go wrong?
+       * A callback could call uv_fs_event_stop()
+       * and the queue can change under our feet.
+       * So, we use QUEUE_MOVE() trick to safely iterate over the queue.
+       * And we don't free the watcher_list until we're done iterating.
+       *
+       * First,
+       * tell uv_fs_event_stop() (that could be called from a user's callback)
+       * not to free watcher_list.
+       */
+      w->iterating = 1;
+      QUEUE_MOVE(&w->watchers, &queue);
+      while (!QUEUE_EMPTY(&queue)) {
+        q = QUEUE_HEAD(&queue);
+        h = QUEUE_DATA(q, uv_fs_event_t, watchers);
+
+        QUEUE_REMOVE(q);
+        QUEUE_INSERT_TAIL(&w->watchers, q);
+
+        h->cb(h, path, events, 0);
+      }
+      /* done iterating, time to (maybe) free empty watcher_list */
+      w->iterating = 0;
+      maybe_free_watcher_list(w, loop);
+    }
+  }
+}
+
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_EVENT);
+  return 0;
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* path,
+                      unsigned int flags) {
+  struct watcher_list* w;
+  int events;
+  int err;
+  int wd;
+
+  if (uv__is_active(handle))
+    return -EINVAL;
+
+  err = init_inotify(handle->loop);
+  if (err)
+    return err;
+
+  events = UV__IN_ATTRIB
+         | UV__IN_CREATE
+         | UV__IN_MODIFY
+         | UV__IN_DELETE
+         | UV__IN_DELETE_SELF
+         | UV__IN_MOVE_SELF
+         | UV__IN_MOVED_FROM
+         | UV__IN_MOVED_TO;
+
+  wd = uv__inotify_add_watch(handle->loop->inotify_fd, path, events);
+  if (wd == -1)
+    return -errno;
+
+  w = find_watcher(handle->loop, wd);
+  if (w)
+    goto no_insert;
+
+  w = uv__malloc(sizeof(*w) + strlen(path) + 1);
+  if (w == NULL)
+    return -ENOMEM;
+
+  w->wd = wd;
+  w->path = strcpy((char*)(w + 1), path);
+  QUEUE_INIT(&w->watchers);
+  w->iterating = 0;
+  RB_INSERT(watcher_root, CAST(&handle->loop->inotify_watchers), w);
+
+no_insert:
+  uv__handle_start(handle);
+  QUEUE_INSERT_TAIL(&w->watchers, &handle->watchers);
+  handle->path = w->path;
+  handle->cb = cb;
+  handle->wd = wd;
+
+  return 0;
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+  struct watcher_list* w;
+
+  if (!uv__is_active(handle))
+    return 0;
+
+  w = find_watcher(handle->loop, handle->wd);
+  assert(w != NULL);
+
+  handle->wd = -1;
+  handle->path = NULL;
+  uv__handle_stop(handle);
+  QUEUE_REMOVE(&handle->watchers);
+
+  maybe_free_watcher_list(w, handle->loop);
+
+  return 0;
+}
+
+
+void uv__fs_event_close(uv_fs_event_t* handle) {
+  uv_fs_event_stop(handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/linux-syscalls.c b/Utilities/cmlibuv/src/unix/linux-syscalls.c
new file mode 100644
index 0000000..89998de
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/linux-syscalls.c
@@ -0,0 +1,471 @@
+/* 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 "linux-syscalls.h"
+#include <unistd.h>
+#include <signal.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <errno.h>
+
+#if defined(__has_feature)
+# if __has_feature(memory_sanitizer)
+#  define MSAN_ACTIVE 1
+#  include <sanitizer/msan_interface.h>
+# endif
+#endif
+
+#if defined(__i386__)
+# ifndef __NR_socketcall
+#  define __NR_socketcall 102
+# endif
+#endif
+
+#if defined(__arm__)
+# if defined(__thumb__) || defined(__ARM_EABI__)
+#  define UV_SYSCALL_BASE 0
+# else
+#  define UV_SYSCALL_BASE 0x900000
+# endif
+#endif /* __arm__ */
+
+#ifndef __NR_accept4
+# if defined(__x86_64__)
+#  define __NR_accept4 288
+# elif defined(__i386__)
+   /* Nothing. Handled through socketcall(). */
+# elif defined(__arm__)
+#  define __NR_accept4 (UV_SYSCALL_BASE + 366)
+# endif
+#endif /* __NR_accept4 */
+
+#ifndef __NR_eventfd
+# if defined(__x86_64__)
+#  define __NR_eventfd 284
+# elif defined(__i386__)
+#  define __NR_eventfd 323
+# elif defined(__arm__)
+#  define __NR_eventfd (UV_SYSCALL_BASE + 351)
+# endif
+#endif /* __NR_eventfd */
+
+#ifndef __NR_eventfd2
+# if defined(__x86_64__)
+#  define __NR_eventfd2 290
+# elif defined(__i386__)
+#  define __NR_eventfd2 328
+# elif defined(__arm__)
+#  define __NR_eventfd2 (UV_SYSCALL_BASE + 356)
+# endif
+#endif /* __NR_eventfd2 */
+
+#ifndef __NR_epoll_create
+# if defined(__x86_64__)
+#  define __NR_epoll_create 213
+# elif defined(__i386__)
+#  define __NR_epoll_create 254
+# elif defined(__arm__)
+#  define __NR_epoll_create (UV_SYSCALL_BASE + 250)
+# endif
+#endif /* __NR_epoll_create */
+
+#ifndef __NR_epoll_create1
+# if defined(__x86_64__)
+#  define __NR_epoll_create1 291
+# elif defined(__i386__)
+#  define __NR_epoll_create1 329
+# elif defined(__arm__)
+#  define __NR_epoll_create1 (UV_SYSCALL_BASE + 357)
+# endif
+#endif /* __NR_epoll_create1 */
+
+#ifndef __NR_epoll_ctl
+# if defined(__x86_64__)
+#  define __NR_epoll_ctl 233 /* used to be 214 */
+# elif defined(__i386__)
+#  define __NR_epoll_ctl 255
+# elif defined(__arm__)
+#  define __NR_epoll_ctl (UV_SYSCALL_BASE + 251)
+# endif
+#endif /* __NR_epoll_ctl */
+
+#ifndef __NR_epoll_wait
+# if defined(__x86_64__)
+#  define __NR_epoll_wait 232 /* used to be 215 */
+# elif defined(__i386__)
+#  define __NR_epoll_wait 256
+# elif defined(__arm__)
+#  define __NR_epoll_wait (UV_SYSCALL_BASE + 252)
+# endif
+#endif /* __NR_epoll_wait */
+
+#ifndef __NR_epoll_pwait
+# if defined(__x86_64__)
+#  define __NR_epoll_pwait 281
+# elif defined(__i386__)
+#  define __NR_epoll_pwait 319
+# elif defined(__arm__)
+#  define __NR_epoll_pwait (UV_SYSCALL_BASE + 346)
+# endif
+#endif /* __NR_epoll_pwait */
+
+#ifndef __NR_inotify_init
+# if defined(__x86_64__)
+#  define __NR_inotify_init 253
+# elif defined(__i386__)
+#  define __NR_inotify_init 291
+# elif defined(__arm__)
+#  define __NR_inotify_init (UV_SYSCALL_BASE + 316)
+# endif
+#endif /* __NR_inotify_init */
+
+#ifndef __NR_inotify_init1
+# if defined(__x86_64__)
+#  define __NR_inotify_init1 294
+# elif defined(__i386__)
+#  define __NR_inotify_init1 332
+# elif defined(__arm__)
+#  define __NR_inotify_init1 (UV_SYSCALL_BASE + 360)
+# endif
+#endif /* __NR_inotify_init1 */
+
+#ifndef __NR_inotify_add_watch
+# if defined(__x86_64__)
+#  define __NR_inotify_add_watch 254
+# elif defined(__i386__)
+#  define __NR_inotify_add_watch 292
+# elif defined(__arm__)
+#  define __NR_inotify_add_watch (UV_SYSCALL_BASE + 317)
+# endif
+#endif /* __NR_inotify_add_watch */
+
+#ifndef __NR_inotify_rm_watch
+# if defined(__x86_64__)
+#  define __NR_inotify_rm_watch 255
+# elif defined(__i386__)
+#  define __NR_inotify_rm_watch 293
+# elif defined(__arm__)
+#  define __NR_inotify_rm_watch (UV_SYSCALL_BASE + 318)
+# endif
+#endif /* __NR_inotify_rm_watch */
+
+#ifndef __NR_pipe2
+# if defined(__x86_64__)
+#  define __NR_pipe2 293
+# elif defined(__i386__)
+#  define __NR_pipe2 331
+# elif defined(__arm__)
+#  define __NR_pipe2 (UV_SYSCALL_BASE + 359)
+# endif
+#endif /* __NR_pipe2 */
+
+#ifndef __NR_recvmmsg
+# if defined(__x86_64__)
+#  define __NR_recvmmsg 299
+# elif defined(__i386__)
+#  define __NR_recvmmsg 337
+# elif defined(__arm__)
+#  define __NR_recvmmsg (UV_SYSCALL_BASE + 365)
+# endif
+#endif /* __NR_recvmsg */
+
+#ifndef __NR_sendmmsg
+# if defined(__x86_64__)
+#  define __NR_sendmmsg 307
+# elif defined(__i386__)
+#  define __NR_sendmmsg 345
+# elif defined(__arm__)
+#  define __NR_sendmmsg (UV_SYSCALL_BASE + 374)
+# endif
+#endif /* __NR_sendmmsg */
+
+#ifndef __NR_utimensat
+# if defined(__x86_64__)
+#  define __NR_utimensat 280
+# elif defined(__i386__)
+#  define __NR_utimensat 320
+# elif defined(__arm__)
+#  define __NR_utimensat (UV_SYSCALL_BASE + 348)
+# endif
+#endif /* __NR_utimensat */
+
+#ifndef __NR_preadv
+# if defined(__x86_64__)
+#  define __NR_preadv 295
+# elif defined(__i386__)
+#  define __NR_preadv 333
+# elif defined(__arm__)
+#  define __NR_preadv (UV_SYSCALL_BASE + 361)
+# endif
+#endif /* __NR_preadv */
+
+#ifndef __NR_pwritev
+# if defined(__x86_64__)
+#  define __NR_pwritev 296
+# elif defined(__i386__)
+#  define __NR_pwritev 334
+# elif defined(__arm__)
+#  define __NR_pwritev (UV_SYSCALL_BASE + 362)
+# endif
+#endif /* __NR_pwritev */
+
+#ifndef __NR_dup3
+# if defined(__x86_64__)
+#  define __NR_dup3 292
+# elif defined(__i386__)
+#  define __NR_dup3 330
+# elif defined(__arm__)
+#  define __NR_dup3 (UV_SYSCALL_BASE + 358)
+# endif
+#endif /* __NR_pwritev */
+
+
+int uv__accept4(int fd, struct sockaddr* addr, socklen_t* addrlen, int flags) {
+#if defined(__i386__)
+  unsigned long args[4];
+  int r;
+
+  args[0] = (unsigned long) fd;
+  args[1] = (unsigned long) addr;
+  args[2] = (unsigned long) addrlen;
+  args[3] = (unsigned long) flags;
+
+  r = syscall(__NR_socketcall, 18 /* SYS_ACCEPT4 */, args);
+
+  /* socketcall() raises EINVAL when SYS_ACCEPT4 is not supported but so does
+   * a bad flags argument. Try to distinguish between the two cases.
+   */
+  if (r == -1)
+    if (errno == EINVAL)
+      if ((flags & ~(UV__SOCK_CLOEXEC|UV__SOCK_NONBLOCK)) == 0)
+        errno = ENOSYS;
+
+  return r;
+#elif defined(__NR_accept4)
+  return syscall(__NR_accept4, fd, addr, addrlen, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__eventfd(unsigned int count) {
+#if defined(__NR_eventfd)
+  return syscall(__NR_eventfd, count);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__eventfd2(unsigned int count, int flags) {
+#if defined(__NR_eventfd2)
+  return syscall(__NR_eventfd2, count, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__epoll_create(int size) {
+#if defined(__NR_epoll_create)
+  return syscall(__NR_epoll_create, size);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__epoll_create1(int flags) {
+#if defined(__NR_epoll_create1)
+  return syscall(__NR_epoll_create1, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__epoll_ctl(int epfd, int op, int fd, struct uv__epoll_event* events) {
+#if defined(__NR_epoll_ctl)
+  return syscall(__NR_epoll_ctl, epfd, op, fd, events);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__epoll_wait(int epfd,
+                   struct uv__epoll_event* events,
+                   int nevents,
+                   int timeout) {
+#if defined(__NR_epoll_wait)
+  int result;
+  result = syscall(__NR_epoll_wait, epfd, events, nevents, timeout);
+#if MSAN_ACTIVE
+  if (result > 0)
+    __msan_unpoison(events, sizeof(events[0]) * result);
+#endif
+  return result;
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__epoll_pwait(int epfd,
+                    struct uv__epoll_event* events,
+                    int nevents,
+                    int timeout,
+                    uint64_t sigmask) {
+#if defined(__NR_epoll_pwait)
+  int result;
+  result = syscall(__NR_epoll_pwait,
+                   epfd,
+                   events,
+                   nevents,
+                   timeout,
+                   &sigmask,
+                   sizeof(sigmask));
+#if MSAN_ACTIVE
+  if (result > 0)
+    __msan_unpoison(events, sizeof(events[0]) * result);
+#endif
+  return result;
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__inotify_init(void) {
+#if defined(__NR_inotify_init)
+  return syscall(__NR_inotify_init);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__inotify_init1(int flags) {
+#if defined(__NR_inotify_init1)
+  return syscall(__NR_inotify_init1, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__inotify_add_watch(int fd, const char* path, uint32_t mask) {
+#if defined(__NR_inotify_add_watch)
+  return syscall(__NR_inotify_add_watch, fd, path, mask);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__inotify_rm_watch(int fd, int32_t wd) {
+#if defined(__NR_inotify_rm_watch)
+  return syscall(__NR_inotify_rm_watch, fd, wd);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__pipe2(int pipefd[2], int flags) {
+#if defined(__NR_pipe2)
+  int result;
+  result = syscall(__NR_pipe2, pipefd, flags);
+#if MSAN_ACTIVE
+  if (!result)
+    __msan_unpoison(pipefd, sizeof(int[2]));
+#endif
+  return result;
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__sendmmsg(int fd,
+                 struct uv__mmsghdr* mmsg,
+                 unsigned int vlen,
+                 unsigned int flags) {
+#if defined(__NR_sendmmsg)
+  return syscall(__NR_sendmmsg, fd, mmsg, vlen, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__recvmmsg(int fd,
+                 struct uv__mmsghdr* mmsg,
+                 unsigned int vlen,
+                 unsigned int flags,
+                 struct timespec* timeout) {
+#if defined(__NR_recvmmsg)
+  return syscall(__NR_recvmmsg, fd, mmsg, vlen, flags, timeout);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__utimesat(int dirfd,
+                 const char* path,
+                 const struct timespec times[2],
+                 int flags)
+{
+#if defined(__NR_utimensat)
+  return syscall(__NR_utimensat, dirfd, path, times, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+ssize_t uv__preadv(int fd, const struct iovec *iov, int iovcnt, int64_t offset) {
+#if defined(__NR_preadv)
+  return syscall(__NR_preadv, fd, iov, iovcnt, (long)offset, (long)(offset >> 32));
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+ssize_t uv__pwritev(int fd, const struct iovec *iov, int iovcnt, int64_t offset) {
+#if defined(__NR_pwritev)
+  return syscall(__NR_pwritev, fd, iov, iovcnt, (long)offset, (long)(offset >> 32));
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
+
+
+int uv__dup3(int oldfd, int newfd, int flags) {
+#if defined(__NR_dup3)
+  return syscall(__NR_dup3, oldfd, newfd, flags);
+#else
+  return errno = ENOSYS, -1;
+#endif
+}
diff --git a/Utilities/cmlibuv/src/unix/linux-syscalls.h b/Utilities/cmlibuv/src/unix/linux-syscalls.h
new file mode 100644
index 0000000..4c095e9
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/linux-syscalls.h
@@ -0,0 +1,151 @@
+/* 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_SYSCALL_H_
+#define UV_LINUX_SYSCALL_H_
+
+#undef  _GNU_SOURCE
+#define _GNU_SOURCE
+
+#include <stdint.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+
+#if defined(__alpha__)
+# define UV__O_CLOEXEC        0x200000
+#elif defined(__hppa__)
+# define UV__O_CLOEXEC        0x200000
+#elif defined(__sparc__)
+# define UV__O_CLOEXEC        0x400000
+#else
+# define UV__O_CLOEXEC        0x80000
+#endif
+
+#if defined(__alpha__)
+# define UV__O_NONBLOCK       0x4
+#elif defined(__hppa__)
+# define UV__O_NONBLOCK       O_NONBLOCK
+#elif defined(__mips__)
+# define UV__O_NONBLOCK       0x80
+#elif defined(__sparc__)
+# define UV__O_NONBLOCK       0x4000
+#else
+# define UV__O_NONBLOCK       0x800
+#endif
+
+#define UV__EFD_CLOEXEC       UV__O_CLOEXEC
+#define UV__EFD_NONBLOCK      UV__O_NONBLOCK
+
+#define UV__IN_CLOEXEC        UV__O_CLOEXEC
+#define UV__IN_NONBLOCK       UV__O_NONBLOCK
+
+#define UV__SOCK_CLOEXEC      UV__O_CLOEXEC
+#if defined(SOCK_NONBLOCK)
+# define UV__SOCK_NONBLOCK    SOCK_NONBLOCK
+#else
+# define UV__SOCK_NONBLOCK    UV__O_NONBLOCK
+#endif
+
+/* epoll flags */
+#define UV__EPOLL_CLOEXEC     UV__O_CLOEXEC
+#define UV__EPOLL_CTL_ADD     1
+#define UV__EPOLL_CTL_DEL     2
+#define UV__EPOLL_CTL_MOD     3
+
+/* inotify flags */
+#define UV__IN_ACCESS         0x001
+#define UV__IN_MODIFY         0x002
+#define UV__IN_ATTRIB         0x004
+#define UV__IN_CLOSE_WRITE    0x008
+#define UV__IN_CLOSE_NOWRITE  0x010
+#define UV__IN_OPEN           0x020
+#define UV__IN_MOVED_FROM     0x040
+#define UV__IN_MOVED_TO       0x080
+#define UV__IN_CREATE         0x100
+#define UV__IN_DELETE         0x200
+#define UV__IN_DELETE_SELF    0x400
+#define UV__IN_MOVE_SELF      0x800
+
+#if defined(__x86_64__)
+struct uv__epoll_event {
+  uint32_t events;
+  uint64_t data;
+} __attribute__((packed));
+#else
+struct uv__epoll_event {
+  uint32_t events;
+  uint64_t data;
+};
+#endif
+
+struct uv__inotify_event {
+  int32_t wd;
+  uint32_t mask;
+  uint32_t cookie;
+  uint32_t len;
+  /* char name[0]; */
+};
+
+struct uv__mmsghdr {
+  struct msghdr msg_hdr;
+  unsigned int msg_len;
+};
+
+int uv__accept4(int fd, struct sockaddr* addr, socklen_t* addrlen, int flags);
+int uv__eventfd(unsigned int count);
+int uv__epoll_create(int size);
+int uv__epoll_create1(int flags);
+int uv__epoll_ctl(int epfd, int op, int fd, struct uv__epoll_event *ev);
+int uv__epoll_wait(int epfd,
+                   struct uv__epoll_event* events,
+                   int nevents,
+                   int timeout);
+int uv__epoll_pwait(int epfd,
+                    struct uv__epoll_event* events,
+                    int nevents,
+                    int timeout,
+                    uint64_t sigmask);
+int uv__eventfd2(unsigned int count, int flags);
+int uv__inotify_init(void);
+int uv__inotify_init1(int flags);
+int uv__inotify_add_watch(int fd, const char* path, uint32_t mask);
+int uv__inotify_rm_watch(int fd, int32_t wd);
+int uv__pipe2(int pipefd[2], int flags);
+int uv__recvmmsg(int fd,
+                 struct uv__mmsghdr* mmsg,
+                 unsigned int vlen,
+                 unsigned int flags,
+                 struct timespec* timeout);
+int uv__sendmmsg(int fd,
+                 struct uv__mmsghdr* mmsg,
+                 unsigned int vlen,
+                 unsigned int flags);
+int uv__utimesat(int dirfd,
+                 const char* path,
+                 const struct timespec times[2],
+                 int flags);
+ssize_t uv__preadv(int fd, const struct iovec *iov, int iovcnt, int64_t offset);
+ssize_t uv__pwritev(int fd, const struct iovec *iov, int iovcnt, int64_t offset);
+int uv__dup3(int oldfd, int newfd, int flags);
+
+#endif /* UV_LINUX_SYSCALL_H_ */
diff --git a/Utilities/cmlibuv/src/unix/loop-watcher.c b/Utilities/cmlibuv/src/unix/loop-watcher.c
new file mode 100644
index 0000000..340bb0d
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/loop-watcher.c
@@ -0,0 +1,68 @@
+/* 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 "internal.h"
+
+#define UV_LOOP_WATCHER_DEFINE(name, type)                                    \
+  int uv_##name##_init(uv_loop_t* loop, uv_##name##_t* handle) {              \
+    uv__handle_init(loop, (uv_handle_t*)handle, UV_##type);                   \
+    handle->name##_cb = NULL;                                                 \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+  int uv_##name##_start(uv_##name##_t* handle, uv_##name##_cb cb) {           \
+    if (uv__is_active(handle)) return 0;                                      \
+    if (cb == NULL) return -EINVAL;                                           \
+    QUEUE_INSERT_HEAD(&handle->loop->name##_handles, &handle->queue);         \
+    handle->name##_cb = cb;                                                   \
+    uv__handle_start(handle);                                                 \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+  int uv_##name##_stop(uv_##name##_t* handle) {                               \
+    if (!uv__is_active(handle)) return 0;                                     \
+    QUEUE_REMOVE(&handle->queue);                                             \
+    uv__handle_stop(handle);                                                  \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+  void uv__run_##name(uv_loop_t* loop) {                                      \
+    uv_##name##_t* h;                                                         \
+    QUEUE queue;                                                              \
+    QUEUE* q;                                                                 \
+    QUEUE_MOVE(&loop->name##_handles, &queue);                                \
+    while (!QUEUE_EMPTY(&queue)) {                                            \
+      q = QUEUE_HEAD(&queue);                                                 \
+      h = QUEUE_DATA(q, uv_##name##_t, queue);                                \
+      QUEUE_REMOVE(q);                                                        \
+      QUEUE_INSERT_TAIL(&loop->name##_handles, q);                            \
+      h->name##_cb(h);                                                        \
+    }                                                                         \
+  }                                                                           \
+                                                                              \
+  void uv__##name##_close(uv_##name##_t* handle) {                            \
+    uv_##name##_stop(handle);                                                 \
+  }
+
+UV_LOOP_WATCHER_DEFINE(prepare, PREPARE)
+UV_LOOP_WATCHER_DEFINE(check, CHECK)
+UV_LOOP_WATCHER_DEFINE(idle, IDLE)
diff --git a/Utilities/cmlibuv/src/unix/loop.c b/Utilities/cmlibuv/src/unix/loop.c
new file mode 100644
index 0000000..bd63c2f
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/loop.c
@@ -0,0 +1,159 @@
+/* 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 "tree.h"
+#include "internal.h"
+#include "heap-inl.h"
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+int uv_loop_init(uv_loop_t* loop) {
+  void* saved_data;
+  int err;
+
+  uv__signal_global_once_init();
+
+  saved_data = loop->data;
+  memset(loop, 0, sizeof(*loop));
+  loop->data = saved_data;
+
+  heap_init((struct heap*) &loop->timer_heap);
+  QUEUE_INIT(&loop->wq);
+  QUEUE_INIT(&loop->active_reqs);
+  QUEUE_INIT(&loop->idle_handles);
+  QUEUE_INIT(&loop->async_handles);
+  QUEUE_INIT(&loop->check_handles);
+  QUEUE_INIT(&loop->prepare_handles);
+  QUEUE_INIT(&loop->handle_queue);
+
+  loop->nfds = 0;
+  loop->watchers = NULL;
+  loop->nwatchers = 0;
+  QUEUE_INIT(&loop->pending_queue);
+  QUEUE_INIT(&loop->watcher_queue);
+
+  loop->closing_handles = NULL;
+  uv__update_time(loop);
+  uv__async_init(&loop->async_watcher);
+  loop->signal_pipefd[0] = -1;
+  loop->signal_pipefd[1] = -1;
+  loop->backend_fd = -1;
+  loop->emfile_fd = -1;
+
+  loop->timer_counter = 0;
+  loop->stop_flag = 0;
+
+  err = uv__platform_loop_init(loop);
+  if (err)
+    return err;
+
+  err = uv_signal_init(loop, &loop->child_watcher);
+  if (err)
+    goto fail_signal_init;
+
+  uv__handle_unref(&loop->child_watcher);
+  loop->child_watcher.flags |= UV__HANDLE_INTERNAL;
+  QUEUE_INIT(&loop->process_handles);
+
+  err = uv_rwlock_init(&loop->cloexec_lock);
+  if (err)
+    goto fail_rwlock_init;
+
+  err = uv_mutex_init(&loop->wq_mutex);
+  if (err)
+    goto fail_mutex_init;
+
+  err = uv_async_init(loop, &loop->wq_async, uv__work_done);
+  if (err)
+    goto fail_async_init;
+
+  uv__handle_unref(&loop->wq_async);
+  loop->wq_async.flags |= UV__HANDLE_INTERNAL;
+
+  return 0;
+
+fail_async_init:
+  uv_mutex_destroy(&loop->wq_mutex);
+
+fail_mutex_init:
+  uv_rwlock_destroy(&loop->cloexec_lock);
+
+fail_rwlock_init:
+  uv__signal_loop_cleanup(loop);
+
+fail_signal_init:
+  uv__platform_loop_delete(loop);
+
+  return err;
+}
+
+
+void uv__loop_close(uv_loop_t* loop) {
+  uv__signal_loop_cleanup(loop);
+  uv__platform_loop_delete(loop);
+  uv__async_stop(loop, &loop->async_watcher);
+
+  if (loop->emfile_fd != -1) {
+    uv__close(loop->emfile_fd);
+    loop->emfile_fd = -1;
+  }
+
+  if (loop->backend_fd != -1) {
+    uv__close(loop->backend_fd);
+    loop->backend_fd = -1;
+  }
+
+  uv_mutex_lock(&loop->wq_mutex);
+  assert(QUEUE_EMPTY(&loop->wq) && "thread pool work queue not empty!");
+  assert(!uv__has_active_reqs(loop));
+  uv_mutex_unlock(&loop->wq_mutex);
+  uv_mutex_destroy(&loop->wq_mutex);
+
+  /*
+   * Note that all thread pool stuff is finished at this point and
+   * it is safe to just destroy rw lock
+   */
+  uv_rwlock_destroy(&loop->cloexec_lock);
+
+#if 0
+  assert(QUEUE_EMPTY(&loop->pending_queue));
+  assert(QUEUE_EMPTY(&loop->watcher_queue));
+  assert(loop->nfds == 0);
+#endif
+
+  uv__free(loop->watchers);
+  loop->watchers = NULL;
+  loop->nwatchers = 0;
+}
+
+
+int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) {
+  if (option != UV_LOOP_BLOCK_SIGNAL)
+    return UV_ENOSYS;
+
+  if (va_arg(ap, int) != SIGPROF)
+    return UV_EINVAL;
+
+  loop->flags |= UV_LOOP_BLOCK_SIGPROF;
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/unix/netbsd.c b/Utilities/cmlibuv/src/unix/netbsd.c
new file mode 100644
index 0000000..4a9e6cb
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/netbsd.c
@@ -0,0 +1,380 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+
+#include <kvm.h>
+#include <paths.h>
+#include <ifaddrs.h>
+#include <unistd.h>
+#include <time.h>
+#include <stdlib.h>
+#include <fcntl.h>
+
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <sys/resource.h>
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#include <uvm/uvm_extern.h>
+
+#include <unistd.h>
+#include <time.h>
+
+#undef NANOSEC
+#define NANOSEC ((uint64_t) 1e9)
+
+static char *process_title;
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  return uv__kqueue_init(loop);
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
+}
+
+
+void uv_loadavg(double avg[3]) {
+  struct loadavg info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_LOADAVG};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0) == -1) return;
+
+  avg[0] = (double) info.ldavg[0] / info.fscale;
+  avg[1] = (double) info.ldavg[1] / info.fscale;
+  avg[2] = (double) info.ldavg[2] / info.fscale;
+}
+
+
+int uv_exepath(char* buffer, size_t* size) {
+  int mib[4];
+  size_t cb;
+  pid_t mypid;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  mypid = getpid();
+  mib[0] = CTL_KERN;
+  mib[1] = KERN_PROC_ARGS;
+  mib[2] = mypid;
+  mib[3] = KERN_PROC_ARGV;
+
+  cb = *size;
+  if (sysctl(mib, 4, buffer, &cb, NULL, 0))
+    return -errno;
+  *size = strlen(buffer);
+
+  return 0;
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  struct uvmexp info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_UVMEXP};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info.free * sysconf(_SC_PAGESIZE);
+}
+
+
+uint64_t uv_get_total_memory(void) {
+#if defined(HW_PHYSMEM64)
+  uint64_t info;
+  int which[] = {CTL_HW, HW_PHYSMEM64};
+#else
+  unsigned int info;
+  int which[] = {CTL_HW, HW_PHYSMEM};
+#endif
+  size_t size = sizeof(info);
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info;
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+  process_title = argc ? uv__strdup(argv[0]) : NULL;
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  if (process_title) uv__free(process_title);
+
+  process_title = uv__strdup(title);
+  setproctitle("%s", title);
+
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  size_t len;
+
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+
+  if (process_title) {
+    len = strlen(process_title) + 1;
+
+    if (size < len)
+      return -ENOBUFS;
+
+    memcpy(buffer, process_title, len);
+  } else {
+    len = 0;
+  }
+
+  buffer[len] = '\0';
+
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  kvm_t *kd = NULL;
+  struct kinfo_proc2 *kinfo = NULL;
+  pid_t pid;
+  int nprocs;
+  int max_size = sizeof(struct kinfo_proc2);
+  int page_size;
+
+  page_size = getpagesize();
+  pid = getpid();
+
+  kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, "kvm_open");
+
+  if (kd == NULL) goto error;
+
+  kinfo = kvm_getproc2(kd, KERN_PROC_PID, pid, max_size, &nprocs);
+  if (kinfo == NULL) goto error;
+
+  *rss = kinfo->p_vm_rssize * page_size;
+
+  kvm_close(kd);
+
+  return 0;
+
+error:
+  if (kd) kvm_close(kd);
+  return -EPERM;
+}
+
+
+int uv_uptime(double* uptime) {
+  time_t now;
+  struct timeval info;
+  size_t size = sizeof(info);
+  static int which[] = {CTL_KERN, KERN_BOOTTIME};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  now = time(NULL);
+
+  *uptime = (double)(now - info.tv_sec);
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK);
+  unsigned int multiplier = ((uint64_t)1000L / ticks);
+  unsigned int cur = 0;
+  uv_cpu_info_t* cpu_info;
+  u_int64_t* cp_times;
+  char model[512];
+  u_int64_t cpuspeed;
+  int numcpus;
+  size_t size;
+  int i;
+
+  size = sizeof(model);
+  if (sysctlbyname("machdep.cpu_brand", &model, &size, NULL, 0) &&
+      sysctlbyname("hw.model", &model, &size, NULL, 0)) {
+    return -errno;
+  }
+
+  size = sizeof(numcpus);
+  if (sysctlbyname("hw.ncpu", &numcpus, &size, NULL, 0))
+    return -errno;
+  *count = numcpus;
+
+  /* Only i386 and amd64 have machdep.tsc_freq */
+  size = sizeof(cpuspeed);
+  if (sysctlbyname("machdep.tsc_freq", &cpuspeed, &size, NULL, 0))
+    cpuspeed = 0;
+
+  size = numcpus * CPUSTATES * sizeof(*cp_times);
+  cp_times = uv__malloc(size);
+  if (cp_times == NULL)
+    return -ENOMEM;
+
+  if (sysctlbyname("kern.cp_time", cp_times, &size, NULL, 0))
+    return -errno;
+
+  *cpu_infos = uv__malloc(numcpus * sizeof(**cpu_infos));
+  if (!(*cpu_infos)) {
+    uv__free(cp_times);
+    uv__free(*cpu_infos);
+    return -ENOMEM;
+  }
+
+  for (i = 0; i < numcpus; i++) {
+    cpu_info = &(*cpu_infos)[i];
+    cpu_info->cpu_times.user = (uint64_t)(cp_times[CP_USER+cur]) * multiplier;
+    cpu_info->cpu_times.nice = (uint64_t)(cp_times[CP_NICE+cur]) * multiplier;
+    cpu_info->cpu_times.sys = (uint64_t)(cp_times[CP_SYS+cur]) * multiplier;
+    cpu_info->cpu_times.idle = (uint64_t)(cp_times[CP_IDLE+cur]) * multiplier;
+    cpu_info->cpu_times.irq = (uint64_t)(cp_times[CP_INTR+cur]) * multiplier;
+    cpu_info->model = uv__strdup(model);
+    cpu_info->speed = (int)(cpuspeed/(uint64_t) 1e6);
+    cur += CPUSTATES;
+  }
+  uv__free(cp_times);
+  return 0;
+}
+
+
+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) {
+  struct ifaddrs *addrs, *ent;
+  uv_interface_address_t* address;
+  int i;
+  struct sockaddr_dl *sa_addr;
+
+  if (getifaddrs(&addrs))
+    return -errno;
+
+  *count = 0;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != PF_INET)) {
+      continue;
+    }
+    (*count)++;
+  }
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    if (ent->ifa_addr->sa_family != PF_INET)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
+
+    address++;
+  }
+
+  /* Fill in physical addresses for each interface */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != AF_LINK)) {
+      continue;
+    }
+
+    address = *addresses;
+
+    for (i = 0; i < (*count); i++) {
+      if (strcmp(address->name, ent->ifa_name) == 0) {
+        sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
+        memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+      }
+      address++;
+    }
+  }
+
+  freeifaddrs(addrs);
+
+  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/openbsd.c b/Utilities/cmlibuv/src/unix/openbsd.c
new file mode 100644
index 0000000..909288c
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/openbsd.c
@@ -0,0 +1,396 @@
+/* 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 "internal.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/resource.h>
+#include <sys/sched.h>
+#include <sys/time.h>
+#include <sys/sysctl.h>
+
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <kvm.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#undef NANOSEC
+#define NANOSEC ((uint64_t) 1e9)
+
+
+static char *process_title;
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  return uv__kqueue_init(loop);
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
+}
+
+
+void uv_loadavg(double avg[3]) {
+  struct loadavg info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_LOADAVG};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0) < 0) return;
+
+  avg[0] = (double) info.ldavg[0] / info.fscale;
+  avg[1] = (double) info.ldavg[1] / info.fscale;
+  avg[2] = (double) info.ldavg[2] / info.fscale;
+}
+
+
+int uv_exepath(char* buffer, size_t* size) {
+  int mib[4];
+  char **argsbuf = NULL;
+  char **argsbuf_tmp;
+  size_t argsbuf_size = 100U;
+  size_t exepath_size;
+  pid_t mypid;
+  int err;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  mypid = getpid();
+  for (;;) {
+    err = -ENOMEM;
+    argsbuf_tmp = uv__realloc(argsbuf, argsbuf_size);
+    if (argsbuf_tmp == NULL)
+      goto out;
+    argsbuf = argsbuf_tmp;
+    mib[0] = CTL_KERN;
+    mib[1] = KERN_PROC_ARGS;
+    mib[2] = mypid;
+    mib[3] = KERN_PROC_ARGV;
+    if (sysctl(mib, 4, argsbuf, &argsbuf_size, NULL, 0) == 0) {
+      break;
+    }
+    if (errno != ENOMEM) {
+      err = -errno;
+      goto out;
+    }
+    argsbuf_size *= 2U;
+  }
+
+  if (argsbuf[0] == NULL) {
+    err = -EINVAL;  /* FIXME(bnoordhuis) More appropriate error. */
+    goto out;
+  }
+
+  *size -= 1;
+  exepath_size = strlen(argsbuf[0]);
+  if (*size > exepath_size)
+    *size = exepath_size;
+
+  memcpy(buffer, argsbuf[0], *size);
+  buffer[*size] = '\0';
+  err = 0;
+
+out:
+  uv__free(argsbuf);
+
+  return err;
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  struct uvmexp info;
+  size_t size = sizeof(info);
+  int which[] = {CTL_VM, VM_UVMEXP};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info.free * sysconf(_SC_PAGESIZE);
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  uint64_t info;
+  int which[] = {CTL_HW, HW_PHYSMEM64};
+  size_t size = sizeof(info);
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  return (uint64_t) info;
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+  process_title = argc ? uv__strdup(argv[0]) : NULL;
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  uv__free(process_title);
+  process_title = uv__strdup(title);
+  setproctitle(title);
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  size_t len;
+
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+
+  if (process_title) {
+    len = strlen(process_title) + 1;
+
+    if (size < len)
+      return -ENOBUFS;
+
+    memcpy(buffer, process_title, len);
+  } else {
+    len = 0;
+  }
+
+  buffer[len] = '\0';
+
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  struct kinfo_proc kinfo;
+  size_t page_size = getpagesize();
+  size_t size = sizeof(struct kinfo_proc);
+  int mib[6];
+
+  mib[0] = CTL_KERN;
+  mib[1] = KERN_PROC;
+  mib[2] = KERN_PROC_PID;
+  mib[3] = getpid();
+  mib[4] = sizeof(struct kinfo_proc);
+  mib[5] = 1;
+
+  if (sysctl(mib, 6, &kinfo, &size, NULL, 0) < 0)
+    return -errno;
+
+  *rss = kinfo.p_vm_rssize * page_size;
+  return 0;
+}
+
+
+int uv_uptime(double* uptime) {
+  time_t now;
+  struct timeval info;
+  size_t size = sizeof(info);
+  static int which[] = {CTL_KERN, KERN_BOOTTIME};
+
+  if (sysctl(which, 2, &info, &size, NULL, 0))
+    return -errno;
+
+  now = time(NULL);
+
+  *uptime = (double)(now - info.tv_sec);
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK),
+               multiplier = ((uint64_t)1000L / ticks), cpuspeed;
+  uint64_t info[CPUSTATES];
+  char model[512];
+  int numcpus = 1;
+  int which[] = {CTL_HW,HW_MODEL,0};
+  size_t size;
+  int i;
+  uv_cpu_info_t* cpu_info;
+
+  size = sizeof(model);
+  if (sysctl(which, 2, &model, &size, NULL, 0))
+    return -errno;
+
+  which[1] = HW_NCPU;
+  size = sizeof(numcpus);
+  if (sysctl(which, 2, &numcpus, &size, NULL, 0))
+    return -errno;
+
+  *cpu_infos = uv__malloc(numcpus * sizeof(**cpu_infos));
+  if (!(*cpu_infos))
+    return -ENOMEM;
+
+  *count = numcpus;
+
+  which[1] = HW_CPUSPEED;
+  size = sizeof(cpuspeed);
+  if (sysctl(which, 2, &cpuspeed, &size, NULL, 0)) {
+    uv__free(*cpu_infos);
+    return -errno;
+  }
+
+  size = sizeof(info);
+  which[0] = CTL_KERN;
+  which[1] = KERN_CPTIME2;
+  for (i = 0; i < numcpus; i++) {
+    which[2] = i;
+    size = sizeof(info);
+    if (sysctl(which, 3, &info, &size, NULL, 0)) {
+      uv__free(*cpu_infos);
+      return -errno;
+    }
+
+    cpu_info = &(*cpu_infos)[i];
+
+    cpu_info->cpu_times.user = (uint64_t)(info[CP_USER]) * multiplier;
+    cpu_info->cpu_times.nice = (uint64_t)(info[CP_NICE]) * multiplier;
+    cpu_info->cpu_times.sys = (uint64_t)(info[CP_SYS]) * multiplier;
+    cpu_info->cpu_times.idle = (uint64_t)(info[CP_IDLE]) * multiplier;
+    cpu_info->cpu_times.irq = (uint64_t)(info[CP_INTR]) * multiplier;
+
+    cpu_info->model = uv__strdup(model);
+    cpu_info->speed = cpuspeed;
+  }
+
+  return 0;
+}
+
+
+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) {
+  struct ifaddrs *addrs, *ent;
+  uv_interface_address_t* address;
+  int i;
+  struct sockaddr_dl *sa_addr;
+
+  if (getifaddrs(&addrs) != 0)
+    return -errno;
+
+   *count = 0;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != PF_INET)) {
+      continue;
+    }
+    (*count)++;
+  }
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    if (ent->ifa_addr->sa_family != PF_INET)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
+
+    address++;
+  }
+
+  /* Fill in physical addresses for each interface */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family != AF_LINK)) {
+      continue;
+    }
+
+    address = *addresses;
+
+    for (i = 0; i < (*count); i++) {
+      if (strcmp(address->name, ent->ifa_name) == 0) {
+        sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
+        memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+      }
+      address++;
+    }
+  }
+
+  freeifaddrs(addrs);
+
+  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/os390.c b/Utilities/cmlibuv/src/unix/os390.c
new file mode 100644
index 0000000..bcdbc4b
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/os390.c
@@ -0,0 +1,42 @@
+/* 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 "internal.h"
+
+int uv__io_check_fd(uv_loop_t* loop, int fd) {
+  struct pollfd p[1];
+  int rv;
+
+  p[0].fd = fd;
+  p[0].events = POLLIN;
+
+  do
+    rv = poll(p, 1, 0);
+  while (rv == -1 && errno == EINTR);
+
+  if (rv == -1)
+    abort();
+
+  if (p[0].revents & POLLNVAL)
+    return -1;
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/unix/pipe.c b/Utilities/cmlibuv/src/unix/pipe.c
new file mode 100644
index 0000000..80f5e6f
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/pipe.c
@@ -0,0 +1,295 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+
+int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) {
+  uv__stream_init(loop, (uv_stream_t*)handle, UV_NAMED_PIPE);
+  handle->shutdown_req = NULL;
+  handle->connect_req = NULL;
+  handle->pipe_fname = NULL;
+  handle->ipc = ipc;
+  return 0;
+}
+
+
+int uv_pipe_bind(uv_pipe_t* handle, const char* name) {
+  struct sockaddr_un saddr;
+  const char* pipe_fname = NULL;
+  int sockfd = -1;
+  int err;
+
+  /* Already bound? */
+  if (uv__stream_fd(handle) >= 0)
+    return -EINVAL;
+
+  /* Make a copy of the file name, it outlives this function's scope. */
+  pipe_fname = uv__strdup(name);
+  if (pipe_fname == NULL)
+    return -ENOMEM;
+
+  /* We've got a copy, don't touch the original any more. */
+  name = NULL;
+
+  err = uv__socket(AF_UNIX, SOCK_STREAM, 0);
+  if (err < 0)
+    goto err_socket;
+  sockfd = err;
+
+  memset(&saddr, 0, sizeof saddr);
+  strncpy(saddr.sun_path, pipe_fname, sizeof(saddr.sun_path) - 1);
+  saddr.sun_path[sizeof(saddr.sun_path) - 1] = '\0';
+  saddr.sun_family = AF_UNIX;
+
+  if (bind(sockfd, (struct sockaddr*)&saddr, sizeof saddr)) {
+    err = -errno;
+    /* Convert ENOENT to EACCES for compatibility with Windows. */
+    if (err == -ENOENT)
+      err = -EACCES;
+    goto err_bind;
+  }
+
+  /* Success. */
+  handle->flags |= UV_HANDLE_BOUND;
+  handle->pipe_fname = pipe_fname; /* Is a strdup'ed copy. */
+  handle->io_watcher.fd = sockfd;
+  return 0;
+
+err_bind:
+  uv__close(sockfd);
+
+err_socket:
+  uv__free((void*)pipe_fname);
+  return err;
+}
+
+
+int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) {
+  if (uv__stream_fd(handle) == -1)
+    return -EINVAL;
+
+#if defined(__MVS__)
+  /* On zOS, backlog=0 has undefined behaviour */
+  if (backlog == 0)
+    backlog = 1;
+  else if (backlog < 0)
+    backlog = SOMAXCONN;
+#endif
+
+  if (listen(uv__stream_fd(handle), backlog))
+    return -errno;
+
+  handle->connection_cb = cb;
+  handle->io_watcher.cb = uv__server_io;
+  uv__io_start(handle->loop, &handle->io_watcher, POLLIN);
+  return 0;
+}
+
+
+void uv__pipe_close(uv_pipe_t* handle) {
+  if (handle->pipe_fname) {
+    /*
+     * Unlink the file system entity before closing the file descriptor.
+     * Doing it the other way around introduces a race where our process
+     * unlinks a socket with the same name that's just been created by
+     * another thread or process.
+     */
+    unlink(handle->pipe_fname);
+    uv__free((void*)handle->pipe_fname);
+    handle->pipe_fname = NULL;
+  }
+
+  uv__stream_close((uv_stream_t*)handle);
+}
+
+
+int uv_pipe_open(uv_pipe_t* handle, uv_file fd) {
+  int err;
+
+  err = uv__nonblock(fd, 1);
+  if (err)
+    return err;
+
+#if defined(__APPLE__)
+  err = uv__stream_try_select((uv_stream_t*) handle, &fd);
+  if (err)
+    return err;
+#endif /* defined(__APPLE__) */
+
+  return uv__stream_open((uv_stream_t*)handle,
+                         fd,
+                         UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+}
+
+
+void uv_pipe_connect(uv_connect_t* req,
+                    uv_pipe_t* handle,
+                    const char* name,
+                    uv_connect_cb cb) {
+  struct sockaddr_un saddr;
+  int new_sock;
+  int err;
+  int r;
+
+  new_sock = (uv__stream_fd(handle) == -1);
+
+  if (new_sock) {
+    err = uv__socket(AF_UNIX, SOCK_STREAM, 0);
+    if (err < 0)
+      goto out;
+    handle->io_watcher.fd = err;
+  }
+
+  memset(&saddr, 0, sizeof saddr);
+  strncpy(saddr.sun_path, name, sizeof(saddr.sun_path) - 1);
+  saddr.sun_path[sizeof(saddr.sun_path) - 1] = '\0';
+  saddr.sun_family = AF_UNIX;
+
+  do {
+    r = connect(uv__stream_fd(handle),
+                (struct sockaddr*)&saddr, sizeof saddr);
+  }
+  while (r == -1 && errno == EINTR);
+
+  if (r == -1 && errno != EINPROGRESS) {
+    err = -errno;
+    goto out;
+  }
+
+  err = 0;
+  if (new_sock) {
+    err = uv__stream_open((uv_stream_t*)handle,
+                          uv__stream_fd(handle),
+                          UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+  }
+
+  if (err == 0)
+    uv__io_start(handle->loop, &handle->io_watcher, POLLIN | POLLOUT);
+
+out:
+  handle->delayed_error = err;
+  handle->connect_req = req;
+
+  uv__req_init(handle->loop, req, UV_CONNECT);
+  req->handle = (uv_stream_t*)handle;
+  req->cb = cb;
+  QUEUE_INIT(&req->queue);
+
+  /* Force callback to run on next tick in case of error. */
+  if (err)
+    uv__io_feed(handle->loop, &handle->io_watcher);
+
+}
+
+
+typedef int (*uv__peersockfunc)(int, struct sockaddr*, socklen_t*);
+
+
+static int uv__pipe_getsockpeername(const uv_pipe_t* handle,
+                                    uv__peersockfunc func,
+                                    char* buffer,
+                                    size_t* size) {
+  struct sockaddr_un sa;
+  socklen_t addrlen;
+  int err;
+
+  addrlen = sizeof(sa);
+  memset(&sa, 0, addrlen);
+  err = func(uv__stream_fd(handle), (struct sockaddr*) &sa, &addrlen);
+  if (err < 0) {
+    *size = 0;
+    return -errno;
+  }
+
+#if defined(__linux__)
+  if (sa.sun_path[0] == 0)
+    /* Linux abstract namespace */
+    addrlen -= offsetof(struct sockaddr_un, sun_path);
+  else
+#endif
+    addrlen = strlen(sa.sun_path);
+
+
+  if (addrlen >= *size) {
+    *size = addrlen + 1;
+    return UV_ENOBUFS;
+  }
+
+  memcpy(buffer, sa.sun_path, addrlen);
+  *size = addrlen;
+
+  /* only null-terminate if it's not an abstract socket */
+  if (buffer[0] != '\0')
+    buffer[addrlen] = '\0';
+
+  return 0;
+}
+
+
+int uv_pipe_getsockname(const uv_pipe_t* handle, char* buffer, size_t* size) {
+  return uv__pipe_getsockpeername(handle, getsockname, buffer, size);
+}
+
+
+int uv_pipe_getpeername(const uv_pipe_t* handle, char* buffer, size_t* size) {
+  return uv__pipe_getsockpeername(handle, getpeername, buffer, size);
+}
+
+
+void uv_pipe_pending_instances(uv_pipe_t* handle, int count) {
+}
+
+
+int uv_pipe_pending_count(uv_pipe_t* handle) {
+  uv__stream_queued_fds_t* queued_fds;
+
+  if (!handle->ipc)
+    return 0;
+
+  if (handle->accepted_fd == -1)
+    return 0;
+
+  if (handle->queued_fds == NULL)
+    return 1;
+
+  queued_fds = handle->queued_fds;
+  return queued_fds->offset + 1;
+}
+
+
+uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle) {
+  if (!handle->ipc)
+    return UV_UNKNOWN_HANDLE;
+
+  if (handle->accepted_fd == -1)
+    return UV_UNKNOWN_HANDLE;
+  else
+    return uv__handle_type(handle->accepted_fd);
+}
diff --git a/Utilities/cmlibuv/src/unix/poll.c b/Utilities/cmlibuv/src/unix/poll.c
new file mode 100644
index 0000000..4c0d478
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/poll.c
@@ -0,0 +1,130 @@
+/* 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 "internal.h"
+
+#include <unistd.h>
+#include <assert.h>
+#include <errno.h>
+
+
+static void uv__poll_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  uv_poll_t* handle;
+  int pevents;
+
+  handle = container_of(w, uv_poll_t, io_watcher);
+
+  if (events & POLLERR) {
+    uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP);
+    uv__handle_stop(handle);
+    handle->poll_cb(handle, -EBADF, 0);
+    return;
+  }
+
+  pevents = 0;
+  if (events & POLLIN)
+    pevents |= UV_READABLE;
+  if (events & POLLOUT)
+    pevents |= UV_WRITABLE;
+  if (events & UV__POLLRDHUP)
+    pevents |= UV_DISCONNECT;
+
+  handle->poll_cb(handle, 0, pevents);
+}
+
+
+int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd) {
+  int err;
+
+  err = uv__io_check_fd(loop, fd);
+  if (err)
+    return err;
+
+  /* If ioctl(FIONBIO) reports ENOTTY, try fcntl(F_GETFL) + fcntl(F_SETFL).
+   * Workaround for e.g. kqueue fds not supporting ioctls.
+   */
+  err = uv__nonblock(fd, 1);
+  if (err == -ENOTTY)
+    if (uv__nonblock == uv__nonblock_ioctl)
+      err = uv__nonblock_fcntl(fd, 1);
+
+  if (err)
+    return err;
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_POLL);
+  uv__io_init(&handle->io_watcher, uv__poll_io, fd);
+  handle->poll_cb = NULL;
+  return 0;
+}
+
+
+int uv_poll_init_socket(uv_loop_t* loop, uv_poll_t* handle,
+    uv_os_sock_t socket) {
+  return uv_poll_init(loop, handle, socket);
+}
+
+
+static void uv__poll_stop(uv_poll_t* handle) {
+  uv__io_stop(handle->loop,
+              &handle->io_watcher,
+              POLLIN | POLLOUT | UV__POLLRDHUP);
+  uv__handle_stop(handle);
+}
+
+
+int uv_poll_stop(uv_poll_t* handle) {
+  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
+  uv__poll_stop(handle);
+  return 0;
+}
+
+
+int uv_poll_start(uv_poll_t* handle, int pevents, uv_poll_cb poll_cb) {
+  int events;
+
+  assert((pevents & ~(UV_READABLE | UV_WRITABLE | UV_DISCONNECT)) == 0);
+  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
+
+  uv__poll_stop(handle);
+
+  if (pevents == 0)
+    return 0;
+
+  events = 0;
+  if (pevents & UV_READABLE)
+    events |= POLLIN;
+  if (pevents & UV_WRITABLE)
+    events |= POLLOUT;
+  if (pevents & UV_DISCONNECT)
+    events |= UV__POLLRDHUP;
+
+  uv__io_start(handle->loop, &handle->io_watcher, events);
+  uv__handle_start(handle);
+  handle->poll_cb = poll_cb;
+
+  return 0;
+}
+
+
+void uv__poll_close(uv_poll_t* handle) {
+  uv__poll_stop(handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/process.c b/Utilities/cmlibuv/src/unix/process.c
new file mode 100644
index 0000000..45f5b45
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/process.c
@@ -0,0 +1,563 @@
+/* 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 "internal.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <poll.h>
+
+#if defined(__APPLE__) && !TARGET_OS_IPHONE
+# include <crt_externs.h>
+# define environ (*_NSGetEnviron())
+#else
+extern char **environ;
+#endif
+
+#if defined(__linux__) || defined(__GLIBC__)
+# include <grp.h>
+#endif
+
+
+static void uv__chld(uv_signal_t* handle, int signum) {
+  uv_process_t* process;
+  uv_loop_t* loop;
+  int exit_status;
+  int term_signal;
+  int status;
+  pid_t pid;
+  QUEUE pending;
+  QUEUE* q;
+  QUEUE* h;
+
+  assert(signum == SIGCHLD);
+
+  QUEUE_INIT(&pending);
+  loop = handle->loop;
+
+  h = &loop->process_handles;
+  q = QUEUE_HEAD(h);
+  while (q != h) {
+    process = QUEUE_DATA(q, uv_process_t, queue);
+    q = QUEUE_NEXT(q);
+
+    do
+      pid = waitpid(process->pid, &status, WNOHANG);
+    while (pid == -1 && errno == EINTR);
+
+    if (pid == 0)
+      continue;
+
+    if (pid == -1) {
+      if (errno != ECHILD)
+        abort();
+      continue;
+    }
+
+    process->status = status;
+    QUEUE_REMOVE(&process->queue);
+    QUEUE_INSERT_TAIL(&pending, &process->queue);
+  }
+
+  h = &pending;
+  q = QUEUE_HEAD(h);
+  while (q != h) {
+    process = QUEUE_DATA(q, uv_process_t, queue);
+    q = QUEUE_NEXT(q);
+
+    QUEUE_REMOVE(&process->queue);
+    QUEUE_INIT(&process->queue);
+    uv__handle_stop(process);
+
+    if (process->exit_cb == NULL)
+      continue;
+
+    exit_status = 0;
+    if (WIFEXITED(process->status))
+      exit_status = WEXITSTATUS(process->status);
+
+    term_signal = 0;
+    if (WIFSIGNALED(process->status))
+      term_signal = WTERMSIG(process->status);
+
+    process->exit_cb(process, exit_status, term_signal);
+  }
+  assert(QUEUE_EMPTY(&pending));
+}
+
+
+int uv__make_socketpair(int fds[2], int flags) {
+#if defined(__linux__)
+  static int no_cloexec;
+
+  if (no_cloexec)
+    goto skip;
+
+  if (socketpair(AF_UNIX, SOCK_STREAM | UV__SOCK_CLOEXEC | flags, 0, fds) == 0)
+    return 0;
+
+  /* Retry on EINVAL, it means SOCK_CLOEXEC is not supported.
+   * Anything else is a genuine error.
+   */
+  if (errno != EINVAL)
+    return -errno;
+
+  no_cloexec = 1;
+
+skip:
+#endif
+
+  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
+    return -errno;
+
+  uv__cloexec(fds[0], 1);
+  uv__cloexec(fds[1], 1);
+
+  if (flags & UV__F_NONBLOCK) {
+    uv__nonblock(fds[0], 1);
+    uv__nonblock(fds[1], 1);
+  }
+
+  return 0;
+}
+
+
+int uv__make_pipe(int fds[2], int flags) {
+#if defined(__linux__)
+  static int no_pipe2;
+
+  if (no_pipe2)
+    goto skip;
+
+  if (uv__pipe2(fds, flags | UV__O_CLOEXEC) == 0)
+    return 0;
+
+  if (errno != ENOSYS)
+    return -errno;
+
+  no_pipe2 = 1;
+
+skip:
+#endif
+
+  if (pipe(fds))
+    return -errno;
+
+  uv__cloexec(fds[0], 1);
+  uv__cloexec(fds[1], 1);
+
+  if (flags & UV__F_NONBLOCK) {
+    uv__nonblock(fds[0], 1);
+    uv__nonblock(fds[1], 1);
+  }
+
+  return 0;
+}
+
+
+/*
+ * Used for initializing stdio streams like options.stdin_stream. Returns
+ * zero on success. See also the cleanup section in uv_spawn().
+ */
+static int uv__process_init_stdio(uv_stdio_container_t* container, int fds[2]) {
+  int mask;
+  int fd;
+
+  mask = UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD | UV_INHERIT_STREAM;
+
+  switch (container->flags & mask) {
+  case UV_IGNORE:
+    return 0;
+
+  case UV_CREATE_PIPE:
+    assert(container->data.stream != NULL);
+    if (container->data.stream->type != UV_NAMED_PIPE)
+      return -EINVAL;
+    else
+      return uv__make_socketpair(fds, 0);
+
+  case UV_INHERIT_FD:
+  case UV_INHERIT_STREAM:
+    if (container->flags & UV_INHERIT_FD)
+      fd = container->data.fd;
+    else
+      fd = uv__stream_fd(container->data.stream);
+
+    if (fd == -1)
+      return -EINVAL;
+
+    fds[1] = fd;
+    return 0;
+
+  default:
+    assert(0 && "Unexpected flags");
+    return -EINVAL;
+  }
+}
+
+
+static int uv__process_open_stream(uv_stdio_container_t* container,
+                                   int pipefds[2],
+                                   int writable) {
+  int flags;
+  int err;
+
+  if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0)
+    return 0;
+
+  err = uv__close(pipefds[1]);
+  if (err != 0)
+    abort();
+
+  pipefds[1] = -1;
+  uv__nonblock(pipefds[0], 1);
+
+  if (container->data.stream->type == UV_NAMED_PIPE &&
+      ((uv_pipe_t*)container->data.stream)->ipc)
+    flags = UV_STREAM_READABLE | UV_STREAM_WRITABLE;
+  else if (writable)
+    flags = UV_STREAM_WRITABLE;
+  else
+    flags = UV_STREAM_READABLE;
+
+  return uv__stream_open(container->data.stream, pipefds[0], flags);
+}
+
+
+static void uv__process_close_stream(uv_stdio_container_t* container) {
+  if (!(container->flags & UV_CREATE_PIPE)) return;
+  uv__stream_close((uv_stream_t*)container->data.stream);
+}
+
+
+static void uv__write_int(int fd, int val) {
+  ssize_t n;
+
+  do
+    n = write(fd, &val, sizeof(val));
+  while (n == -1 && errno == EINTR);
+
+  if (n == -1 && errno == EPIPE)
+    return; /* parent process has quit */
+
+  assert(n == sizeof(val));
+}
+
+
+#if !(defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH))
+/* execvp is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED, so must be
+ * avoided. Since this isn't called on those targets, the function
+ * doesn't even need to be defined for them.
+ */
+static void uv__process_child_init(const uv_process_options_t* options,
+                                   int stdio_count,
+                                   int (*pipes)[2],
+                                   int error_fd) {
+  int close_fd;
+  int use_fd;
+  int fd;
+
+  if (options->flags & UV_PROCESS_DETACHED)
+    setsid();
+
+  /* First duplicate low numbered fds, since it's not safe to duplicate them,
+   * they could get replaced. Example: swapping stdout and stderr; without
+   * this fd 2 (stderr) would be duplicated into fd 1, thus making both
+   * stdout and stderr go to the same fd, which was not the intention. */
+  for (fd = 0; fd < stdio_count; fd++) {
+    use_fd = pipes[fd][1];
+    if (use_fd < 0 || use_fd >= fd)
+      continue;
+    pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count);
+    if (pipes[fd][1] == -1) {
+      uv__write_int(error_fd, -errno);
+      _exit(127);
+    }
+  }
+
+  for (fd = 0; fd < stdio_count; fd++) {
+    close_fd = pipes[fd][0];
+    use_fd = pipes[fd][1];
+
+    if (use_fd < 0) {
+      if (fd >= 3)
+        continue;
+      else {
+        /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is
+         * set
+         */
+        use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR);
+        close_fd = use_fd;
+
+        if (use_fd == -1) {
+          uv__write_int(error_fd, -errno);
+          _exit(127);
+        }
+      }
+    }
+
+    if (fd == use_fd)
+      uv__cloexec(use_fd, 0);
+    else
+      fd = dup2(use_fd, fd);
+
+    if (fd == -1) {
+      uv__write_int(error_fd, -errno);
+      _exit(127);
+    }
+
+    if (fd <= 2)
+      uv__nonblock(fd, 0);
+
+    if (close_fd >= stdio_count)
+      uv__close(close_fd);
+  }
+
+  for (fd = 0; fd < stdio_count; fd++) {
+    use_fd = pipes[fd][1];
+
+    if (use_fd >= stdio_count)
+      uv__close(use_fd);
+  }
+
+  if (options->cwd != NULL && chdir(options->cwd)) {
+    uv__write_int(error_fd, -errno);
+    _exit(127);
+  }
+
+  if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
+    /* When dropping privileges from root, the `setgroups` call will
+     * remove any extraneous groups. If we don't call this, then
+     * even though our uid has dropped, we may still have groups
+     * that enable us to do super-user things. This will fail if we
+     * aren't root, so don't bother checking the return value, this
+     * is just done as an optimistic privilege dropping function.
+     */
+    SAVE_ERRNO(setgroups(0, NULL));
+  }
+
+  if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) {
+    uv__write_int(error_fd, -errno);
+    _exit(127);
+  }
+
+  if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) {
+    uv__write_int(error_fd, -errno);
+    _exit(127);
+  }
+
+  if (options->env != NULL) {
+    environ = options->env;
+  }
+
+  execvp(options->file, options->args);
+  uv__write_int(error_fd, -errno);
+  _exit(127);
+}
+#endif
+
+
+int uv_spawn(uv_loop_t* loop,
+             uv_process_t* process,
+             const uv_process_options_t* options) {
+#if defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH)
+  /* fork is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED. */
+  return -ENOSYS;
+#else
+  int signal_pipe[2] = { -1, -1 };
+  int (*pipes)[2];
+  int stdio_count;
+  ssize_t r;
+  pid_t pid;
+  int err;
+  int exec_errorno;
+  int i;
+  int status;
+
+  assert(options->file != NULL);
+  assert(!(options->flags & ~(UV_PROCESS_DETACHED |
+                              UV_PROCESS_SETGID |
+                              UV_PROCESS_SETUID |
+                              UV_PROCESS_WINDOWS_HIDE |
+                              UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
+
+  uv__handle_init(loop, (uv_handle_t*)process, UV_PROCESS);
+  QUEUE_INIT(&process->queue);
+
+  stdio_count = options->stdio_count;
+  if (stdio_count < 3)
+    stdio_count = 3;
+
+  err = -ENOMEM;
+  pipes = uv__malloc(stdio_count * sizeof(*pipes));
+  if (pipes == NULL)
+    goto error;
+
+  for (i = 0; i < stdio_count; i++) {
+    pipes[i][0] = -1;
+    pipes[i][1] = -1;
+  }
+
+  for (i = 0; i < options->stdio_count; i++) {
+    err = uv__process_init_stdio(options->stdio + i, pipes[i]);
+    if (err)
+      goto error;
+  }
+
+  /* This pipe is used by the parent to wait until
+   * the child has called `execve()`. We need this
+   * to avoid the following race condition:
+   *
+   *    if ((pid = fork()) > 0) {
+   *      kill(pid, SIGTERM);
+   *    }
+   *    else if (pid == 0) {
+   *      execve("/bin/cat", argp, envp);
+   *    }
+   *
+   * The parent sends a signal immediately after forking.
+   * Since the child may not have called `execve()` yet,
+   * there is no telling what process receives the signal,
+   * our fork or /bin/cat.
+   *
+   * To avoid ambiguity, we create a pipe with both ends
+   * marked close-on-exec. Then, after the call to `fork()`,
+   * the parent polls the read end until it EOFs or errors with EPIPE.
+   */
+  err = uv__make_pipe(signal_pipe, 0);
+  if (err)
+    goto error;
+
+  uv_signal_start(&loop->child_watcher, uv__chld, SIGCHLD);
+
+  /* Acquire write lock to prevent opening new fds in worker threads */
+  uv_rwlock_wrlock(&loop->cloexec_lock);
+  pid = fork();
+
+  if (pid == -1) {
+    err = -errno;
+    uv_rwlock_wrunlock(&loop->cloexec_lock);
+    uv__close(signal_pipe[0]);
+    uv__close(signal_pipe[1]);
+    goto error;
+  }
+
+  if (pid == 0) {
+    uv__process_child_init(options, stdio_count, pipes, signal_pipe[1]);
+    abort();
+  }
+
+  /* Release lock in parent process */
+  uv_rwlock_wrunlock(&loop->cloexec_lock);
+  uv__close(signal_pipe[1]);
+
+  process->status = 0;
+  exec_errorno = 0;
+  do
+    r = read(signal_pipe[0], &exec_errorno, sizeof(exec_errorno));
+  while (r == -1 && errno == EINTR);
+
+  if (r == 0)
+    ; /* okay, EOF */
+  else if (r == sizeof(exec_errorno)) {
+    do
+      err = waitpid(pid, &status, 0); /* okay, read errorno */
+    while (err == -1 && errno == EINTR);
+    assert(err == pid);
+  } else if (r == -1 && errno == EPIPE) {
+    do
+      err = waitpid(pid, &status, 0); /* okay, got EPIPE */
+    while (err == -1 && errno == EINTR);
+    assert(err == pid);
+  } else
+    abort();
+
+  uv__close_nocheckstdio(signal_pipe[0]);
+
+  for (i = 0; i < options->stdio_count; i++) {
+    err = uv__process_open_stream(options->stdio + i, pipes[i], i == 0);
+    if (err == 0)
+      continue;
+
+    while (i--)
+      uv__process_close_stream(options->stdio + i);
+
+    goto error;
+  }
+
+  /* Only activate this handle if exec() happened successfully */
+  if (exec_errorno == 0) {
+    QUEUE_INSERT_TAIL(&loop->process_handles, &process->queue);
+    uv__handle_start(process);
+  }
+
+  process->pid = pid;
+  process->exit_cb = options->exit_cb;
+
+  uv__free(pipes);
+  return exec_errorno;
+
+error:
+  if (pipes != NULL) {
+    for (i = 0; i < stdio_count; i++) {
+      if (i < options->stdio_count)
+        if (options->stdio[i].flags & (UV_INHERIT_FD | UV_INHERIT_STREAM))
+          continue;
+      if (pipes[i][0] != -1)
+        uv__close_nocheckstdio(pipes[i][0]);
+      if (pipes[i][1] != -1)
+        uv__close_nocheckstdio(pipes[i][1]);
+    }
+    uv__free(pipes);
+  }
+
+  return err;
+#endif
+}
+
+
+int uv_process_kill(uv_process_t* process, int signum) {
+  return uv_kill(process->pid, signum);
+}
+
+
+int uv_kill(int pid, int signum) {
+  if (kill(pid, signum))
+    return -errno;
+  else
+    return 0;
+}
+
+
+void uv__process_close(uv_process_t* handle) {
+  QUEUE_REMOVE(&handle->queue);
+  uv__handle_stop(handle);
+  if (QUEUE_EMPTY(&handle->loop->process_handles))
+    uv_signal_stop(&handle->loop->child_watcher);
+}
diff --git a/Utilities/cmlibuv/src/unix/proctitle.c b/Utilities/cmlibuv/src/unix/proctitle.c
new file mode 100644
index 0000000..08d875f
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/proctitle.c
@@ -0,0 +1,105 @@
+/* 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 "internal.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+extern void uv__set_process_title(const char* title);
+
+static void* args_mem;
+
+static struct {
+  char* str;
+  size_t len;
+} process_title;
+
+
+char** uv_setup_args(int argc, char** argv) {
+  char** new_argv;
+  size_t size;
+  char* s;
+  int i;
+
+  if (argc <= 0)
+    return argv;
+
+  /* Calculate how much memory we need for the argv strings. */
+  size = 0;
+  for (i = 0; i < argc; i++)
+    size += strlen(argv[i]) + 1;
+
+  process_title.str = argv[0];
+  process_title.len = argv[argc - 1] + strlen(argv[argc - 1]) - argv[0];
+  assert(process_title.len + 1 == size);  /* argv memory should be adjacent. */
+
+  /* Add space for the argv pointers. */
+  size += (argc + 1) * sizeof(char*);
+
+  new_argv = uv__malloc(size);
+  if (new_argv == NULL)
+    return argv;
+  args_mem = new_argv;
+
+  /* Copy over the strings and set up the pointer table. */
+  s = (char*) &new_argv[argc + 1];
+  for (i = 0; i < argc; i++) {
+    size = strlen(argv[i]) + 1;
+    memcpy(s, argv[i], size);
+    new_argv[i] = s;
+    s += size;
+  }
+  new_argv[i] = NULL;
+
+  return new_argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  if (process_title.len == 0)
+    return 0;
+
+  /* No need to terminate, byte after is always '\0'. */
+  strncpy(process_title.str, title, process_title.len);
+  uv__set_process_title(title);
+
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+  else if (size <= process_title.len)
+    return -ENOBUFS;
+
+  memcpy(buffer, process_title.str, process_title.len + 1);
+  buffer[process_title.len] = '\0';
+
+  return 0;
+}
+
+
+UV_DESTRUCTOR(static void free_args_mem(void)) {
+  uv__free(args_mem);  /* Keep valgrind happy. */
+  args_mem = NULL;
+}
diff --git a/Utilities/cmlibuv/src/unix/pthread-barrier.c b/Utilities/cmlibuv/src/unix/pthread-barrier.c
new file mode 100644
index 0000000..f57bf25
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/pthread-barrier.c
@@ -0,0 +1,120 @@
+/*
+Copyright (c) 2016, Kari Tristan Helgason <kthelgason at gmail.com>
+
+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.
+*/
+#include "uv-common.h"
+#include "pthread-barrier.h"
+
+#include <stdlib.h>
+#include <assert.h>
+
+/* TODO: support barrier_attr */
+int pthread_barrier_init(pthread_barrier_t* barrier,
+                         const void* barrier_attr,
+                         unsigned count) {
+  int rc;
+  _uv_barrier* b;
+
+  if (barrier == NULL || count == 0)
+    return EINVAL;
+
+  if (barrier_attr != NULL)
+    return ENOTSUP;
+
+  b = uv__malloc(sizeof(*b));
+  if (b == NULL)
+    return ENOMEM;
+
+  b->in = 0;
+  b->out = 0;
+  b->threshold = count;
+
+  if ((rc = pthread_mutex_init(&b->mutex, NULL)) != 0)
+    goto error2;
+  if ((rc = pthread_cond_init(&b->cond, NULL)) != 0)
+    goto error;
+
+  barrier->b = b;
+  return 0;
+
+error:
+  pthread_mutex_destroy(&b->mutex);
+error2:
+  uv__free(b);
+  return rc;
+}
+
+int pthread_barrier_wait(pthread_barrier_t* barrier) {
+  int rc;
+  _uv_barrier* b;
+
+  if (barrier == NULL || barrier->b == NULL)
+    return EINVAL;
+
+  b = barrier->b;
+  /* Lock the mutex*/
+  if ((rc = pthread_mutex_lock(&b->mutex)) != 0)
+    return rc;
+
+  /* Increment the count. If this is the first thread to reach the threshold,
+     wake up waiters, unlock the mutex, then return
+     PTHREAD_BARRIER_SERIAL_THREAD. */
+  if (++b->in == b->threshold) {
+    b->in = 0;
+    b->out = b->threshold - 1;
+    assert(pthread_cond_signal(&b->cond) == 0);
+
+    pthread_mutex_unlock(&b->mutex);
+    return PTHREAD_BARRIER_SERIAL_THREAD;
+  }
+  /* Otherwise, wait for other threads until in is set to 0,
+     then return 0 to indicate this is not the first thread. */
+  do {
+    if ((rc = pthread_cond_wait(&b->cond, &b->mutex)) != 0)
+      break;
+  } while (b->in != 0);
+
+  /* mark thread exit */
+  b->out--;
+  pthread_cond_signal(&b->cond);
+  pthread_mutex_unlock(&b->mutex);
+  return rc;
+}
+
+int pthread_barrier_destroy(pthread_barrier_t* barrier) {
+  int rc;
+  _uv_barrier* b;
+
+  if (barrier == NULL || barrier->b == NULL)
+    return EINVAL;
+
+  b = barrier->b;
+
+  if ((rc = pthread_mutex_lock(&b->mutex)) != 0)
+    return rc;
+
+  if (b->in > 0 || b->out > 0)
+    rc = EBUSY;
+
+  pthread_mutex_unlock(&b->mutex);
+
+  if (rc)
+    return rc;
+
+  pthread_cond_destroy(&b->cond);
+  pthread_mutex_destroy(&b->mutex);
+  uv__free(barrier->b);
+  barrier->b = NULL;
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/unix/pthread-fixes.c b/Utilities/cmlibuv/src/unix/pthread-fixes.c
new file mode 100644
index 0000000..fb17995
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/pthread-fixes.c
@@ -0,0 +1,56 @@
+/* Copyright (c) 2013, Sony Mobile Communications AB
+ * Copyright (c) 2012, Google 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 of Google Inc. 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.
+*/
+
+/* Android versions < 4.1 have a broken pthread_sigmask. */
+#include <errno.h>
+#include <pthread.h>
+#include <signal.h>
+
+int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset) {
+  static int workaround;
+  int err;
+
+  if (workaround) {
+    return sigprocmask(how, set, oset);
+  } else {
+    err = pthread_sigmask(how, set, oset);
+    if (err) {
+      if (err == EINVAL && sigprocmask(how, set, oset) == 0) {
+        workaround = 1;
+        return 0;
+      } else {
+        return -1;
+      }
+    }
+  }
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/unix/signal.c b/Utilities/cmlibuv/src/unix/signal.c
new file mode 100644
index 0000000..d82b9b7
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/signal.c
@@ -0,0 +1,467 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+
+typedef struct {
+  uv_signal_t* handle;
+  int signum;
+} uv__signal_msg_t;
+
+RB_HEAD(uv__signal_tree_s, uv_signal_s);
+
+
+static int uv__signal_unlock(void);
+static void uv__signal_event(uv_loop_t* loop, uv__io_t* w, unsigned int events);
+static int uv__signal_compare(uv_signal_t* w1, uv_signal_t* w2);
+static void uv__signal_stop(uv_signal_t* handle);
+
+
+static pthread_once_t uv__signal_global_init_guard = PTHREAD_ONCE_INIT;
+static struct uv__signal_tree_s uv__signal_tree =
+    RB_INITIALIZER(uv__signal_tree);
+static int uv__signal_lock_pipefd[2];
+
+
+RB_GENERATE_STATIC(uv__signal_tree_s,
+                   uv_signal_s, tree_entry,
+                   uv__signal_compare)
+
+
+static void uv__signal_global_init(void) {
+  if (uv__make_pipe(uv__signal_lock_pipefd, 0))
+    abort();
+
+  if (uv__signal_unlock())
+    abort();
+}
+
+
+void uv__signal_global_once_init(void) {
+  pthread_once(&uv__signal_global_init_guard, uv__signal_global_init);
+}
+
+
+
+static int uv__signal_lock(void) {
+  int r;
+  char data;
+
+  do {
+    r = read(uv__signal_lock_pipefd[0], &data, sizeof data);
+  } while (r < 0 && errno == EINTR);
+
+  return (r < 0) ? -1 : 0;
+}
+
+
+static int uv__signal_unlock(void) {
+  int r;
+  char data = 42;
+
+  do {
+    r = write(uv__signal_lock_pipefd[1], &data, sizeof data);
+  } while (r < 0 && errno == EINTR);
+
+  return (r < 0) ? -1 : 0;
+}
+
+
+static void uv__signal_block_and_lock(sigset_t* saved_sigmask) {
+  sigset_t new_mask;
+
+  if (sigfillset(&new_mask))
+    abort();
+
+  if (pthread_sigmask(SIG_SETMASK, &new_mask, saved_sigmask))
+    abort();
+
+  if (uv__signal_lock())
+    abort();
+}
+
+
+static void uv__signal_unlock_and_unblock(sigset_t* saved_sigmask) {
+  if (uv__signal_unlock())
+    abort();
+
+  if (pthread_sigmask(SIG_SETMASK, saved_sigmask, NULL))
+    abort();
+}
+
+
+static uv_signal_t* uv__signal_first_handle(int signum) {
+  /* This function must be called with the signal lock held. */
+  uv_signal_t lookup;
+  uv_signal_t* handle;
+
+  lookup.signum = signum;
+  lookup.loop = NULL;
+
+  handle = RB_NFIND(uv__signal_tree_s, &uv__signal_tree, &lookup);
+
+  if (handle != NULL && handle->signum == signum)
+    return handle;
+
+  return NULL;
+}
+
+
+static void uv__signal_handler(int signum) {
+  uv__signal_msg_t msg;
+  uv_signal_t* handle;
+  int saved_errno;
+
+  saved_errno = errno;
+  memset(&msg, 0, sizeof msg);
+
+  if (uv__signal_lock()) {
+    errno = saved_errno;
+    return;
+  }
+
+  for (handle = uv__signal_first_handle(signum);
+       handle != NULL && handle->signum == signum;
+       handle = RB_NEXT(uv__signal_tree_s, &uv__signal_tree, handle)) {
+    int r;
+
+    msg.signum = signum;
+    msg.handle = handle;
+
+    /* write() should be atomic for small data chunks, so the entire message
+     * should be written at once. In theory the pipe could become full, in
+     * which case the user is out of luck.
+     */
+    do {
+      r = write(handle->loop->signal_pipefd[1], &msg, sizeof msg);
+    } while (r == -1 && errno == EINTR);
+
+    assert(r == sizeof msg ||
+           (r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)));
+
+    if (r != -1)
+      handle->caught_signals++;
+  }
+
+  uv__signal_unlock();
+  errno = saved_errno;
+}
+
+
+static int uv__signal_register_handler(int signum) {
+  /* When this function is called, the signal lock must be held. */
+  struct sigaction sa;
+
+  /* XXX use a separate signal stack? */
+  memset(&sa, 0, sizeof(sa));
+  if (sigfillset(&sa.sa_mask))
+    abort();
+  sa.sa_handler = uv__signal_handler;
+
+  /* XXX save old action so we can restore it later on? */
+  if (sigaction(signum, &sa, NULL))
+    return -errno;
+
+  return 0;
+}
+
+
+static void uv__signal_unregister_handler(int signum) {
+  /* When this function is called, the signal lock must be held. */
+  struct sigaction sa;
+
+  memset(&sa, 0, sizeof(sa));
+  sa.sa_handler = SIG_DFL;
+
+  /* sigaction can only fail with EINVAL or EFAULT; an attempt to deregister a
+   * signal implies that it was successfully registered earlier, so EINVAL
+   * should never happen.
+   */
+  if (sigaction(signum, &sa, NULL))
+    abort();
+}
+
+
+static int uv__signal_loop_once_init(uv_loop_t* loop) {
+  int err;
+
+  /* Return if already initialized. */
+  if (loop->signal_pipefd[0] != -1)
+    return 0;
+
+  err = uv__make_pipe(loop->signal_pipefd, UV__F_NONBLOCK);
+  if (err)
+    return err;
+
+  uv__io_init(&loop->signal_io_watcher,
+              uv__signal_event,
+              loop->signal_pipefd[0]);
+  uv__io_start(loop, &loop->signal_io_watcher, POLLIN);
+
+  return 0;
+}
+
+
+void uv__signal_loop_cleanup(uv_loop_t* loop) {
+  QUEUE* q;
+
+  /* Stop all the signal watchers that are still attached to this loop. This
+   * ensures that the (shared) signal tree doesn't contain any invalid entries
+   * entries, and that signal handlers are removed when appropriate.
+   * It's safe to use QUEUE_FOREACH here because the handles and the handle
+   * queue are not modified by uv__signal_stop().
+   */
+  QUEUE_FOREACH(q, &loop->handle_queue) {
+    uv_handle_t* handle = QUEUE_DATA(q, uv_handle_t, handle_queue);
+
+    if (handle->type == UV_SIGNAL)
+      uv__signal_stop((uv_signal_t*) handle);
+  }
+
+  if (loop->signal_pipefd[0] != -1) {
+    uv__close(loop->signal_pipefd[0]);
+    loop->signal_pipefd[0] = -1;
+  }
+
+  if (loop->signal_pipefd[1] != -1) {
+    uv__close(loop->signal_pipefd[1]);
+    loop->signal_pipefd[1] = -1;
+  }
+}
+
+
+int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle) {
+  int err;
+
+  err = uv__signal_loop_once_init(loop);
+  if (err)
+    return err;
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_SIGNAL);
+  handle->signum = 0;
+  handle->caught_signals = 0;
+  handle->dispatched_signals = 0;
+
+  return 0;
+}
+
+
+void uv__signal_close(uv_signal_t* handle) {
+
+  uv__signal_stop(handle);
+
+  /* If there are any caught signals "trapped" in the signal pipe, we can't
+   * call the close callback yet. Otherwise, add the handle to the finish_close
+   * queue.
+   */
+  if (handle->caught_signals == handle->dispatched_signals) {
+    uv__make_close_pending((uv_handle_t*) handle);
+  }
+}
+
+
+int uv_signal_start(uv_signal_t* handle, uv_signal_cb signal_cb, int signum) {
+  sigset_t saved_sigmask;
+  int err;
+
+  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
+
+  /* If the user supplies signum == 0, then return an error already. If the
+   * signum is otherwise invalid then uv__signal_register will find out
+   * eventually.
+   */
+  if (signum == 0)
+    return -EINVAL;
+
+  /* Short circuit: if the signal watcher is already watching {signum} don't
+   * go through the process of deregistering and registering the handler.
+   * Additionally, this avoids pending signals getting lost in the small time
+   * time frame that handle->signum == 0.
+   */
+  if (signum == handle->signum) {
+    handle->signal_cb = signal_cb;
+    return 0;
+  }
+
+  /* If the signal handler was already active, stop it first. */
+  if (handle->signum != 0) {
+    uv__signal_stop(handle);
+  }
+
+  uv__signal_block_and_lock(&saved_sigmask);
+
+  /* If at this point there are no active signal watchers for this signum (in
+   * any of the loops), it's time to try and register a handler for it here.
+   */
+  if (uv__signal_first_handle(signum) == NULL) {
+    err = uv__signal_register_handler(signum);
+    if (err) {
+      /* Registering the signal handler failed. Must be an invalid signal. */
+      uv__signal_unlock_and_unblock(&saved_sigmask);
+      return err;
+    }
+  }
+
+  handle->signum = signum;
+  RB_INSERT(uv__signal_tree_s, &uv__signal_tree, handle);
+
+  uv__signal_unlock_and_unblock(&saved_sigmask);
+
+  handle->signal_cb = signal_cb;
+  uv__handle_start(handle);
+
+  return 0;
+}
+
+
+static void uv__signal_event(uv_loop_t* loop,
+                             uv__io_t* w,
+                             unsigned int events) {
+  uv__signal_msg_t* msg;
+  uv_signal_t* handle;
+  char buf[sizeof(uv__signal_msg_t) * 32];
+  size_t bytes, end, i;
+  int r;
+
+  bytes = 0;
+  end = 0;
+
+  do {
+    r = read(loop->signal_pipefd[0], buf + bytes, sizeof(buf) - bytes);
+
+    if (r == -1 && errno == EINTR)
+      continue;
+
+    if (r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+      /* If there are bytes in the buffer already (which really is extremely
+       * unlikely if possible at all) we can't exit the function here. We'll
+       * spin until more bytes are read instead.
+       */
+      if (bytes > 0)
+        continue;
+
+      /* Otherwise, there was nothing there. */
+      return;
+    }
+
+    /* Other errors really should never happen. */
+    if (r == -1)
+      abort();
+
+    bytes += r;
+
+    /* `end` is rounded down to a multiple of sizeof(uv__signal_msg_t). */
+    end = (bytes / sizeof(uv__signal_msg_t)) * sizeof(uv__signal_msg_t);
+
+    for (i = 0; i < end; i += sizeof(uv__signal_msg_t)) {
+      msg = (uv__signal_msg_t*) (buf + i);
+      handle = msg->handle;
+
+      if (msg->signum == handle->signum) {
+        assert(!(handle->flags & UV_CLOSING));
+        handle->signal_cb(handle, handle->signum);
+      }
+
+      handle->dispatched_signals++;
+
+      /* If uv_close was called while there were caught signals that were not
+       * yet dispatched, the uv__finish_close was deferred. Make close pending
+       * now if this has happened.
+       */
+      if ((handle->flags & UV_CLOSING) &&
+          (handle->caught_signals == handle->dispatched_signals)) {
+        uv__make_close_pending((uv_handle_t*) handle);
+      }
+    }
+
+    bytes -= end;
+
+    /* If there are any "partial" messages left, move them to the start of the
+     * the buffer, and spin. This should not happen.
+     */
+    if (bytes) {
+      memmove(buf, buf + end, bytes);
+      continue;
+    }
+  } while (end == sizeof buf);
+}
+
+
+static int uv__signal_compare(uv_signal_t* w1, uv_signal_t* w2) {
+  /* Compare signums first so all watchers with the same signnum end up
+   * adjacent.
+   */
+  if (w1->signum < w2->signum) return -1;
+  if (w1->signum > w2->signum) return 1;
+
+  /* Sort by loop pointer, so we can easily look up the first item after
+   * { .signum = x, .loop = NULL }.
+   */
+  if (w1->loop < w2->loop) return -1;
+  if (w1->loop > w2->loop) return 1;
+
+  if (w1 < w2) return -1;
+  if (w1 > w2) return 1;
+
+  return 0;
+}
+
+
+int uv_signal_stop(uv_signal_t* handle) {
+  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
+  uv__signal_stop(handle);
+  return 0;
+}
+
+
+static void uv__signal_stop(uv_signal_t* handle) {
+  uv_signal_t* removed_handle;
+  sigset_t saved_sigmask;
+
+  /* If the watcher wasn't started, this is a no-op. */
+  if (handle->signum == 0)
+    return;
+
+  uv__signal_block_and_lock(&saved_sigmask);
+
+  removed_handle = RB_REMOVE(uv__signal_tree_s, &uv__signal_tree, handle);
+  assert(removed_handle == handle);
+  (void) removed_handle;
+
+  /* Check if there are other active signal watchers observing this signal. If
+   * not, unregister the signal handler.
+   */
+  if (uv__signal_first_handle(handle->signum) == NULL)
+    uv__signal_unregister_handler(handle->signum);
+
+  uv__signal_unlock_and_unblock(&saved_sigmask);
+
+  handle->signum = 0;
+  uv__handle_stop(handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/spinlock.h b/Utilities/cmlibuv/src/unix/spinlock.h
new file mode 100644
index 0000000..a20c83c
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/spinlock.h
@@ -0,0 +1,53 @@
+/* Copyright (c) 2013, Ben Noordhuis <info at 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_SPINLOCK_H_
+#define UV_SPINLOCK_H_
+
+#include "internal.h"  /* ACCESS_ONCE, UV_UNUSED */
+#include "atomic-ops.h"
+
+#define UV_SPINLOCK_INITIALIZER { 0 }
+
+typedef struct {
+  int lock;
+} uv_spinlock_t;
+
+UV_UNUSED(static void uv_spinlock_init(uv_spinlock_t* spinlock));
+UV_UNUSED(static void uv_spinlock_lock(uv_spinlock_t* spinlock));
+UV_UNUSED(static void uv_spinlock_unlock(uv_spinlock_t* spinlock));
+UV_UNUSED(static int uv_spinlock_trylock(uv_spinlock_t* spinlock));
+
+UV_UNUSED(static void uv_spinlock_init(uv_spinlock_t* spinlock)) {
+  ACCESS_ONCE(int, spinlock->lock) = 0;
+}
+
+UV_UNUSED(static void uv_spinlock_lock(uv_spinlock_t* spinlock)) {
+  while (!uv_spinlock_trylock(spinlock)) cpu_relax();
+}
+
+UV_UNUSED(static void uv_spinlock_unlock(uv_spinlock_t* spinlock)) {
+  ACCESS_ONCE(int, spinlock->lock) = 0;
+}
+
+UV_UNUSED(static int uv_spinlock_trylock(uv_spinlock_t* spinlock)) {
+  /* TODO(bnoordhuis) Maybe change to a ticket lock to guarantee fair queueing.
+   * Not really critical until we have locks that are (frequently) contended
+   * for by several threads.
+   */
+  return 0 == cmpxchgi(&spinlock->lock, 0, 1);
+}
+
+#endif  /* UV_SPINLOCK_H_ */
diff --git a/Utilities/cmlibuv/src/unix/stream.c b/Utilities/cmlibuv/src/unix/stream.c
new file mode 100644
index 0000000..d20d0bc
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/stream.c
@@ -0,0 +1,1638 @@
+/* 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 "internal.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <limits.h> /* IOV_MAX */
+
+#if defined(__APPLE__)
+# include <sys/event.h>
+# include <sys/time.h>
+# include <sys/select.h>
+
+/* Forward declaration */
+typedef struct uv__stream_select_s uv__stream_select_t;
+
+struct uv__stream_select_s {
+  uv_stream_t* stream;
+  uv_thread_t thread;
+  uv_sem_t close_sem;
+  uv_sem_t async_sem;
+  uv_async_t async;
+  int events;
+  int fake_fd;
+  int int_fd;
+  int fd;
+  fd_set* sread;
+  size_t sread_sz;
+  fd_set* swrite;
+  size_t swrite_sz;
+};
+#endif /* defined(__APPLE__) */
+
+static void uv__stream_connect(uv_stream_t*);
+static void uv__write(uv_stream_t* stream);
+static void uv__read(uv_stream_t* stream);
+static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events);
+static void uv__write_callbacks(uv_stream_t* stream);
+static size_t uv__write_req_size(uv_write_t* req);
+
+
+void uv__stream_init(uv_loop_t* loop,
+                     uv_stream_t* stream,
+                     uv_handle_type type) {
+  int err;
+
+  uv__handle_init(loop, (uv_handle_t*)stream, type);
+  stream->read_cb = NULL;
+  stream->alloc_cb = NULL;
+  stream->close_cb = NULL;
+  stream->connection_cb = NULL;
+  stream->connect_req = NULL;
+  stream->shutdown_req = NULL;
+  stream->accepted_fd = -1;
+  stream->queued_fds = NULL;
+  stream->delayed_error = 0;
+  QUEUE_INIT(&stream->write_queue);
+  QUEUE_INIT(&stream->write_completed_queue);
+  stream->write_queue_size = 0;
+
+  if (loop->emfile_fd == -1) {
+    err = uv__open_cloexec("/dev/null", O_RDONLY);
+    if (err < 0)
+        /* In the rare case that "/dev/null" isn't mounted open "/"
+         * instead.
+         */
+        err = uv__open_cloexec("/", O_RDONLY);
+    if (err >= 0)
+      loop->emfile_fd = err;
+  }
+
+#if defined(__APPLE__)
+  stream->select = NULL;
+#endif /* defined(__APPLE_) */
+
+  uv__io_init(&stream->io_watcher, uv__stream_io, -1);
+}
+
+
+static void uv__stream_osx_interrupt_select(uv_stream_t* stream) {
+#if defined(__APPLE__)
+  /* Notify select() thread about state change */
+  uv__stream_select_t* s;
+  int r;
+
+  s = stream->select;
+  if (s == NULL)
+    return;
+
+  /* Interrupt select() loop
+   * NOTE: fake_fd and int_fd are socketpair(), thus writing to one will
+   * emit read event on other side
+   */
+  do
+    r = write(s->fake_fd, "x", 1);
+  while (r == -1 && errno == EINTR);
+
+  assert(r == 1);
+#else  /* !defined(__APPLE__) */
+  /* No-op on any other platform */
+#endif  /* !defined(__APPLE__) */
+}
+
+
+#if defined(__APPLE__)
+static void uv__stream_osx_select(void* arg) {
+  uv_stream_t* stream;
+  uv__stream_select_t* s;
+  char buf[1024];
+  int events;
+  int fd;
+  int r;
+  int max_fd;
+
+  stream = arg;
+  s = stream->select;
+  fd = s->fd;
+
+  if (fd > s->int_fd)
+    max_fd = fd;
+  else
+    max_fd = s->int_fd;
+
+  while (1) {
+    /* Terminate on semaphore */
+    if (uv_sem_trywait(&s->close_sem) == 0)
+      break;
+
+    /* Watch fd using select(2) */
+    memset(s->sread, 0, s->sread_sz);
+    memset(s->swrite, 0, s->swrite_sz);
+
+    if (uv__io_active(&stream->io_watcher, POLLIN))
+      FD_SET(fd, s->sread);
+    if (uv__io_active(&stream->io_watcher, POLLOUT))
+      FD_SET(fd, s->swrite);
+    FD_SET(s->int_fd, s->sread);
+
+    /* Wait indefinitely for fd events */
+    r = select(max_fd + 1, s->sread, s->swrite, NULL, NULL);
+    if (r == -1) {
+      if (errno == EINTR)
+        continue;
+
+      /* XXX: Possible?! */
+      abort();
+    }
+
+    /* Ignore timeouts */
+    if (r == 0)
+      continue;
+
+    /* Empty socketpair's buffer in case of interruption */
+    if (FD_ISSET(s->int_fd, s->sread))
+      while (1) {
+        r = read(s->int_fd, buf, sizeof(buf));
+
+        if (r == sizeof(buf))
+          continue;
+
+        if (r != -1)
+          break;
+
+        if (errno == EAGAIN || errno == EWOULDBLOCK)
+          break;
+
+        if (errno == EINTR)
+          continue;
+
+        abort();
+      }
+
+    /* Handle events */
+    events = 0;
+    if (FD_ISSET(fd, s->sread))
+      events |= POLLIN;
+    if (FD_ISSET(fd, s->swrite))
+      events |= POLLOUT;
+
+    assert(events != 0 || FD_ISSET(s->int_fd, s->sread));
+    if (events != 0) {
+      ACCESS_ONCE(int, s->events) = events;
+
+      uv_async_send(&s->async);
+      uv_sem_wait(&s->async_sem);
+
+      /* Should be processed at this stage */
+      assert((s->events == 0) || (stream->flags & UV_CLOSING));
+    }
+  }
+}
+
+
+static void uv__stream_osx_select_cb(uv_async_t* handle) {
+  uv__stream_select_t* s;
+  uv_stream_t* stream;
+  int events;
+
+  s = container_of(handle, uv__stream_select_t, async);
+  stream = s->stream;
+
+  /* Get and reset stream's events */
+  events = s->events;
+  ACCESS_ONCE(int, s->events) = 0;
+
+  assert(events != 0);
+  assert(events == (events & (POLLIN | POLLOUT)));
+
+  /* Invoke callback on event-loop */
+  if ((events & POLLIN) && uv__io_active(&stream->io_watcher, POLLIN))
+    uv__stream_io(stream->loop, &stream->io_watcher, POLLIN);
+
+  if ((events & POLLOUT) && uv__io_active(&stream->io_watcher, POLLOUT))
+    uv__stream_io(stream->loop, &stream->io_watcher, POLLOUT);
+
+  if (stream->flags & UV_CLOSING)
+    return;
+
+  /* NOTE: It is important to do it here, otherwise `select()` might be called
+   * before the actual `uv__read()`, leading to the blocking syscall
+   */
+  uv_sem_post(&s->async_sem);
+}
+
+
+static void uv__stream_osx_cb_close(uv_handle_t* async) {
+  uv__stream_select_t* s;
+
+  s = container_of(async, uv__stream_select_t, async);
+  uv__free(s);
+}
+
+
+int uv__stream_try_select(uv_stream_t* stream, int* fd) {
+  /*
+   * kqueue doesn't work with some files from /dev mount on osx.
+   * select(2) in separate thread for those fds
+   */
+
+  struct kevent filter[1];
+  struct kevent events[1];
+  struct timespec timeout;
+  uv__stream_select_t* s;
+  int fds[2];
+  int err;
+  int ret;
+  int kq;
+  int old_fd;
+  int max_fd;
+  size_t sread_sz;
+  size_t swrite_sz;
+
+  kq = kqueue();
+  if (kq == -1) {
+    perror("(libuv) kqueue()");
+    return -errno;
+  }
+
+  EV_SET(&filter[0], *fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0);
+
+  /* Use small timeout, because we only want to capture EINVALs */
+  timeout.tv_sec = 0;
+  timeout.tv_nsec = 1;
+
+  do
+    ret = kevent(kq, filter, 1, events, 1, &timeout);
+  while (ret == -1 && errno == EINTR);
+
+  uv__close(kq);
+
+  if (ret == -1)
+    return -errno;
+
+  if (ret == 0 || (events[0].flags & EV_ERROR) == 0 || events[0].data != EINVAL)
+    return 0;
+
+  /* At this point we definitely know that this fd won't work with kqueue */
+
+  /*
+   * Create fds for io watcher and to interrupt the select() loop.
+   * NOTE: do it ahead of malloc below to allocate enough space for fd_sets
+   */
+  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
+    return -errno;
+
+  max_fd = *fd;
+  if (fds[1] > max_fd)
+    max_fd = fds[1];
+
+  sread_sz = ROUND_UP(max_fd + 1, sizeof(uint32_t) * NBBY) / NBBY;
+  swrite_sz = sread_sz;
+
+  s = uv__malloc(sizeof(*s) + sread_sz + swrite_sz);
+  if (s == NULL) {
+    err = -ENOMEM;
+    goto failed_malloc;
+  }
+
+  s->events = 0;
+  s->fd = *fd;
+  s->sread = (fd_set*) ((char*) s + sizeof(*s));
+  s->sread_sz = sread_sz;
+  s->swrite = (fd_set*) ((char*) s->sread + sread_sz);
+  s->swrite_sz = swrite_sz;
+
+  err = uv_async_init(stream->loop, &s->async, uv__stream_osx_select_cb);
+  if (err)
+    goto failed_async_init;
+
+  s->async.flags |= UV__HANDLE_INTERNAL;
+  uv__handle_unref(&s->async);
+
+  err = uv_sem_init(&s->close_sem, 0);
+  if (err != 0)
+    goto failed_close_sem_init;
+
+  err = uv_sem_init(&s->async_sem, 0);
+  if (err != 0)
+    goto failed_async_sem_init;
+
+  s->fake_fd = fds[0];
+  s->int_fd = fds[1];
+
+  old_fd = *fd;
+  s->stream = stream;
+  stream->select = s;
+  *fd = s->fake_fd;
+
+  err = uv_thread_create(&s->thread, uv__stream_osx_select, stream);
+  if (err != 0)
+    goto failed_thread_create;
+
+  return 0;
+
+failed_thread_create:
+  s->stream = NULL;
+  stream->select = NULL;
+  *fd = old_fd;
+
+  uv_sem_destroy(&s->async_sem);
+
+failed_async_sem_init:
+  uv_sem_destroy(&s->close_sem);
+
+failed_close_sem_init:
+  uv__close(fds[0]);
+  uv__close(fds[1]);
+  uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);
+  return err;
+
+failed_async_init:
+  uv__free(s);
+
+failed_malloc:
+  uv__close(fds[0]);
+  uv__close(fds[1]);
+
+  return err;
+}
+#endif /* defined(__APPLE__) */
+
+
+int uv__stream_open(uv_stream_t* stream, int fd, int flags) {
+#if defined(__APPLE__)
+  int enable;
+#endif
+
+  if (!(stream->io_watcher.fd == -1 || stream->io_watcher.fd == fd))
+    return -EBUSY;
+
+  assert(fd >= 0);
+  stream->flags |= flags;
+
+  if (stream->type == UV_TCP) {
+    if ((stream->flags & UV_TCP_NODELAY) && uv__tcp_nodelay(fd, 1))
+      return -errno;
+
+    /* TODO Use delay the user passed in. */
+    if ((stream->flags & UV_TCP_KEEPALIVE) && uv__tcp_keepalive(fd, 1, 60))
+      return -errno;
+  }
+
+#if defined(__APPLE__)
+  enable = 1;
+  if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &enable, sizeof(enable)) &&
+      errno != ENOTSOCK &&
+      errno != EINVAL) {
+    return -errno;
+  }
+#endif
+
+  stream->io_watcher.fd = fd;
+
+  return 0;
+}
+
+
+void uv__stream_flush_write_queue(uv_stream_t* stream, int error) {
+  uv_write_t* req;
+  QUEUE* q;
+  while (!QUEUE_EMPTY(&stream->write_queue)) {
+    q = QUEUE_HEAD(&stream->write_queue);
+    QUEUE_REMOVE(q);
+
+    req = QUEUE_DATA(q, uv_write_t, queue);
+    req->error = error;
+
+    QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
+  }
+}
+
+
+void uv__stream_destroy(uv_stream_t* stream) {
+  assert(!uv__io_active(&stream->io_watcher, POLLIN | POLLOUT));
+  assert(stream->flags & UV_CLOSED);
+
+  if (stream->connect_req) {
+    uv__req_unregister(stream->loop, stream->connect_req);
+    stream->connect_req->cb(stream->connect_req, -ECANCELED);
+    stream->connect_req = NULL;
+  }
+
+  uv__stream_flush_write_queue(stream, -ECANCELED);
+  uv__write_callbacks(stream);
+
+  if (stream->shutdown_req) {
+    /* The ECANCELED error code is a lie, the shutdown(2) syscall is a
+     * fait accompli at this point. Maybe we should revisit this in v0.11.
+     * A possible reason for leaving it unchanged is that it informs the
+     * callee that the handle has been destroyed.
+     */
+    uv__req_unregister(stream->loop, stream->shutdown_req);
+    stream->shutdown_req->cb(stream->shutdown_req, -ECANCELED);
+    stream->shutdown_req = NULL;
+  }
+
+  assert(stream->write_queue_size == 0);
+}
+
+
+/* Implements a best effort approach to mitigating accept() EMFILE errors.
+ * We have a spare file descriptor stashed away that we close to get below
+ * the EMFILE limit. Next, we accept all pending connections and close them
+ * immediately to signal the clients that we're overloaded - and we are, but
+ * we still keep on trucking.
+ *
+ * There is one caveat: it's not reliable in a multi-threaded environment.
+ * The file descriptor limit is per process. Our party trick fails if another
+ * thread opens a file or creates a socket in the time window between us
+ * calling close() and accept().
+ */
+static int uv__emfile_trick(uv_loop_t* loop, int accept_fd) {
+  int err;
+  int emfile_fd;
+
+  if (loop->emfile_fd == -1)
+    return -EMFILE;
+
+  uv__close(loop->emfile_fd);
+  loop->emfile_fd = -1;
+
+  do {
+    err = uv__accept(accept_fd);
+    if (err >= 0)
+      uv__close(err);
+  } while (err >= 0 || err == -EINTR);
+
+  emfile_fd = uv__open_cloexec("/", O_RDONLY);
+  if (emfile_fd >= 0)
+    loop->emfile_fd = emfile_fd;
+
+  return err;
+}
+
+
+#if defined(UV_HAVE_KQUEUE)
+# define UV_DEC_BACKLOG(w) w->rcount--;
+#else
+# define UV_DEC_BACKLOG(w) /* no-op */
+#endif /* defined(UV_HAVE_KQUEUE) */
+
+
+void uv__server_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  uv_stream_t* stream;
+  int err;
+
+  stream = container_of(w, uv_stream_t, io_watcher);
+  assert(events == POLLIN);
+  assert(stream->accepted_fd == -1);
+  assert(!(stream->flags & UV_CLOSING));
+
+  uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
+
+  /* connection_cb can close the server socket while we're
+   * in the loop so check it on each iteration.
+   */
+  while (uv__stream_fd(stream) != -1) {
+    assert(stream->accepted_fd == -1);
+
+#if defined(UV_HAVE_KQUEUE)
+    if (w->rcount <= 0)
+      return;
+#endif /* defined(UV_HAVE_KQUEUE) */
+
+    err = uv__accept(uv__stream_fd(stream));
+    if (err < 0) {
+      if (err == -EAGAIN || err == -EWOULDBLOCK)
+        return;  /* Not an error. */
+
+      if (err == -ECONNABORTED)
+        continue;  /* Ignore. Nothing we can do about that. */
+
+      if (err == -EMFILE || err == -ENFILE) {
+        err = uv__emfile_trick(loop, uv__stream_fd(stream));
+        if (err == -EAGAIN || err == -EWOULDBLOCK)
+          break;
+      }
+
+      stream->connection_cb(stream, err);
+      continue;
+    }
+
+    UV_DEC_BACKLOG(w)
+    stream->accepted_fd = err;
+    stream->connection_cb(stream, 0);
+
+    if (stream->accepted_fd != -1) {
+      /* The user hasn't yet accepted called uv_accept() */
+      uv__io_stop(loop, &stream->io_watcher, POLLIN);
+      return;
+    }
+
+    if (stream->type == UV_TCP && (stream->flags & UV_TCP_SINGLE_ACCEPT)) {
+      /* Give other processes a chance to accept connections. */
+      struct timespec timeout = { 0, 1 };
+      nanosleep(&timeout, NULL);
+    }
+  }
+}
+
+
+#undef UV_DEC_BACKLOG
+
+
+int uv_accept(uv_stream_t* server, uv_stream_t* client) {
+  int err;
+
+  assert(server->loop == client->loop);
+
+  if (server->accepted_fd == -1)
+    return -EAGAIN;
+
+  switch (client->type) {
+    case UV_NAMED_PIPE:
+    case UV_TCP:
+      err = uv__stream_open(client,
+                            server->accepted_fd,
+                            UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+      if (err) {
+        /* TODO handle error */
+        uv__close(server->accepted_fd);
+        goto done;
+      }
+      break;
+
+    case UV_UDP:
+      err = uv_udp_open((uv_udp_t*) client, server->accepted_fd);
+      if (err) {
+        uv__close(server->accepted_fd);
+        goto done;
+      }
+      break;
+
+    default:
+      return -EINVAL;
+  }
+
+  client->flags |= UV_HANDLE_BOUND;
+
+done:
+  /* Process queued fds */
+  if (server->queued_fds != NULL) {
+    uv__stream_queued_fds_t* queued_fds;
+
+    queued_fds = server->queued_fds;
+
+    /* Read first */
+    server->accepted_fd = queued_fds->fds[0];
+
+    /* All read, free */
+    assert(queued_fds->offset > 0);
+    if (--queued_fds->offset == 0) {
+      uv__free(queued_fds);
+      server->queued_fds = NULL;
+    } else {
+      /* Shift rest */
+      memmove(queued_fds->fds,
+              queued_fds->fds + 1,
+              queued_fds->offset * sizeof(*queued_fds->fds));
+    }
+  } else {
+    server->accepted_fd = -1;
+    if (err == 0)
+      uv__io_start(server->loop, &server->io_watcher, POLLIN);
+  }
+  return err;
+}
+
+
+int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) {
+  int err;
+
+  switch (stream->type) {
+  case UV_TCP:
+    err = uv_tcp_listen((uv_tcp_t*)stream, backlog, cb);
+    break;
+
+  case UV_NAMED_PIPE:
+    err = uv_pipe_listen((uv_pipe_t*)stream, backlog, cb);
+    break;
+
+  default:
+    err = -EINVAL;
+  }
+
+  if (err == 0)
+    uv__handle_start(stream);
+
+  return err;
+}
+
+
+static void uv__drain(uv_stream_t* stream) {
+  uv_shutdown_t* req;
+  int err;
+
+  assert(QUEUE_EMPTY(&stream->write_queue));
+  uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
+  uv__stream_osx_interrupt_select(stream);
+
+  /* Shutdown? */
+  if ((stream->flags & UV_STREAM_SHUTTING) &&
+      !(stream->flags & UV_CLOSING) &&
+      !(stream->flags & UV_STREAM_SHUT)) {
+    assert(stream->shutdown_req);
+
+    req = stream->shutdown_req;
+    stream->shutdown_req = NULL;
+    stream->flags &= ~UV_STREAM_SHUTTING;
+    uv__req_unregister(stream->loop, req);
+
+    err = 0;
+    if (shutdown(uv__stream_fd(stream), SHUT_WR))
+      err = -errno;
+
+    if (err == 0)
+      stream->flags |= UV_STREAM_SHUT;
+
+    if (req->cb != NULL)
+      req->cb(req, err);
+  }
+}
+
+
+static size_t uv__write_req_size(uv_write_t* req) {
+  size_t size;
+
+  assert(req->bufs != NULL);
+  size = uv__count_bufs(req->bufs + req->write_index,
+                        req->nbufs - req->write_index);
+  assert(req->handle->write_queue_size >= size);
+
+  return size;
+}
+
+
+static void uv__write_req_finish(uv_write_t* req) {
+  uv_stream_t* stream = req->handle;
+
+  /* Pop the req off tcp->write_queue. */
+  QUEUE_REMOVE(&req->queue);
+
+  /* Only free when there was no error. On error, we touch up write_queue_size
+   * right before making the callback. The reason we don't do that right away
+   * is that a write_queue_size > 0 is our only way to signal to the user that
+   * they should stop writing - which they should if we got an error. Something
+   * to revisit in future revisions of the libuv API.
+   */
+  if (req->error == 0) {
+    if (req->bufs != req->bufsml)
+      uv__free(req->bufs);
+    req->bufs = NULL;
+  }
+
+  /* Add it to the write_completed_queue where it will have its
+   * callback called in the near future.
+   */
+  QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
+  uv__io_feed(stream->loop, &stream->io_watcher);
+}
+
+
+static int uv__handle_fd(uv_handle_t* handle) {
+  switch (handle->type) {
+    case UV_NAMED_PIPE:
+    case UV_TCP:
+      return ((uv_stream_t*) handle)->io_watcher.fd;
+
+    case UV_UDP:
+      return ((uv_udp_t*) handle)->io_watcher.fd;
+
+    default:
+      return -1;
+  }
+}
+
+static void uv__write(uv_stream_t* stream) {
+  struct iovec* iov;
+  QUEUE* q;
+  uv_write_t* req;
+  int iovmax;
+  int iovcnt;
+  ssize_t n;
+
+start:
+
+  assert(uv__stream_fd(stream) >= 0);
+
+  if (QUEUE_EMPTY(&stream->write_queue))
+    return;
+
+  q = QUEUE_HEAD(&stream->write_queue);
+  req = QUEUE_DATA(q, uv_write_t, queue);
+  assert(req->handle == stream);
+
+  /*
+   * Cast to iovec. We had to have our own uv_buf_t instead of iovec
+   * because Windows's WSABUF is not an iovec.
+   */
+  assert(sizeof(uv_buf_t) == sizeof(struct iovec));
+  iov = (struct iovec*) &(req->bufs[req->write_index]);
+  iovcnt = req->nbufs - req->write_index;
+
+  iovmax = uv__getiovmax();
+
+  /* Limit iov count to avoid EINVALs from writev() */
+  if (iovcnt > iovmax)
+    iovcnt = iovmax;
+
+  /*
+   * Now do the actual writev. Note that we've been updating the pointers
+   * inside the iov each time we write. So there is no need to offset it.
+   */
+
+  if (req->send_handle) {
+    struct msghdr msg;
+    struct cmsghdr *cmsg;
+    int fd_to_send = uv__handle_fd((uv_handle_t*) req->send_handle);
+    char scratch[64] = {0};
+
+    assert(fd_to_send >= 0);
+
+    msg.msg_name = NULL;
+    msg.msg_namelen = 0;
+    msg.msg_iov = iov;
+    msg.msg_iovlen = iovcnt;
+    msg.msg_flags = 0;
+
+    msg.msg_control = (void*) scratch;
+    msg.msg_controllen = CMSG_SPACE(sizeof(fd_to_send));
+
+    cmsg = CMSG_FIRSTHDR(&msg);
+    cmsg->cmsg_level = SOL_SOCKET;
+    cmsg->cmsg_type = SCM_RIGHTS;
+    cmsg->cmsg_len = CMSG_LEN(sizeof(fd_to_send));
+
+    /* silence aliasing warning */
+    {
+      void* pv = CMSG_DATA(cmsg);
+      int* pi = pv;
+      *pi = fd_to_send;
+    }
+
+    do {
+      n = sendmsg(uv__stream_fd(stream), &msg, 0);
+    }
+#if defined(__APPLE__)
+    /*
+     * Due to a possible kernel bug at least in OS X 10.10 "Yosemite",
+     * EPROTOTYPE can be returned while trying to write to a socket that is
+     * shutting down. If we retry the write, we should get the expected EPIPE
+     * instead.
+     */
+    while (n == -1 && (errno == EINTR || errno == EPROTOTYPE));
+#else
+    while (n == -1 && errno == EINTR);
+#endif
+  } else {
+    do {
+      if (iovcnt == 1) {
+        n = write(uv__stream_fd(stream), iov[0].iov_base, iov[0].iov_len);
+      } else {
+        n = writev(uv__stream_fd(stream), iov, iovcnt);
+      }
+    }
+#if defined(__APPLE__)
+    /*
+     * Due to a possible kernel bug at least in OS X 10.10 "Yosemite",
+     * EPROTOTYPE can be returned while trying to write to a socket that is
+     * shutting down. If we retry the write, we should get the expected EPIPE
+     * instead.
+     */
+    while (n == -1 && (errno == EINTR || errno == EPROTOTYPE));
+#else
+    while (n == -1 && errno == EINTR);
+#endif
+  }
+
+  if (n < 0) {
+    if (errno != EAGAIN && errno != EWOULDBLOCK) {
+      /* Error */
+      req->error = -errno;
+      uv__write_req_finish(req);
+      uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
+      if (!uv__io_active(&stream->io_watcher, POLLIN))
+        uv__handle_stop(stream);
+      uv__stream_osx_interrupt_select(stream);
+      return;
+    } else if (stream->flags & UV_STREAM_BLOCKING) {
+      /* If this is a blocking stream, try again. */
+      goto start;
+    }
+  } else {
+    /* Successful write */
+
+    while (n >= 0) {
+      uv_buf_t* buf = &(req->bufs[req->write_index]);
+      size_t len = buf->len;
+
+      assert(req->write_index < req->nbufs);
+
+      if ((size_t)n < len) {
+        buf->base += n;
+        buf->len -= n;
+        stream->write_queue_size -= n;
+        n = 0;
+
+        /* There is more to write. */
+        if (stream->flags & UV_STREAM_BLOCKING) {
+          /*
+           * If we're blocking then we should not be enabling the write
+           * watcher - instead we need to try again.
+           */
+          goto start;
+        } else {
+          /* Break loop and ensure the watcher is pending. */
+          break;
+        }
+
+      } else {
+        /* Finished writing the buf at index req->write_index. */
+        req->write_index++;
+
+        assert((size_t)n >= len);
+        n -= len;
+
+        assert(stream->write_queue_size >= len);
+        stream->write_queue_size -= len;
+
+        if (req->write_index == req->nbufs) {
+          /* Then we're done! */
+          assert(n == 0);
+          uv__write_req_finish(req);
+          /* TODO: start trying to write the next request. */
+          return;
+        }
+      }
+    }
+  }
+
+  /* Either we've counted n down to zero or we've got EAGAIN. */
+  assert(n == 0 || n == -1);
+
+  /* Only non-blocking streams should use the write_watcher. */
+  assert(!(stream->flags & UV_STREAM_BLOCKING));
+
+  /* We're not done. */
+  uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
+
+  /* Notify select() thread about state change */
+  uv__stream_osx_interrupt_select(stream);
+}
+
+
+static void uv__write_callbacks(uv_stream_t* stream) {
+  uv_write_t* req;
+  QUEUE* q;
+
+  while (!QUEUE_EMPTY(&stream->write_completed_queue)) {
+    /* Pop a req off write_completed_queue. */
+    q = QUEUE_HEAD(&stream->write_completed_queue);
+    req = QUEUE_DATA(q, uv_write_t, queue);
+    QUEUE_REMOVE(q);
+    uv__req_unregister(stream->loop, req);
+
+    if (req->bufs != NULL) {
+      stream->write_queue_size -= uv__write_req_size(req);
+      if (req->bufs != req->bufsml)
+        uv__free(req->bufs);
+      req->bufs = NULL;
+    }
+
+    /* NOTE: call callback AFTER freeing the request data. */
+    if (req->cb)
+      req->cb(req, req->error);
+  }
+
+  assert(QUEUE_EMPTY(&stream->write_completed_queue));
+}
+
+
+uv_handle_type uv__handle_type(int fd) {
+  struct sockaddr_storage ss;
+  socklen_t sslen;
+  socklen_t len;
+  int type;
+
+  memset(&ss, 0, sizeof(ss));
+  sslen = sizeof(ss);
+
+  if (getsockname(fd, (struct sockaddr*)&ss, &sslen))
+    return UV_UNKNOWN_HANDLE;
+
+  len = sizeof type;
+
+  if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &len))
+    return UV_UNKNOWN_HANDLE;
+
+  if (type == SOCK_STREAM) {
+#if defined(_AIX) || defined(__DragonFly__)
+    /* on AIX/DragonFly the getsockname call returns an empty sa structure
+     * for sockets of type AF_UNIX.  For all other types it will
+     * return a properly filled in structure.
+     */
+    if (sslen == 0)
+      return UV_NAMED_PIPE;
+#endif
+    switch (ss.ss_family) {
+      case AF_UNIX:
+        return UV_NAMED_PIPE;
+      case AF_INET:
+      case AF_INET6:
+        return UV_TCP;
+      }
+  }
+
+  if (type == SOCK_DGRAM &&
+      (ss.ss_family == AF_INET || ss.ss_family == AF_INET6))
+    return UV_UDP;
+
+  return UV_UNKNOWN_HANDLE;
+}
+
+
+static void uv__stream_eof(uv_stream_t* stream, const uv_buf_t* buf) {
+  stream->flags |= UV_STREAM_READ_EOF;
+  uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
+  if (!uv__io_active(&stream->io_watcher, POLLOUT))
+    uv__handle_stop(stream);
+  uv__stream_osx_interrupt_select(stream);
+  stream->read_cb(stream, UV_EOF, buf);
+  stream->flags &= ~UV_STREAM_READING;
+}
+
+
+static int uv__stream_queue_fd(uv_stream_t* stream, int fd) {
+  uv__stream_queued_fds_t* queued_fds;
+  unsigned int queue_size;
+
+  queued_fds = stream->queued_fds;
+  if (queued_fds == NULL) {
+    queue_size = 8;
+    queued_fds = uv__malloc((queue_size - 1) * sizeof(*queued_fds->fds) +
+                            sizeof(*queued_fds));
+    if (queued_fds == NULL)
+      return -ENOMEM;
+    queued_fds->size = queue_size;
+    queued_fds->offset = 0;
+    stream->queued_fds = queued_fds;
+
+    /* Grow */
+  } else if (queued_fds->size == queued_fds->offset) {
+    queue_size = queued_fds->size + 8;
+    queued_fds = uv__realloc(queued_fds,
+                             (queue_size - 1) * sizeof(*queued_fds->fds) +
+                              sizeof(*queued_fds));
+
+    /*
+     * Allocation failure, report back.
+     * NOTE: if it is fatal - sockets will be closed in uv__stream_close
+     */
+    if (queued_fds == NULL)
+      return -ENOMEM;
+    queued_fds->size = queue_size;
+    stream->queued_fds = queued_fds;
+  }
+
+  /* Put fd in a queue */
+  queued_fds->fds[queued_fds->offset++] = fd;
+
+  return 0;
+}
+
+
+#define UV__CMSG_FD_COUNT 64
+#define UV__CMSG_FD_SIZE (UV__CMSG_FD_COUNT * sizeof(int))
+
+
+static int uv__stream_recv_cmsg(uv_stream_t* stream, struct msghdr* msg) {
+  struct cmsghdr* cmsg;
+
+  for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) {
+    char* start;
+    char* end;
+    int err;
+    void* pv;
+    int* pi;
+    unsigned int i;
+    unsigned int count;
+
+    if (cmsg->cmsg_type != SCM_RIGHTS) {
+      fprintf(stderr, "ignoring non-SCM_RIGHTS ancillary data: %d\n",
+          cmsg->cmsg_type);
+      continue;
+    }
+
+    /* silence aliasing warning */
+    pv = CMSG_DATA(cmsg);
+    pi = pv;
+
+    /* Count available fds */
+    start = (char*) cmsg;
+    end = (char*) cmsg + cmsg->cmsg_len;
+    count = 0;
+    while (start + CMSG_LEN(count * sizeof(*pi)) < end)
+      count++;
+    assert(start + CMSG_LEN(count * sizeof(*pi)) == end);
+
+    for (i = 0; i < count; i++) {
+      /* Already has accepted fd, queue now */
+      if (stream->accepted_fd != -1) {
+        err = uv__stream_queue_fd(stream, pi[i]);
+        if (err != 0) {
+          /* Close rest */
+          for (; i < count; i++)
+            uv__close(pi[i]);
+          return err;
+        }
+      } else {
+        stream->accepted_fd = pi[i];
+      }
+    }
+  }
+
+  return 0;
+}
+
+
+#ifdef __clang__
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wgnu-folding-constant"
+#endif
+
+static void uv__read(uv_stream_t* stream) {
+  uv_buf_t buf;
+  ssize_t nread;
+  struct msghdr msg;
+  char cmsg_space[CMSG_SPACE(UV__CMSG_FD_SIZE)];
+  int count;
+  int err;
+  int is_ipc;
+
+  stream->flags &= ~UV_STREAM_READ_PARTIAL;
+
+  /* Prevent loop starvation when the data comes in as fast as (or faster than)
+   * we can read it. XXX Need to rearm fd if we switch to edge-triggered I/O.
+   */
+  count = 32;
+
+  is_ipc = stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) stream)->ipc;
+
+  /* XXX: Maybe instead of having UV_STREAM_READING we just test if
+   * tcp->read_cb is NULL or not?
+   */
+  while (stream->read_cb
+      && (stream->flags & UV_STREAM_READING)
+      && (count-- > 0)) {
+    assert(stream->alloc_cb != NULL);
+
+    buf = uv_buf_init(NULL, 0);
+    stream->alloc_cb((uv_handle_t*)stream, 64 * 1024, &buf);
+    if (buf.base == NULL || buf.len == 0) {
+      /* User indicates it can't or won't handle the read. */
+      stream->read_cb(stream, UV_ENOBUFS, &buf);
+      return;
+    }
+
+    assert(buf.base != NULL);
+    assert(uv__stream_fd(stream) >= 0);
+
+    if (!is_ipc) {
+      do {
+        nread = read(uv__stream_fd(stream), buf.base, buf.len);
+      }
+      while (nread < 0 && errno == EINTR);
+    } else {
+      /* ipc uses recvmsg */
+      msg.msg_flags = 0;
+      msg.msg_iov = (struct iovec*) &buf;
+      msg.msg_iovlen = 1;
+      msg.msg_name = NULL;
+      msg.msg_namelen = 0;
+      /* Set up to receive a descriptor even if one isn't in the message */
+      msg.msg_controllen = sizeof(cmsg_space);
+      msg.msg_control = cmsg_space;
+
+      do {
+        nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0);
+      }
+      while (nread < 0 && errno == EINTR);
+    }
+
+    if (nread < 0) {
+      /* Error */
+      if (errno == EAGAIN || errno == EWOULDBLOCK) {
+        /* Wait for the next one. */
+        if (stream->flags & UV_STREAM_READING) {
+          uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
+          uv__stream_osx_interrupt_select(stream);
+        }
+        stream->read_cb(stream, 0, &buf);
+      } else {
+        /* Error. User should call uv_close(). */
+        stream->read_cb(stream, -errno, &buf);
+        if (stream->flags & UV_STREAM_READING) {
+          stream->flags &= ~UV_STREAM_READING;
+          uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
+          if (!uv__io_active(&stream->io_watcher, POLLOUT))
+            uv__handle_stop(stream);
+          uv__stream_osx_interrupt_select(stream);
+        }
+      }
+      return;
+    } else if (nread == 0) {
+      uv__stream_eof(stream, &buf);
+      return;
+    } else {
+      /* Successful read */
+      ssize_t buflen = buf.len;
+
+      if (is_ipc) {
+        err = uv__stream_recv_cmsg(stream, &msg);
+        if (err != 0) {
+          stream->read_cb(stream, err, &buf);
+          return;
+        }
+      }
+      stream->read_cb(stream, nread, &buf);
+
+      /* Return if we didn't fill the buffer, there is no more data to read. */
+      if (nread < buflen) {
+        stream->flags |= UV_STREAM_READ_PARTIAL;
+        return;
+      }
+    }
+  }
+}
+
+
+#ifdef __clang__
+# pragma clang diagnostic pop
+#endif
+
+#undef UV__CMSG_FD_COUNT
+#undef UV__CMSG_FD_SIZE
+
+
+int uv_shutdown(uv_shutdown_t* req, uv_stream_t* stream, uv_shutdown_cb cb) {
+  assert((stream->type == UV_TCP || stream->type == UV_NAMED_PIPE) &&
+         "uv_shutdown (unix) only supports uv_handle_t right now");
+
+  if (!(stream->flags & UV_STREAM_WRITABLE) ||
+      stream->flags & UV_STREAM_SHUT ||
+      stream->flags & UV_STREAM_SHUTTING ||
+      stream->flags & UV_CLOSED ||
+      stream->flags & UV_CLOSING) {
+    return -ENOTCONN;
+  }
+
+  assert(uv__stream_fd(stream) >= 0);
+
+  /* Initialize request */
+  uv__req_init(stream->loop, req, UV_SHUTDOWN);
+  req->handle = stream;
+  req->cb = cb;
+  stream->shutdown_req = req;
+  stream->flags |= UV_STREAM_SHUTTING;
+
+  uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
+  uv__stream_osx_interrupt_select(stream);
+
+  return 0;
+}
+
+
+static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+  uv_stream_t* stream;
+
+  stream = container_of(w, uv_stream_t, io_watcher);
+
+  assert(stream->type == UV_TCP ||
+         stream->type == UV_NAMED_PIPE ||
+         stream->type == UV_TTY);
+  assert(!(stream->flags & UV_CLOSING));
+
+  if (stream->connect_req) {
+    uv__stream_connect(stream);
+    return;
+  }
+
+  assert(uv__stream_fd(stream) >= 0);
+
+  /* Ignore POLLHUP here. Even it it's set, there may still be data to read. */
+  if (events & (POLLIN | POLLERR | POLLHUP))
+    uv__read(stream);
+
+  if (uv__stream_fd(stream) == -1)
+    return;  /* read_cb closed stream. */
+
+  /* Short-circuit iff POLLHUP is set, the user is still interested in read
+   * events and uv__read() reported a partial read but not EOF. If the EOF
+   * flag is set, uv__read() called read_cb with err=UV_EOF and we don't
+   * have to do anything. If the partial read flag is not set, we can't
+   * report the EOF yet because there is still data to read.
+   */
+  if ((events & POLLHUP) &&
+      (stream->flags & UV_STREAM_READING) &&
+      (stream->flags & UV_STREAM_READ_PARTIAL) &&
+      !(stream->flags & UV_STREAM_READ_EOF)) {
+    uv_buf_t buf = { NULL, 0 };
+    uv__stream_eof(stream, &buf);
+  }
+
+  if (uv__stream_fd(stream) == -1)
+    return;  /* read_cb closed stream. */
+
+  if (events & (POLLOUT | POLLERR | POLLHUP)) {
+    uv__write(stream);
+    uv__write_callbacks(stream);
+
+    /* Write queue drained. */
+    if (QUEUE_EMPTY(&stream->write_queue))
+      uv__drain(stream);
+  }
+}
+
+
+/**
+ * We get called here from directly following a call to connect(2).
+ * In order to determine if we've errored out or succeeded must call
+ * getsockopt.
+ */
+static void uv__stream_connect(uv_stream_t* stream) {
+  int error;
+  uv_connect_t* req = stream->connect_req;
+  socklen_t errorsize = sizeof(int);
+
+  assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE);
+  assert(req);
+
+  if (stream->delayed_error) {
+    /* To smooth over the differences between unixes errors that
+     * were reported synchronously on the first connect can be delayed
+     * until the next tick--which is now.
+     */
+    error = stream->delayed_error;
+    stream->delayed_error = 0;
+  } else {
+    /* Normal situation: we need to get the socket error from the kernel. */
+    assert(uv__stream_fd(stream) >= 0);
+    getsockopt(uv__stream_fd(stream),
+               SOL_SOCKET,
+               SO_ERROR,
+               &error,
+               &errorsize);
+    error = -error;
+  }
+
+  if (error == -EINPROGRESS)
+    return;
+
+  stream->connect_req = NULL;
+  uv__req_unregister(stream->loop, req);
+
+  if (error < 0 || QUEUE_EMPTY(&stream->write_queue)) {
+    uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
+  }
+
+  if (req->cb)
+    req->cb(req, error);
+
+  if (uv__stream_fd(stream) == -1)
+    return;
+
+  if (error < 0) {
+    uv__stream_flush_write_queue(stream, -ECANCELED);
+    uv__write_callbacks(stream);
+  }
+}
+
+
+int uv_write2(uv_write_t* req,
+              uv_stream_t* stream,
+              const uv_buf_t bufs[],
+              unsigned int nbufs,
+              uv_stream_t* send_handle,
+              uv_write_cb cb) {
+  int empty_queue;
+
+  assert(nbufs > 0);
+  assert((stream->type == UV_TCP ||
+          stream->type == UV_NAMED_PIPE ||
+          stream->type == UV_TTY) &&
+         "uv_write (unix) does not yet support other types of streams");
+
+  if (uv__stream_fd(stream) < 0)
+    return -EBADF;
+
+  if (send_handle) {
+    if (stream->type != UV_NAMED_PIPE || !((uv_pipe_t*)stream)->ipc)
+      return -EINVAL;
+
+    /* XXX We abuse uv_write2() to send over UDP handles to child processes.
+     * Don't call uv__stream_fd() on those handles, it's a macro that on OS X
+     * evaluates to a function that operates on a uv_stream_t with a couple of
+     * OS X specific fields. On other Unices it does (handle)->io_watcher.fd,
+     * which works but only by accident.
+     */
+    if (uv__handle_fd((uv_handle_t*) send_handle) < 0)
+      return -EBADF;
+  }
+
+  /* It's legal for write_queue_size > 0 even when the write_queue is empty;
+   * it means there are error-state requests in the write_completed_queue that
+   * will touch up write_queue_size later, see also uv__write_req_finish().
+   * We could check that write_queue is empty instead but that implies making
+   * a write() syscall when we know that the handle is in error mode.
+   */
+  empty_queue = (stream->write_queue_size == 0);
+
+  /* Initialize the req */
+  uv__req_init(stream->loop, req, UV_WRITE);
+  req->cb = cb;
+  req->handle = stream;
+  req->error = 0;
+  req->send_handle = send_handle;
+  QUEUE_INIT(&req->queue);
+
+  req->bufs = req->bufsml;
+  if (nbufs > ARRAY_SIZE(req->bufsml))
+    req->bufs = uv__malloc(nbufs * sizeof(bufs[0]));
+
+  if (req->bufs == NULL)
+    return -ENOMEM;
+
+  memcpy(req->bufs, bufs, nbufs * sizeof(bufs[0]));
+  req->nbufs = nbufs;
+  req->write_index = 0;
+  stream->write_queue_size += uv__count_bufs(bufs, nbufs);
+
+  /* Append the request to write_queue. */
+  QUEUE_INSERT_TAIL(&stream->write_queue, &req->queue);
+
+  /* If the queue was empty when this function began, we should attempt to
+   * do the write immediately. Otherwise start the write_watcher and wait
+   * for the fd to become writable.
+   */
+  if (stream->connect_req) {
+    /* Still connecting, do nothing. */
+  }
+  else if (empty_queue) {
+    uv__write(stream);
+  }
+  else {
+    /*
+     * blocking streams should never have anything in the queue.
+     * if this assert fires then somehow the blocking stream isn't being
+     * sufficiently flushed in uv__write.
+     */
+    assert(!(stream->flags & UV_STREAM_BLOCKING));
+    uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
+    uv__stream_osx_interrupt_select(stream);
+  }
+
+  return 0;
+}
+
+
+/* The buffers to be written must remain valid until the callback is called.
+ * This is not required for the uv_buf_t array.
+ */
+int uv_write(uv_write_t* req,
+             uv_stream_t* handle,
+             const uv_buf_t bufs[],
+             unsigned int nbufs,
+             uv_write_cb cb) {
+  return uv_write2(req, handle, bufs, nbufs, NULL, cb);
+}
+
+
+void uv_try_write_cb(uv_write_t* req, int status) {
+  /* Should not be called */
+  abort();
+}
+
+
+int uv_try_write(uv_stream_t* stream,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs) {
+  int r;
+  int has_pollout;
+  size_t written;
+  size_t req_size;
+  uv_write_t req;
+
+  /* Connecting or already writing some data */
+  if (stream->connect_req != NULL || stream->write_queue_size != 0)
+    return -EAGAIN;
+
+  has_pollout = uv__io_active(&stream->io_watcher, POLLOUT);
+
+  r = uv_write(&req, stream, bufs, nbufs, uv_try_write_cb);
+  if (r != 0)
+    return r;
+
+  /* Remove not written bytes from write queue size */
+  written = uv__count_bufs(bufs, nbufs);
+  if (req.bufs != NULL)
+    req_size = uv__write_req_size(&req);
+  else
+    req_size = 0;
+  written -= req_size;
+  stream->write_queue_size -= req_size;
+
+  /* Unqueue request, regardless of immediateness */
+  QUEUE_REMOVE(&req.queue);
+  uv__req_unregister(stream->loop, &req);
+  if (req.bufs != req.bufsml)
+    uv__free(req.bufs);
+  req.bufs = NULL;
+
+  /* Do not poll for writable, if we wasn't before calling this */
+  if (!has_pollout) {
+    uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
+    uv__stream_osx_interrupt_select(stream);
+  }
+
+  if (written == 0 && req_size != 0)
+    return -EAGAIN;
+  else
+    return written;
+}
+
+
+int uv_read_start(uv_stream_t* stream,
+                  uv_alloc_cb alloc_cb,
+                  uv_read_cb read_cb) {
+  assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE ||
+      stream->type == UV_TTY);
+
+  if (stream->flags & UV_CLOSING)
+    return -EINVAL;
+
+  /* The UV_STREAM_READING flag is irrelevant of the state of the tcp - it just
+   * expresses the desired state of the user.
+   */
+  stream->flags |= UV_STREAM_READING;
+
+  /* TODO: try to do the read inline? */
+  /* TODO: keep track of tcp state. If we've gotten a EOF then we should
+   * not start the IO watcher.
+   */
+  assert(uv__stream_fd(stream) >= 0);
+  assert(alloc_cb);
+
+  stream->read_cb = read_cb;
+  stream->alloc_cb = alloc_cb;
+
+  uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
+  uv__handle_start(stream);
+  uv__stream_osx_interrupt_select(stream);
+
+  return 0;
+}
+
+
+int uv_read_stop(uv_stream_t* stream) {
+  if (!(stream->flags & UV_STREAM_READING))
+    return 0;
+
+  stream->flags &= ~UV_STREAM_READING;
+  uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
+  if (!uv__io_active(&stream->io_watcher, POLLOUT))
+    uv__handle_stop(stream);
+  uv__stream_osx_interrupt_select(stream);
+
+  stream->read_cb = NULL;
+  stream->alloc_cb = NULL;
+  return 0;
+}
+
+
+int uv_is_readable(const uv_stream_t* stream) {
+  return !!(stream->flags & UV_STREAM_READABLE);
+}
+
+
+int uv_is_writable(const uv_stream_t* stream) {
+  return !!(stream->flags & UV_STREAM_WRITABLE);
+}
+
+
+#if defined(__APPLE__)
+int uv___stream_fd(const uv_stream_t* handle) {
+  const uv__stream_select_t* s;
+
+  assert(handle->type == UV_TCP ||
+         handle->type == UV_TTY ||
+         handle->type == UV_NAMED_PIPE);
+
+  s = handle->select;
+  if (s != NULL)
+    return s->fd;
+
+  return handle->io_watcher.fd;
+}
+#endif /* defined(__APPLE__) */
+
+
+void uv__stream_close(uv_stream_t* handle) {
+  unsigned int i;
+  uv__stream_queued_fds_t* queued_fds;
+
+#if defined(__APPLE__)
+  /* Terminate select loop first */
+  if (handle->select != NULL) {
+    uv__stream_select_t* s;
+
+    s = handle->select;
+
+    uv_sem_post(&s->close_sem);
+    uv_sem_post(&s->async_sem);
+    uv__stream_osx_interrupt_select(handle);
+    uv_thread_join(&s->thread);
+    uv_sem_destroy(&s->close_sem);
+    uv_sem_destroy(&s->async_sem);
+    uv__close(s->fake_fd);
+    uv__close(s->int_fd);
+    uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);
+
+    handle->select = NULL;
+  }
+#endif /* defined(__APPLE__) */
+
+  uv__io_close(handle->loop, &handle->io_watcher);
+  uv_read_stop(handle);
+  uv__handle_stop(handle);
+
+  if (handle->io_watcher.fd != -1) {
+    /* Don't close stdio file descriptors.  Nothing good comes from it. */
+    if (handle->io_watcher.fd > STDERR_FILENO)
+      uv__close(handle->io_watcher.fd);
+    handle->io_watcher.fd = -1;
+  }
+
+  if (handle->accepted_fd != -1) {
+    uv__close(handle->accepted_fd);
+    handle->accepted_fd = -1;
+  }
+
+  /* Close all queued fds */
+  if (handle->queued_fds != NULL) {
+    queued_fds = handle->queued_fds;
+    for (i = 0; i < queued_fds->offset; i++)
+      uv__close(queued_fds->fds[i]);
+    uv__free(handle->queued_fds);
+    handle->queued_fds = NULL;
+  }
+
+  assert(!uv__io_active(&handle->io_watcher, POLLIN | POLLOUT));
+}
+
+
+int uv_stream_set_blocking(uv_stream_t* handle, int blocking) {
+  /* Don't need to check the file descriptor, uv__nonblock()
+   * will fail with EBADF if it's not valid.
+   */
+  return uv__nonblock(uv__stream_fd(handle), !blocking);
+}
diff --git a/Utilities/cmlibuv/src/unix/sunos.c b/Utilities/cmlibuv/src/unix/sunos.c
new file mode 100644
index 0000000..3e7a759
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/sunos.c
@@ -0,0 +1,821 @@
+/* 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 "internal.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#ifndef SUNOS_NO_IFADDRS
+# include <ifaddrs.h>
+#endif
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <net/if_arp.h>
+#include <sys/sockio.h>
+
+#include <sys/loadavg.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <kstat.h>
+#include <fcntl.h>
+
+#include <sys/port.h>
+#include <port.h>
+
+#define PORT_FIRED 0x69
+#define PORT_UNUSED 0x0
+#define PORT_LOADED 0x99
+#define PORT_DELETED -1
+
+#if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
+#define PROCFS_FILE_OFFSET_BITS_HACK 1
+#undef _FILE_OFFSET_BITS
+#else
+#define PROCFS_FILE_OFFSET_BITS_HACK 0
+#endif
+
+#include <procfs.h>
+
+#if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
+#define _FILE_OFFSET_BITS 64
+#endif
+
+
+int uv__platform_loop_init(uv_loop_t* loop) {
+  int err;
+  int fd;
+
+  loop->fs_fd = -1;
+  loop->backend_fd = -1;
+
+  fd = port_create();
+  if (fd == -1)
+    return -errno;
+
+  err = uv__cloexec(fd, 1);
+  if (err) {
+    uv__close(fd);
+    return err;
+  }
+  loop->backend_fd = fd;
+
+  return 0;
+}
+
+
+void uv__platform_loop_delete(uv_loop_t* loop) {
+  if (loop->fs_fd != -1) {
+    uv__close(loop->fs_fd);
+    loop->fs_fd = -1;
+  }
+
+  if (loop->backend_fd != -1) {
+    uv__close(loop->backend_fd);
+    loop->backend_fd = -1;
+  }
+}
+
+
+void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) {
+  struct port_event* events;
+  uintptr_t i;
+  uintptr_t nfds;
+
+  assert(loop->watchers != NULL);
+
+  events = (struct port_event*) loop->watchers[loop->nwatchers];
+  nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
+  if (events == NULL)
+    return;
+
+  /* Invalidate events with same file descriptor */
+  for (i = 0; i < nfds; i++)
+    if ((int) events[i].portev_object == fd)
+      events[i].portev_object = -1;
+}
+
+
+int uv__io_check_fd(uv_loop_t* loop, int fd) {
+  if (port_associate(loop->backend_fd, PORT_SOURCE_FD, fd, POLLIN, 0))
+    return -errno;
+
+  if (port_dissociate(loop->backend_fd, PORT_SOURCE_FD, fd))
+    abort();
+
+  return 0;
+}
+
+
+void uv__io_poll(uv_loop_t* loop, int timeout) {
+  struct port_event events[1024];
+  struct port_event* pe;
+  struct timespec spec;
+  QUEUE* q;
+  uv__io_t* w;
+  sigset_t* pset;
+  sigset_t set;
+  uint64_t base;
+  uint64_t diff;
+  unsigned int nfds;
+  unsigned int i;
+  int saved_errno;
+  int have_signals;
+  int nevents;
+  int count;
+  int err;
+  int fd;
+
+  if (loop->nfds == 0) {
+    assert(QUEUE_EMPTY(&loop->watcher_queue));
+    return;
+  }
+
+  while (!QUEUE_EMPTY(&loop->watcher_queue)) {
+    q = QUEUE_HEAD(&loop->watcher_queue);
+    QUEUE_REMOVE(q);
+    QUEUE_INIT(q);
+
+    w = QUEUE_DATA(q, uv__io_t, watcher_queue);
+    assert(w->pevents != 0);
+
+    if (port_associate(loop->backend_fd, PORT_SOURCE_FD, w->fd, w->pevents, 0))
+      abort();
+
+    w->events = w->pevents;
+  }
+
+  pset = NULL;
+  if (loop->flags & UV_LOOP_BLOCK_SIGPROF) {
+    pset = &set;
+    sigemptyset(pset);
+    sigaddset(pset, SIGPROF);
+  }
+
+  assert(timeout >= -1);
+  base = loop->time;
+  count = 48; /* Benchmarks suggest this gives the best throughput. */
+
+  for (;;) {
+    if (timeout != -1) {
+      spec.tv_sec = timeout / 1000;
+      spec.tv_nsec = (timeout % 1000) * 1000000;
+    }
+
+    /* Work around a kernel bug where nfds is not updated. */
+    events[0].portev_source = 0;
+
+    nfds = 1;
+    saved_errno = 0;
+
+    if (pset != NULL)
+      pthread_sigmask(SIG_BLOCK, pset, NULL);
+
+    err = port_getn(loop->backend_fd,
+                    events,
+                    ARRAY_SIZE(events),
+                    &nfds,
+                    timeout == -1 ? NULL : &spec);
+
+    if (pset != NULL)
+      pthread_sigmask(SIG_UNBLOCK, pset, NULL);
+
+    if (err) {
+      /* Work around another kernel bug: port_getn() may return events even
+       * on error.
+       */
+      if (errno == EINTR || errno == ETIME)
+        saved_errno = errno;
+      else
+        abort();
+    }
+
+    /* Update loop->time unconditionally. It's tempting to skip the update when
+     * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
+     * operating system didn't reschedule our process while in the syscall.
+     */
+    SAVE_ERRNO(uv__update_time(loop));
+
+    if (events[0].portev_source == 0) {
+      if (timeout == 0)
+        return;
+
+      if (timeout == -1)
+        continue;
+
+      goto update_timeout;
+    }
+
+    if (nfds == 0) {
+      assert(timeout != -1);
+      return;
+    }
+
+    have_signals = 0;
+    nevents = 0;
+
+    assert(loop->watchers != NULL);
+    loop->watchers[loop->nwatchers] = (void*) events;
+    loop->watchers[loop->nwatchers + 1] = (void*) (uintptr_t) nfds;
+    for (i = 0; i < nfds; i++) {
+      pe = events + i;
+      fd = pe->portev_object;
+
+      /* Skip invalidated events, see uv__platform_invalidate_fd */
+      if (fd == -1)
+        continue;
+
+      assert(fd >= 0);
+      assert((unsigned) fd < loop->nwatchers);
+
+      w = loop->watchers[fd];
+
+      /* File descriptor that we've stopped watching, ignore. */
+      if (w == NULL)
+        continue;
+
+      /* Run signal watchers last.  This also affects child process watchers
+       * because those are implemented in terms of signal watchers.
+       */
+      if (w == &loop->signal_io_watcher)
+        have_signals = 1;
+      else
+        w->cb(loop, w, pe->portev_events);
+
+      nevents++;
+
+      if (w != loop->watchers[fd])
+        continue;  /* Disabled by callback. */
+
+      /* Events Ports operates in oneshot mode, rearm timer on next run. */
+      if (w->pevents != 0 && QUEUE_EMPTY(&w->watcher_queue))
+        QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
+    }
+
+    if (have_signals != 0)
+      loop->signal_io_watcher.cb(loop, &loop->signal_io_watcher, POLLIN);
+
+    loop->watchers[loop->nwatchers] = NULL;
+    loop->watchers[loop->nwatchers + 1] = NULL;
+
+    if (have_signals != 0)
+      return;  /* Event loop should cycle now so don't poll again. */
+
+    if (nevents != 0) {
+      if (nfds == ARRAY_SIZE(events) && --count != 0) {
+        /* Poll for more events but don't block this time. */
+        timeout = 0;
+        continue;
+      }
+      return;
+    }
+
+    if (saved_errno == ETIME) {
+      assert(timeout != -1);
+      return;
+    }
+
+    if (timeout == 0)
+      return;
+
+    if (timeout == -1)
+      continue;
+
+update_timeout:
+    assert(timeout > 0);
+
+    diff = loop->time - base;
+    if (diff >= (uint64_t) timeout)
+      return;
+
+    timeout -= diff;
+  }
+}
+
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+  return gethrtime();
+}
+
+
+/*
+ * 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.
+ */
+int uv_exepath(char* buffer, size_t* size) {
+  ssize_t res;
+  char buf[128];
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return -EINVAL;
+
+  snprintf(buf, sizeof(buf), "/proc/%lu/path/a.out", (unsigned long) getpid());
+
+  res = *size - 1;
+  if (res > 0)
+    res = readlink(buf, buffer, res);
+
+  if (res == -1)
+    return -errno;
+
+  buffer[res] = '\0';
+  *size = res;
+  return 0;
+}
+
+
+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]) {
+  (void) getloadavg(avg, 3);
+}
+
+
+#if defined(PORT_SOURCE_FILE)
+
+static int uv__fs_event_rearm(uv_fs_event_t *handle) {
+  if (handle->fd == -1)
+    return -EBADF;
+
+  if (port_associate(handle->loop->fs_fd,
+                     PORT_SOURCE_FILE,
+                     (uintptr_t) &handle->fo,
+                     FILE_ATTRIB | FILE_MODIFIED,
+                     handle) == -1) {
+    return -errno;
+  }
+  handle->fd = PORT_LOADED;
+
+  return 0;
+}
+
+
+static void uv__fs_event_read(uv_loop_t* loop,
+                              uv__io_t* w,
+                              unsigned int revents) {
+  uv_fs_event_t *handle = NULL;
+  timespec_t timeout;
+  port_event_t pe;
+  int events;
+  int r;
+
+  (void) w;
+  (void) revents;
+
+  do {
+    uint_t n = 1;
+
+    /*
+     * Note that our use of port_getn() here (and not port_get()) is deliberate:
+     * there is a bug in event ports (Sun bug 6456558) whereby a zeroed timeout
+     * causes port_get() to return success instead of ETIME when there aren't
+     * actually any events (!); by using port_getn() in lieu of port_get(),
+     * we can at least workaround the bug by checking for zero returned events
+     * and treating it as we would ETIME.
+     */
+    do {
+      memset(&timeout, 0, sizeof timeout);
+      r = port_getn(loop->fs_fd, &pe, 1, &n, &timeout);
+    }
+    while (r == -1 && errno == EINTR);
+
+    if ((r == -1 && errno == ETIME) || n == 0)
+      break;
+
+    handle = (uv_fs_event_t*) pe.portev_user;
+    assert((r == 0) && "unexpected port_get() error");
+
+    events = 0;
+    if (pe.portev_events & (FILE_ATTRIB | FILE_MODIFIED))
+      events |= UV_CHANGE;
+    if (pe.portev_events & ~(FILE_ATTRIB | FILE_MODIFIED))
+      events |= UV_RENAME;
+    assert(events != 0);
+    handle->fd = PORT_FIRED;
+    handle->cb(handle, NULL, events, 0);
+
+    if (handle->fd != PORT_DELETED) {
+      r = uv__fs_event_rearm(handle);
+      if (r != 0)
+        handle->cb(handle, NULL, 0, r);
+    }
+  }
+  while (handle->fd != PORT_DELETED);
+}
+
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_EVENT);
+  return 0;
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* path,
+                      unsigned int flags) {
+  int portfd;
+  int first_run;
+  int err;
+
+  if (uv__is_active(handle))
+    return -EINVAL;
+
+  first_run = 0;
+  if (handle->loop->fs_fd == -1) {
+    portfd = port_create();
+    if (portfd == -1)
+      return -errno;
+    handle->loop->fs_fd = portfd;
+    first_run = 1;
+  }
+
+  uv__handle_start(handle);
+  handle->path = uv__strdup(path);
+  handle->fd = PORT_UNUSED;
+  handle->cb = cb;
+
+  memset(&handle->fo, 0, sizeof handle->fo);
+  handle->fo.fo_name = handle->path;
+  err = uv__fs_event_rearm(handle);
+  if (err != 0)
+    return err;
+
+  if (first_run) {
+    uv__io_init(&handle->loop->fs_event_watcher, uv__fs_event_read, portfd);
+    uv__io_start(handle->loop, &handle->loop->fs_event_watcher, POLLIN);
+  }
+
+  return 0;
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+  if (!uv__is_active(handle))
+    return 0;
+
+  if (handle->fd == PORT_FIRED || handle->fd == PORT_LOADED) {
+    port_dissociate(handle->loop->fs_fd,
+                    PORT_SOURCE_FILE,
+                    (uintptr_t) &handle->fo);
+  }
+
+  handle->fd = PORT_DELETED;
+  uv__free(handle->path);
+  handle->path = NULL;
+  handle->fo.fo_name = NULL;
+  uv__handle_stop(handle);
+
+  return 0;
+}
+
+void uv__fs_event_close(uv_fs_event_t* handle) {
+  uv_fs_event_stop(handle);
+}
+
+#else /* !defined(PORT_SOURCE_FILE) */
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+  return -ENOSYS;
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* filename,
+                      unsigned int flags) {
+  return -ENOSYS;
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+  return -ENOSYS;
+}
+
+
+void uv__fs_event_close(uv_fs_event_t* handle) {
+  UNREACHABLE();
+}
+
+#endif /* defined(PORT_SOURCE_FILE) */
+
+
+char** uv_setup_args(int argc, char** argv) {
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+  if (buffer == NULL || size == 0)
+    return -EINVAL;
+
+  buffer[0] = '\0';
+  return 0;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  psinfo_t psinfo;
+  int err;
+  int fd;
+
+  fd = open("/proc/self/psinfo", O_RDONLY);
+  if (fd == -1)
+    return -errno;
+
+  /* FIXME(bnoordhuis) Handle EINTR. */
+  err = -EINVAL;
+  if (read(fd, &psinfo, sizeof(psinfo)) == sizeof(psinfo)) {
+    *rss = (size_t)psinfo.pr_rssize * 1024;
+    err = 0;
+  }
+  uv__close(fd);
+
+  return err;
+}
+
+
+int uv_uptime(double* uptime) {
+  kstat_ctl_t   *kc;
+  kstat_t       *ksp;
+  kstat_named_t *knp;
+
+  long hz = sysconf(_SC_CLK_TCK);
+
+  kc = kstat_open();
+  if (kc == NULL)
+    return -EPERM;
+
+  ksp = kstat_lookup(kc, (char*) "unix", 0, (char*) "system_misc");
+  if (kstat_read(kc, ksp, NULL) == -1) {
+    *uptime = -1;
+  } else {
+    knp = (kstat_named_t*)  kstat_data_lookup(ksp, (char*) "clk_intr");
+    *uptime = knp->value.ul / hz;
+  }
+  kstat_close(kc);
+
+  return 0;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+  int           lookup_instance;
+  kstat_ctl_t   *kc;
+  kstat_t       *ksp;
+  kstat_named_t *knp;
+  uv_cpu_info_t* cpu_info;
+
+  kc = kstat_open();
+  if (kc == NULL)
+    return -EPERM;
+
+  /* Get count of cpus */
+  lookup_instance = 0;
+  while ((ksp = kstat_lookup(kc, (char*) "cpu_info", lookup_instance, NULL))) {
+    lookup_instance++;
+  }
+
+  *cpu_infos = uv__malloc(lookup_instance * sizeof(**cpu_infos));
+  if (!(*cpu_infos)) {
+    kstat_close(kc);
+    return -ENOMEM;
+  }
+
+  *count = lookup_instance;
+
+  cpu_info = *cpu_infos;
+  lookup_instance = 0;
+  while ((ksp = kstat_lookup(kc, (char*) "cpu_info", lookup_instance, NULL))) {
+    if (kstat_read(kc, ksp, NULL) == -1) {
+      cpu_info->speed = 0;
+      cpu_info->model = NULL;
+    } else {
+      knp = kstat_data_lookup(ksp, (char*) "clock_MHz");
+      assert(knp->data_type == KSTAT_DATA_INT32 ||
+             knp->data_type == KSTAT_DATA_INT64);
+      cpu_info->speed = (knp->data_type == KSTAT_DATA_INT32) ? knp->value.i32
+                                                             : knp->value.i64;
+
+      knp = kstat_data_lookup(ksp, (char*) "brand");
+      assert(knp->data_type == KSTAT_DATA_STRING);
+      cpu_info->model = uv__strdup(KSTAT_NAMED_STR_PTR(knp));
+    }
+
+    lookup_instance++;
+    cpu_info++;
+  }
+
+  cpu_info = *cpu_infos;
+  lookup_instance = 0;
+  for (;;) {
+    ksp = kstat_lookup(kc, (char*) "cpu", lookup_instance, (char*) "sys");
+
+    if (ksp == NULL)
+      break;
+
+    if (kstat_read(kc, ksp, NULL) == -1) {
+      cpu_info->cpu_times.user = 0;
+      cpu_info->cpu_times.nice = 0;
+      cpu_info->cpu_times.sys = 0;
+      cpu_info->cpu_times.idle = 0;
+      cpu_info->cpu_times.irq = 0;
+    } else {
+      knp = kstat_data_lookup(ksp, (char*) "cpu_ticks_user");
+      assert(knp->data_type == KSTAT_DATA_UINT64);
+      cpu_info->cpu_times.user = knp->value.ui64;
+
+      knp = kstat_data_lookup(ksp, (char*) "cpu_ticks_kernel");
+      assert(knp->data_type == KSTAT_DATA_UINT64);
+      cpu_info->cpu_times.sys = knp->value.ui64;
+
+      knp = kstat_data_lookup(ksp, (char*) "cpu_ticks_idle");
+      assert(knp->data_type == KSTAT_DATA_UINT64);
+      cpu_info->cpu_times.idle = knp->value.ui64;
+
+      knp = kstat_data_lookup(ksp, (char*) "intr");
+      assert(knp->data_type == KSTAT_DATA_UINT64);
+      cpu_info->cpu_times.irq = knp->value.ui64;
+      cpu_info->cpu_times.nice = 0;
+    }
+
+    lookup_instance++;
+    cpu_info++;
+  }
+
+  kstat_close(kc);
+
+  return 0;
+}
+
+
+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);
+}
+
+/*
+ * Inspired By:
+ * https://blogs.oracle.com/paulie/entry/retrieving_mac_address_in_solaris
+ * http://www.pauliesworld.org/project/getmac.c
+ */
+static int uv__set_phys_addr(uv_interface_address_t* address,
+                             struct ifaddrs* ent) {
+
+  struct sockaddr_dl* sa_addr;
+  int sockfd;
+  int i;
+  struct arpreq arpreq;
+
+  /* This appears to only work as root */
+  sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
+  memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+  for (i = 0; i < sizeof(address->phys_addr); i++) {
+    if (address->phys_addr[i] != 0)
+      return 0;
+  }
+  memset(&arpreq, 0, sizeof(arpreq));
+  if (address->address.address4.sin_family == AF_INET) {
+    struct sockaddr_in* sin = ((struct sockaddr_in*)&arpreq.arp_pa);
+    sin->sin_addr.s_addr = address->address.address4.sin_addr.s_addr;
+  } else if (address->address.address4.sin_family == AF_INET6) {
+    struct sockaddr_in6* sin = ((struct sockaddr_in6*)&arpreq.arp_pa);
+    memcpy(sin->sin6_addr.s6_addr,
+           address->address.address6.sin6_addr.s6_addr,
+           sizeof(address->address.address6.sin6_addr.s6_addr));
+  } else {
+    return 0;
+  }
+
+  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
+  if (sockfd < 0)
+    return -errno;
+
+  if (ioctl(sockfd, SIOCGARP, (char*)&arpreq) == -1) {
+    uv__close(sockfd);
+    return -errno;
+  }
+  memcpy(address->phys_addr, arpreq.arp_ha.sa_data, sizeof(address->phys_addr));
+  uv__close(sockfd);
+  return 0;
+}
+
+int uv_interface_addresses(uv_interface_address_t** addresses, int* count) {
+#ifdef SUNOS_NO_IFADDRS
+  return -ENOSYS;
+#else
+  uv_interface_address_t* address;
+  struct ifaddrs* addrs;
+  struct ifaddrs* ent;
+  int i;
+
+  if (getifaddrs(&addrs))
+    return -errno;
+
+  *count = 0;
+
+  /* Count the number of interfaces */
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)) ||
+        (ent->ifa_addr == NULL) ||
+        (ent->ifa_addr->sa_family == PF_PACKET)) {
+      continue;
+    }
+
+    (*count)++;
+  }
+
+  *addresses = uv__malloc(*count * sizeof(**addresses));
+  if (!(*addresses)) {
+    freeifaddrs(addrs);
+    return -ENOMEM;
+  }
+
+  address = *addresses;
+
+  for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
+    if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
+      continue;
+
+    if (ent->ifa_addr == NULL)
+      continue;
+
+    address->name = uv__strdup(ent->ifa_name);
+
+    if (ent->ifa_addr->sa_family == AF_INET6) {
+      address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
+    } else {
+      address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
+    }
+
+    if (ent->ifa_netmask->sa_family == AF_INET6) {
+      address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
+    } else {
+      address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
+    }
+
+    address->is_internal = !!((ent->ifa_flags & IFF_PRIVATE) ||
+                           (ent->ifa_flags & IFF_LOOPBACK));
+
+    uv__set_phys_addr(address, ent);
+    address++;
+  }
+
+  freeifaddrs(addrs);
+
+  return 0;
+#endif  /* SUNOS_NO_IFADDRS */
+}
+
+
+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/tcp.c b/Utilities/cmlibuv/src/unix/tcp.c
new file mode 100644
index 0000000..c423dcb
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/tcp.c
@@ -0,0 +1,395 @@
+/* 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 "internal.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <assert.h>
+#include <errno.h>
+
+
+static int maybe_new_socket(uv_tcp_t* handle, int domain, int flags) {
+  int sockfd;
+  int err;
+
+  if (domain == AF_UNSPEC || uv__stream_fd(handle) != -1) {
+    handle->flags |= flags;
+    return 0;
+  }
+
+  err = uv__socket(domain, SOCK_STREAM, 0);
+  if (err < 0)
+    return err;
+  sockfd = err;
+
+  err = uv__stream_open((uv_stream_t*) handle, sockfd, flags);
+  if (err) {
+    uv__close(sockfd);
+    return err;
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_init_ex(uv_loop_t* loop, uv_tcp_t* tcp, unsigned int flags) {
+  int domain;
+
+  /* Use the lower 8 bits for the domain */
+  domain = flags & 0xFF;
+  if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNSPEC)
+    return -EINVAL;
+
+  if (flags & ~0xFF)
+    return -EINVAL;
+
+  uv__stream_init(loop, (uv_stream_t*)tcp, UV_TCP);
+
+  /* If anything fails beyond this point we need to remove the handle from
+   * the handle queue, since it was added by uv__handle_init in uv_stream_init.
+   */
+
+  if (domain != AF_UNSPEC) {
+    int err = maybe_new_socket(tcp, domain, 0);
+    if (err) {
+      QUEUE_REMOVE(&tcp->handle_queue);
+      return err;
+    }
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_init(uv_loop_t* loop, uv_tcp_t* tcp) {
+  return uv_tcp_init_ex(loop, tcp, AF_UNSPEC);
+}
+
+
+int uv__tcp_bind(uv_tcp_t* tcp,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 unsigned int flags) {
+  int err;
+  int on;
+
+  /* Cannot set IPv6-only mode on non-IPv6 socket. */
+  if ((flags & UV_TCP_IPV6ONLY) && addr->sa_family != AF_INET6)
+    return -EINVAL;
+
+  err = maybe_new_socket(tcp,
+                         addr->sa_family,
+                         UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+  if (err)
+    return err;
+
+  on = 1;
+  if (setsockopt(tcp->io_watcher.fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
+    return -errno;
+
+#ifdef IPV6_V6ONLY
+  if (addr->sa_family == AF_INET6) {
+    on = (flags & UV_TCP_IPV6ONLY) != 0;
+    if (setsockopt(tcp->io_watcher.fd,
+                   IPPROTO_IPV6,
+                   IPV6_V6ONLY,
+                   &on,
+                   sizeof on) == -1) {
+#if defined(__MVS__)
+      if (errno == EOPNOTSUPP)
+        return -EINVAL;
+#endif
+      return -errno;
+    }
+  }
+#endif
+
+  errno = 0;
+  if (bind(tcp->io_watcher.fd, addr, addrlen) && errno != EADDRINUSE) {
+    if (errno == EAFNOSUPPORT)
+      /* OSX, other BSDs and SunoS fail with EAFNOSUPPORT when binding a
+       * socket created with AF_INET to an AF_INET6 address or vice versa. */
+      return -EINVAL;
+    return -errno;
+  }
+  tcp->delayed_error = -errno;
+
+  tcp->flags |= UV_HANDLE_BOUND;
+  if (addr->sa_family == AF_INET6)
+    tcp->flags |= UV_HANDLE_IPV6;
+
+  return 0;
+}
+
+
+int uv__tcp_connect(uv_connect_t* req,
+                    uv_tcp_t* handle,
+                    const struct sockaddr* addr,
+                    unsigned int addrlen,
+                    uv_connect_cb cb) {
+  int err;
+  int r;
+
+  assert(handle->type == UV_TCP);
+
+  if (handle->connect_req != NULL)
+    return -EALREADY;  /* FIXME(bnoordhuis) -EINVAL or maybe -EBUSY. */
+
+  err = maybe_new_socket(handle,
+                         addr->sa_family,
+                         UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+  if (err)
+    return err;
+
+  handle->delayed_error = 0;
+
+  do {
+    errno = 0;
+    r = connect(uv__stream_fd(handle), addr, addrlen);
+  } while (r == -1 && errno == EINTR);
+
+  /* We not only check the return value, but also check the errno != 0.
+   * Because in rare cases connect() will return -1 but the errno
+   * is 0 (for example, on Android 4.3, OnePlus phone A0001_12_150227)
+   * and actually the tcp three-way handshake is completed.
+   */
+  if (r == -1 && errno != 0) {
+    if (errno == EINPROGRESS)
+      ; /* not an error */
+    else if (errno == ECONNREFUSED)
+    /* If we get a ECONNREFUSED wait until the next tick to report the
+     * error. Solaris wants to report immediately--other unixes want to
+     * wait.
+     */
+      handle->delayed_error = -errno;
+    else
+      return -errno;
+  }
+
+  uv__req_init(handle->loop, req, UV_CONNECT);
+  req->cb = cb;
+  req->handle = (uv_stream_t*) handle;
+  QUEUE_INIT(&req->queue);
+  handle->connect_req = req;
+
+  uv__io_start(handle->loop, &handle->io_watcher, POLLOUT);
+
+  if (handle->delayed_error)
+    uv__io_feed(handle->loop, &handle->io_watcher);
+
+  return 0;
+}
+
+
+int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock) {
+  int err;
+
+  err = uv__nonblock(sock, 1);
+  if (err)
+    return err;
+
+  return uv__stream_open((uv_stream_t*)handle,
+                         sock,
+                         UV_STREAM_READABLE | UV_STREAM_WRITABLE);
+}
+
+
+int uv_tcp_getsockname(const uv_tcp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  socklen_t socklen;
+
+  if (handle->delayed_error)
+    return handle->delayed_error;
+
+  if (uv__stream_fd(handle) < 0)
+    return -EINVAL;  /* FIXME(bnoordhuis) -EBADF */
+
+  /* sizeof(socklen_t) != sizeof(int) on some systems. */
+  socklen = (socklen_t) *namelen;
+
+  if (getsockname(uv__stream_fd(handle), name, &socklen))
+    return -errno;
+
+  *namelen = (int) socklen;
+  return 0;
+}
+
+
+int uv_tcp_getpeername(const uv_tcp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  socklen_t socklen;
+
+  if (handle->delayed_error)
+    return handle->delayed_error;
+
+  if (uv__stream_fd(handle) < 0)
+    return -EINVAL;  /* FIXME(bnoordhuis) -EBADF */
+
+  /* sizeof(socklen_t) != sizeof(int) on some systems. */
+  socklen = (socklen_t) *namelen;
+
+  if (getpeername(uv__stream_fd(handle), name, &socklen))
+    return -errno;
+
+  *namelen = (int) socklen;
+  return 0;
+}
+
+
+int uv_tcp_listen(uv_tcp_t* tcp, int backlog, uv_connection_cb cb) {
+  static int single_accept = -1;
+  int err;
+
+  if (tcp->delayed_error)
+    return tcp->delayed_error;
+
+  if (single_accept == -1) {
+    const char* val = getenv("UV_TCP_SINGLE_ACCEPT");
+    single_accept = (val != NULL && atoi(val) != 0);  /* Off by default. */
+  }
+
+  if (single_accept)
+    tcp->flags |= UV_TCP_SINGLE_ACCEPT;
+
+  err = maybe_new_socket(tcp, AF_INET, UV_STREAM_READABLE);
+  if (err)
+    return err;
+
+#ifdef __MVS__
+  /* on zOS the listen call does not bind automatically
+     if the socket is unbound. Hence the manual binding to
+     an arbitrary port is required to be done manually
+  */
+
+  if (!(tcp->flags & UV_HANDLE_BOUND)) {
+    struct sockaddr_storage saddr;
+    socklen_t slen  = sizeof(saddr);
+    memset(&saddr, 0, sizeof(saddr));
+
+    if (getsockname(tcp->io_watcher.fd, (struct sockaddr*) &saddr, &slen))
+      return -errno;
+
+    if (bind(tcp->io_watcher.fd, (struct sockaddr*) &saddr, slen))
+      return -errno;
+
+    tcp->flags |= UV_HANDLE_BOUND;
+  }
+#endif
+
+  if (listen(tcp->io_watcher.fd, backlog))
+    return -errno;
+
+  tcp->connection_cb = cb;
+  tcp->flags |= UV_HANDLE_BOUND;
+
+  /* Start listening for connections. */
+  tcp->io_watcher.cb = uv__server_io;
+  uv__io_start(tcp->loop, &tcp->io_watcher, POLLIN);
+
+  return 0;
+}
+
+
+int uv__tcp_nodelay(int fd, int on) {
+  if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)))
+    return -errno;
+  return 0;
+}
+
+
+int uv__tcp_keepalive(int fd, int on, unsigned int delay) {
+  if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)))
+    return -errno;
+
+#ifdef TCP_KEEPIDLE
+  if (on && setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &delay, sizeof(delay)))
+    return -errno;
+#endif
+
+  /* Solaris/SmartOS, if you don't support keep-alive,
+   * then don't advertise it in your system headers...
+   */
+  /* FIXME(bnoordhuis) That's possibly because sizeof(delay) should be 1. */
+#if defined(TCP_KEEPALIVE) && !defined(__sun)
+  if (on && setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &delay, sizeof(delay)))
+    return -errno;
+#endif
+
+  return 0;
+}
+
+
+int uv_tcp_nodelay(uv_tcp_t* handle, int on) {
+  int err;
+
+  if (uv__stream_fd(handle) != -1) {
+    err = uv__tcp_nodelay(uv__stream_fd(handle), on);
+    if (err)
+      return err;
+  }
+
+  if (on)
+    handle->flags |= UV_TCP_NODELAY;
+  else
+    handle->flags &= ~UV_TCP_NODELAY;
+
+  return 0;
+}
+
+
+int uv_tcp_keepalive(uv_tcp_t* handle, int on, unsigned int delay) {
+  int err;
+
+  if (uv__stream_fd(handle) != -1) {
+    err =uv__tcp_keepalive(uv__stream_fd(handle), on, delay);
+    if (err)
+      return err;
+  }
+
+  if (on)
+    handle->flags |= UV_TCP_KEEPALIVE;
+  else
+    handle->flags &= ~UV_TCP_KEEPALIVE;
+
+  /* TODO Store delay if uv__stream_fd(handle) == -1 but don't want to enlarge
+   *      uv_tcp_t with an int that's almost never used...
+   */
+
+  return 0;
+}
+
+
+int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable) {
+  if (enable)
+    handle->flags &= ~UV_TCP_SINGLE_ACCEPT;
+  else
+    handle->flags |= UV_TCP_SINGLE_ACCEPT;
+  return 0;
+}
+
+
+void uv__tcp_close(uv_tcp_t* handle) {
+  uv__stream_close((uv_stream_t*)handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/thread.c b/Utilities/cmlibuv/src/unix/thread.c
new file mode 100644
index 0000000..52989f7
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/thread.c
@@ -0,0 +1,605 @@
+/* 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 "internal.h"
+
+#include <pthread.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/time.h>
+#include <sys/resource.h>  /* getrlimit() */
+#include <unistd.h>  /* getpagesize() */
+
+#include <limits.h>
+
+#ifdef __MVS__
+#include <sys/ipc.h>
+#include <sys/sem.h>
+#endif
+
+#undef NANOSEC
+#define NANOSEC ((uint64_t) 1e9)
+
+struct thread_ctx {
+  void (*entry)(void* arg);
+  void* arg;
+};
+
+
+static void* uv__thread_start(void *arg)
+{
+  struct thread_ctx *ctx_p;
+  struct thread_ctx ctx;
+
+  ctx_p = arg;
+  ctx = *ctx_p;
+  uv__free(ctx_p);
+  ctx.entry(ctx.arg);
+
+  return 0;
+}
+
+
+int uv_thread_create(uv_thread_t *tid, void (*entry)(void *arg), void *arg) {
+  struct thread_ctx* ctx;
+  int err;
+  pthread_attr_t* attr;
+#if defined(__APPLE__)
+  pthread_attr_t attr_storage;
+  struct rlimit lim;
+#endif
+
+  ctx = uv__malloc(sizeof(*ctx));
+  if (ctx == NULL)
+    return UV_ENOMEM;
+
+  ctx->entry = entry;
+  ctx->arg = arg;
+
+  /* On OSX threads other than the main thread are created with a reduced stack
+   * size by default, adjust it to RLIMIT_STACK.
+   */
+#if defined(__APPLE__)
+  if (getrlimit(RLIMIT_STACK, &lim))
+    abort();
+
+  attr = &attr_storage;
+  if (pthread_attr_init(attr))
+    abort();
+
+  if (lim.rlim_cur != RLIM_INFINITY) {
+    /* pthread_attr_setstacksize() expects page-aligned values. */
+    lim.rlim_cur -= lim.rlim_cur % (rlim_t) getpagesize();
+
+    if (lim.rlim_cur >= PTHREAD_STACK_MIN)
+      if (pthread_attr_setstacksize(attr, lim.rlim_cur))
+        abort();
+  }
+#else
+  attr = NULL;
+#endif
+
+  err = pthread_create(tid, attr, uv__thread_start, ctx);
+
+  if (attr != NULL)
+    pthread_attr_destroy(attr);
+
+  if (err)
+    uv__free(ctx);
+
+  return -err;
+}
+
+
+uv_thread_t uv_thread_self(void) {
+  return pthread_self();
+}
+
+int uv_thread_join(uv_thread_t *tid) {
+  return -pthread_join(*tid, NULL);
+}
+
+
+int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2) {
+  return pthread_equal(*t1, *t2);
+}
+
+
+int uv_mutex_init(uv_mutex_t* mutex) {
+#if defined(NDEBUG) || !defined(PTHREAD_MUTEX_ERRORCHECK)
+  return -pthread_mutex_init(mutex, NULL);
+#else
+  pthread_mutexattr_t attr;
+  int err;
+
+  if (pthread_mutexattr_init(&attr))
+    abort();
+
+  if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK))
+    abort();
+
+  err = pthread_mutex_init(mutex, &attr);
+
+  if (pthread_mutexattr_destroy(&attr))
+    abort();
+
+  return -err;
+#endif
+}
+
+
+void uv_mutex_destroy(uv_mutex_t* mutex) {
+  if (pthread_mutex_destroy(mutex))
+    abort();
+}
+
+
+void uv_mutex_lock(uv_mutex_t* mutex) {
+  if (pthread_mutex_lock(mutex))
+    abort();
+}
+
+
+int uv_mutex_trylock(uv_mutex_t* mutex) {
+  int err;
+
+  err = pthread_mutex_trylock(mutex);
+  if (err) {
+    if (err != EBUSY && err != EAGAIN)
+      abort();
+    return -EBUSY;
+  }
+
+  return 0;
+}
+
+
+void uv_mutex_unlock(uv_mutex_t* mutex) {
+  if (pthread_mutex_unlock(mutex))
+    abort();
+}
+
+
+int uv_rwlock_init(uv_rwlock_t* rwlock) {
+  return -pthread_rwlock_init(rwlock, NULL);
+}
+
+
+void uv_rwlock_destroy(uv_rwlock_t* rwlock) {
+  if (pthread_rwlock_destroy(rwlock))
+    abort();
+}
+
+
+void uv_rwlock_rdlock(uv_rwlock_t* rwlock) {
+  if (pthread_rwlock_rdlock(rwlock))
+    abort();
+}
+
+
+int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock) {
+  int err;
+
+  err = pthread_rwlock_tryrdlock(rwlock);
+  if (err) {
+    if (err != EBUSY && err != EAGAIN)
+      abort();
+    return -EBUSY;
+  }
+
+  return 0;
+}
+
+
+void uv_rwlock_rdunlock(uv_rwlock_t* rwlock) {
+  if (pthread_rwlock_unlock(rwlock))
+    abort();
+}
+
+
+void uv_rwlock_wrlock(uv_rwlock_t* rwlock) {
+  if (pthread_rwlock_wrlock(rwlock))
+    abort();
+}
+
+
+int uv_rwlock_trywrlock(uv_rwlock_t* rwlock) {
+  int err;
+
+  err = pthread_rwlock_trywrlock(rwlock);
+  if (err) {
+    if (err != EBUSY && err != EAGAIN)
+      abort();
+    return -EBUSY;
+  }
+
+  return 0;
+}
+
+
+void uv_rwlock_wrunlock(uv_rwlock_t* rwlock) {
+  if (pthread_rwlock_unlock(rwlock))
+    abort();
+}
+
+
+void uv_once(uv_once_t* guard, void (*callback)(void)) {
+  if (pthread_once(guard, callback))
+    abort();
+}
+
+#if defined(__APPLE__) && defined(__MACH__)
+
+int uv_sem_init(uv_sem_t* sem, unsigned int value) {
+  kern_return_t err;
+
+  err = semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value);
+  if (err == KERN_SUCCESS)
+    return 0;
+  if (err == KERN_INVALID_ARGUMENT)
+    return -EINVAL;
+  if (err == KERN_RESOURCE_SHORTAGE)
+    return -ENOMEM;
+
+  abort();
+  return -EINVAL;  /* Satisfy the compiler. */
+}
+
+
+void uv_sem_destroy(uv_sem_t* sem) {
+  if (semaphore_destroy(mach_task_self(), *sem))
+    abort();
+}
+
+
+void uv_sem_post(uv_sem_t* sem) {
+  if (semaphore_signal(*sem))
+    abort();
+}
+
+
+void uv_sem_wait(uv_sem_t* sem) {
+  int r;
+
+  do
+    r = semaphore_wait(*sem);
+  while (r == KERN_ABORTED);
+
+  if (r != KERN_SUCCESS)
+    abort();
+}
+
+
+int uv_sem_trywait(uv_sem_t* sem) {
+  mach_timespec_t interval;
+  kern_return_t err;
+
+  interval.tv_sec = 0;
+  interval.tv_nsec = 0;
+
+  err = semaphore_timedwait(*sem, interval);
+  if (err == KERN_SUCCESS)
+    return 0;
+  if (err == KERN_OPERATION_TIMED_OUT)
+    return -EAGAIN;
+
+  abort();
+  return -EINVAL;  /* Satisfy the compiler. */
+}
+
+#elif defined(__MVS__)
+
+int uv_sem_init(uv_sem_t* sem, unsigned int value) {
+  uv_sem_t semid;
+  struct sembuf buf;
+  int err;
+
+  buf.sem_num = 0;
+  buf.sem_op = value;
+  buf.sem_flg = 0;
+
+  semid = semget(IPC_PRIVATE, 1, S_IRUSR | S_IWUSR);
+  if (semid == -1)
+    return -errno;
+
+  if (-1 == semop(semid, &buf, 1)) {
+    err = errno;
+    if (-1 == semctl(*sem, 0, IPC_RMID))
+      abort();
+    return -err;
+  }
+
+  *sem = semid;
+  return 0;
+}
+
+void uv_sem_destroy(uv_sem_t* sem) {
+  if (-1 == semctl(*sem, 0, IPC_RMID))
+    abort();
+}
+
+void uv_sem_post(uv_sem_t* sem) {
+  struct sembuf buf;
+
+  buf.sem_num = 0;
+  buf.sem_op = 1;
+  buf.sem_flg = 0;
+
+  if (-1 == semop(*sem, &buf, 1))
+    abort();
+}
+
+void uv_sem_wait(uv_sem_t* sem) {
+  struct sembuf buf;
+  int op_status;
+
+  buf.sem_num = 0;
+  buf.sem_op = -1;
+  buf.sem_flg = 0;
+
+  do
+    op_status = semop(*sem, &buf, 1);
+  while (op_status == -1 && errno == EINTR);
+
+  if (op_status)
+    abort();
+}
+
+int uv_sem_trywait(uv_sem_t* sem) {
+  struct sembuf buf;
+  int op_status;
+
+  buf.sem_num = 0;
+  buf.sem_op = -1;
+  buf.sem_flg = IPC_NOWAIT;
+
+  do
+    op_status = semop(*sem, &buf, 1);
+  while (op_status == -1 && errno == EINTR);
+
+  if (op_status) {
+    if (errno == EAGAIN)
+      return -EAGAIN;
+    abort();
+  }
+
+  return 0;
+}
+
+#else /* !(defined(__APPLE__) && defined(__MACH__)) */
+
+int uv_sem_init(uv_sem_t* sem, unsigned int value) {
+  if (sem_init(sem, 0, value))
+    return -errno;
+  return 0;
+}
+
+
+void uv_sem_destroy(uv_sem_t* sem) {
+  if (sem_destroy(sem))
+    abort();
+}
+
+
+void uv_sem_post(uv_sem_t* sem) {
+  if (sem_post(sem))
+    abort();
+}
+
+
+void uv_sem_wait(uv_sem_t* sem) {
+  int r;
+
+  do
+    r = sem_wait(sem);
+  while (r == -1 && errno == EINTR);
+
+  if (r)
+    abort();
+}
+
+
+int uv_sem_trywait(uv_sem_t* sem) {
+  int r;
+
+  do
+    r = sem_trywait(sem);
+  while (r == -1 && errno == EINTR);
+
+  if (r) {
+    if (errno == EAGAIN)
+      return -EAGAIN;
+    abort();
+  }
+
+  return 0;
+}
+
+#endif /* defined(__APPLE__) && defined(__MACH__) */
+
+
+#if defined(__APPLE__) && defined(__MACH__) || defined(__MVS__)
+
+int uv_cond_init(uv_cond_t* cond) {
+  return -pthread_cond_init(cond, NULL);
+}
+
+#else /* !(defined(__APPLE__) && defined(__MACH__)) */
+
+int uv_cond_init(uv_cond_t* cond) {
+  pthread_condattr_t attr;
+  int err;
+
+  err = pthread_condattr_init(&attr);
+  if (err)
+    return -err;
+
+#if !(defined(__ANDROID__) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
+  err = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
+  if (err)
+    goto error2;
+#endif
+
+  err = pthread_cond_init(cond, &attr);
+  if (err)
+    goto error2;
+
+  err = pthread_condattr_destroy(&attr);
+  if (err)
+    goto error;
+
+  return 0;
+
+error:
+  pthread_cond_destroy(cond);
+error2:
+  pthread_condattr_destroy(&attr);
+  return -err;
+}
+
+#endif /* defined(__APPLE__) && defined(__MACH__) */
+
+void uv_cond_destroy(uv_cond_t* cond) {
+#if defined(__APPLE__) && defined(__MACH__)
+  /* It has been reported that destroying condition variables that have been
+   * signalled but not waited on can sometimes result in application crashes.
+   * See https://codereview.chromium.org/1323293005.
+   */
+  pthread_mutex_t mutex;
+  struct timespec ts;
+  int err;
+
+  if (pthread_mutex_init(&mutex, NULL))
+    abort();
+
+  if (pthread_mutex_lock(&mutex))
+    abort();
+
+  ts.tv_sec = 0;
+  ts.tv_nsec = 1;
+
+  err = pthread_cond_timedwait_relative_np(cond, &mutex, &ts);
+  if (err != 0 && err != ETIMEDOUT)
+    abort();
+
+  if (pthread_mutex_unlock(&mutex))
+    abort();
+
+  if (pthread_mutex_destroy(&mutex))
+    abort();
+#endif /* defined(__APPLE__) && defined(__MACH__) */
+
+  if (pthread_cond_destroy(cond))
+    abort();
+}
+
+void uv_cond_signal(uv_cond_t* cond) {
+  if (pthread_cond_signal(cond))
+    abort();
+}
+
+void uv_cond_broadcast(uv_cond_t* cond) {
+  if (pthread_cond_broadcast(cond))
+    abort();
+}
+
+void uv_cond_wait(uv_cond_t* cond, uv_mutex_t* mutex) {
+  if (pthread_cond_wait(cond, mutex))
+    abort();
+}
+
+
+int uv_cond_timedwait(uv_cond_t* cond, uv_mutex_t* mutex, uint64_t timeout) {
+  int r;
+  struct timespec ts;
+
+#if defined(__APPLE__) && defined(__MACH__)
+  ts.tv_sec = timeout / NANOSEC;
+  ts.tv_nsec = timeout % NANOSEC;
+  r = pthread_cond_timedwait_relative_np(cond, mutex, &ts);
+#else
+  timeout += uv__hrtime(UV_CLOCK_PRECISE);
+  ts.tv_sec = timeout / NANOSEC;
+  ts.tv_nsec = timeout % NANOSEC;
+#if defined(__ANDROID__) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC)
+  /*
+   * The bionic pthread implementation doesn't support CLOCK_MONOTONIC,
+   * but has this alternative function instead.
+   */
+  r = pthread_cond_timedwait_monotonic_np(cond, mutex, &ts);
+#else
+  r = pthread_cond_timedwait(cond, mutex, &ts);
+#endif /* __ANDROID__ */
+#endif
+
+
+  if (r == 0)
+    return 0;
+
+  if (r == ETIMEDOUT)
+    return -ETIMEDOUT;
+
+  abort();
+  return -EINVAL;  /* Satisfy the compiler. */
+}
+
+
+int uv_barrier_init(uv_barrier_t* barrier, unsigned int count) {
+  return -pthread_barrier_init(barrier, NULL, count);
+}
+
+
+void uv_barrier_destroy(uv_barrier_t* barrier) {
+  if (pthread_barrier_destroy(barrier))
+    abort();
+}
+
+
+int uv_barrier_wait(uv_barrier_t* barrier) {
+  int r = pthread_barrier_wait(barrier);
+  if (r && r != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort();
+  return r == PTHREAD_BARRIER_SERIAL_THREAD;
+}
+
+
+int uv_key_create(uv_key_t* key) {
+  return -pthread_key_create(key, NULL);
+}
+
+
+void uv_key_delete(uv_key_t* key) {
+  if (pthread_key_delete(*key))
+    abort();
+}
+
+
+void* uv_key_get(uv_key_t* key) {
+  return pthread_getspecific(*key);
+}
+
+
+void uv_key_set(uv_key_t* key, void* value) {
+  if (pthread_setspecific(*key, value))
+    abort();
+}
diff --git a/Utilities/cmlibuv/src/unix/timer.c b/Utilities/cmlibuv/src/unix/timer.c
new file mode 100644
index 0000000..f46bdf4
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/timer.c
@@ -0,0 +1,172 @@
+/* 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 "internal.h"
+#include "heap-inl.h"
+
+#include <assert.h>
+#include <limits.h>
+
+
+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 -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((struct heap*) &handle->loop->timer_heap,
+              (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((struct heap*) &handle->loop->timer_heap,
+              (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 -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((const struct heap*) &loop->timer_heap);
+  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 diff;
+}
+
+
+void uv__run_timers(uv_loop_t* loop) {
+  struct heap_node* heap_node;
+  uv_timer_t* handle;
+
+  for (;;) {
+    heap_node = heap_min((struct heap*) &loop->timer_heap);
+    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/tty.c b/Utilities/cmlibuv/src/unix/tty.c
new file mode 100644
index 0000000..ae1018f
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/tty.c
@@ -0,0 +1,333 @@
+/* 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 "internal.h"
+#include "spinlock.h"
+
+#include <stdlib.h>
+#include <assert.h>
+#include <unistd.h>
+#include <termios.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+
+#if defined(__MVS__) && !defined(IMAXBEL)
+#define IMAXBEL 0
+#endif
+
+static int orig_termios_fd = -1;
+static struct termios orig_termios;
+static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER;
+
+static int uv__tty_is_slave(const int fd) {
+  int result;
+#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
+  int dummy;
+
+  result = ioctl(fd, TIOCGPTN, &dummy) != 0;
+#elif defined(__APPLE__)
+  char dummy[256];
+
+  result = ioctl(fd, TIOCPTYGNAME, &dummy) != 0;
+#else
+  /* Fallback to ptsname
+   */
+  result = ptsname(fd) == NULL;
+#endif
+  return result;
+}
+
+int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) {
+  uv_handle_type type;
+  int flags = 0;
+  int newfd = -1;
+  int r;
+  int saved_flags;
+  char path[256];
+
+  /* File descriptors that refer to files cannot be monitored with epoll.
+   * That restriction also applies to character devices like /dev/random
+   * (but obviously not /dev/tty.)
+   */
+  type = uv_guess_handle(fd);
+  if (type == UV_FILE || type == UV_UNKNOWN_HANDLE)
+    return -EINVAL;
+
+  /* Reopen the file descriptor when it refers to a tty. This lets us put the
+   * tty in non-blocking mode without affecting other processes that share it
+   * with us.
+   *
+   * Example: `node | cat` - if we put our fd 0 in non-blocking mode, it also
+   * affects fd 1 of `cat` because both file descriptors refer to the same
+   * struct file in the kernel. When we reopen our fd 0, it points to a
+   * different struct file, hence changing its properties doesn't affect
+   * other processes.
+   */
+  if (type == UV_TTY) {
+    /* Reopening a pty in master mode won't work either because the reopened
+     * pty will be in slave mode (*BSD) or reopening will allocate a new
+     * master/slave pair (Linux). Therefore check if the fd points to a
+     * slave device.
+     */
+    if (uv__tty_is_slave(fd) && ttyname_r(fd, path, sizeof(path)) == 0)
+      r = uv__open_cloexec(path, O_RDWR);
+    else
+      r = -1;
+
+    if (r < 0) {
+      /* fallback to using blocking writes */
+      if (!readable)
+        flags |= UV_STREAM_BLOCKING;
+      goto skip;
+    }
+
+    newfd = r;
+
+    r = uv__dup2_cloexec(newfd, fd);
+    if (r < 0 && r != -EINVAL) {
+      /* EINVAL means newfd == fd which could conceivably happen if another
+       * thread called close(fd) between our calls to isatty() and open().
+       * That's a rather unlikely event but let's handle it anyway.
+       */
+      uv__close(newfd);
+      return r;
+    }
+
+    fd = newfd;
+  }
+
+#if defined(__APPLE__)
+  /* Save the fd flags in case we need to restore them due to an error. */
+  do
+    saved_flags = fcntl(fd, F_GETFL);
+  while (saved_flags == -1 && errno == EINTR);
+
+  if (saved_flags == -1) {
+    if (newfd != -1)
+      uv__close(newfd);
+    return -errno;
+  }
+#endif
+
+  /* Pacify the compiler. */
+  (void) &saved_flags;
+
+skip:
+  uv__stream_init(loop, (uv_stream_t*) tty, UV_TTY);
+
+  /* If anything fails beyond this point we need to remove the handle from
+   * the handle queue, since it was added by uv__handle_init in uv_stream_init.
+   */
+
+  if (!(flags & UV_STREAM_BLOCKING))
+    uv__nonblock(fd, 1);
+
+#if defined(__APPLE__)
+  r = uv__stream_try_select((uv_stream_t*) tty, &fd);
+  if (r) {
+    int rc = r;
+    if (newfd != -1)
+      uv__close(newfd);
+    QUEUE_REMOVE(&tty->handle_queue);
+    do
+      r = fcntl(fd, F_SETFL, saved_flags);
+    while (r == -1 && errno == EINTR);
+    return rc;
+  }
+#endif
+
+  if (readable)
+    flags |= UV_STREAM_READABLE;
+  else
+    flags |= UV_STREAM_WRITABLE;
+
+  uv__stream_open((uv_stream_t*) tty, fd, flags);
+  tty->mode = UV_TTY_MODE_NORMAL;
+
+  return 0;
+}
+
+static void uv__tty_make_raw(struct termios* tio) {
+  assert(tio != NULL);
+
+#if defined __sun || defined __MVS__
+  /*
+   * This implementation of cfmakeraw for Solaris and derivatives is taken from
+   * http://www.perkin.org.uk/posts/solaris-portability-cfmakeraw.html.
+   */
+  tio->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR |
+                    IGNCR | ICRNL | IXON);
+  tio->c_oflag &= ~OPOST;
+  tio->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
+  tio->c_cflag &= ~(CSIZE | PARENB);
+  tio->c_cflag |= CS8;
+#else
+  cfmakeraw(tio);
+#endif /* #ifdef __sun */
+}
+
+int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
+  struct termios tmp;
+  int fd;
+
+  if (tty->mode == (int) mode)
+    return 0;
+
+  fd = uv__stream_fd(tty);
+  if (tty->mode == UV_TTY_MODE_NORMAL && mode != UV_TTY_MODE_NORMAL) {
+    if (tcgetattr(fd, &tty->orig_termios))
+      return -errno;
+
+    /* This is used for uv_tty_reset_mode() */
+    uv_spinlock_lock(&termios_spinlock);
+    if (orig_termios_fd == -1) {
+      orig_termios = tty->orig_termios;
+      orig_termios_fd = fd;
+    }
+    uv_spinlock_unlock(&termios_spinlock);
+  }
+
+  tmp = tty->orig_termios;
+  switch (mode) {
+    case UV_TTY_MODE_NORMAL:
+      break;
+    case UV_TTY_MODE_RAW:
+      tmp.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+      tmp.c_oflag |= (ONLCR);
+      tmp.c_cflag |= (CS8);
+      tmp.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+      tmp.c_cc[VMIN] = 1;
+      tmp.c_cc[VTIME] = 0;
+      break;
+    case UV_TTY_MODE_IO:
+      uv__tty_make_raw(&tmp);
+      break;
+  }
+
+  /* Apply changes after draining */
+  if (tcsetattr(fd, TCSADRAIN, &tmp))
+    return -errno;
+
+  tty->mode = mode;
+  return 0;
+}
+
+
+int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
+  struct winsize ws;
+  int err;
+
+  do
+    err = ioctl(uv__stream_fd(tty), TIOCGWINSZ, &ws);
+  while (err == -1 && errno == EINTR);
+
+  if (err == -1)
+    return -errno;
+
+  *width = ws.ws_col;
+  *height = ws.ws_row;
+
+  return 0;
+}
+
+
+uv_handle_type uv_guess_handle(uv_file file) {
+  struct sockaddr sa;
+  struct stat s;
+  socklen_t len;
+  int type;
+
+  if (file < 0)
+    return UV_UNKNOWN_HANDLE;
+
+  if (isatty(file))
+    return UV_TTY;
+
+  if (fstat(file, &s))
+    return UV_UNKNOWN_HANDLE;
+
+  if (S_ISREG(s.st_mode))
+    return UV_FILE;
+
+  if (S_ISCHR(s.st_mode))
+    return UV_FILE;  /* XXX UV_NAMED_PIPE? */
+
+  if (S_ISFIFO(s.st_mode))
+    return UV_NAMED_PIPE;
+
+  if (!S_ISSOCK(s.st_mode))
+    return UV_UNKNOWN_HANDLE;
+
+  len = sizeof(type);
+  if (getsockopt(file, SOL_SOCKET, SO_TYPE, &type, &len))
+    return UV_UNKNOWN_HANDLE;
+
+  len = sizeof(sa);
+  if (getsockname(file, &sa, &len))
+    return UV_UNKNOWN_HANDLE;
+
+  if (type == SOCK_DGRAM)
+    if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
+      return UV_UDP;
+
+  if (type == SOCK_STREAM) {
+#if defined(_AIX) || defined(__DragonFly__)
+    /* on AIX/DragonFly the getsockname call returns an empty sa structure
+     * for sockets of type AF_UNIX.  For all other types it will
+     * return a properly filled in structure.
+     */
+    if (len == 0)
+      return UV_NAMED_PIPE;
+#endif /* defined(_AIX) || defined(__DragonFly__) */
+
+    if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
+      return UV_TCP;
+    if (sa.sa_family == AF_UNIX)
+      return UV_NAMED_PIPE;
+  }
+
+  return UV_UNKNOWN_HANDLE;
+}
+
+
+/* This function is async signal-safe, meaning that it's safe to call from
+ * inside a signal handler _unless_ execution was inside uv_tty_set_mode()'s
+ * critical section when the signal was raised.
+ */
+int uv_tty_reset_mode(void) {
+  int saved_errno;
+  int err;
+
+  saved_errno = errno;
+  if (!uv_spinlock_trylock(&termios_spinlock))
+    return -EBUSY;  /* In uv_tty_set_mode(). */
+
+  err = 0;
+  if (orig_termios_fd != -1)
+    if (tcsetattr(orig_termios_fd, TCSANOW, &orig_termios))
+      err = -errno;
+
+  uv_spinlock_unlock(&termios_spinlock);
+  errno = saved_errno;
+
+  return err;
+}
diff --git a/Utilities/cmlibuv/src/unix/udp.c b/Utilities/cmlibuv/src/unix/udp.c
new file mode 100644
index 0000000..1cd4925
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/udp.c
@@ -0,0 +1,895 @@
+/* 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 "internal.h"
+
+#include <assert.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+#if defined(__MVS__)
+#include <xti.h>
+#endif
+
+#if defined(IPV6_JOIN_GROUP) && !defined(IPV6_ADD_MEMBERSHIP)
+# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
+#endif
+
+#if defined(IPV6_LEAVE_GROUP) && !defined(IPV6_DROP_MEMBERSHIP)
+# define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
+#endif
+
+
+static void uv__udp_run_completed(uv_udp_t* handle);
+static void uv__udp_io(uv_loop_t* loop, uv__io_t* w, unsigned int revents);
+static void uv__udp_recvmsg(uv_udp_t* handle);
+static void uv__udp_sendmsg(uv_udp_t* handle);
+static int uv__udp_maybe_deferred_bind(uv_udp_t* handle,
+                                       int domain,
+                                       unsigned int flags);
+
+
+void uv__udp_close(uv_udp_t* handle) {
+  uv__io_close(handle->loop, &handle->io_watcher);
+  uv__handle_stop(handle);
+
+  if (handle->io_watcher.fd != -1) {
+    uv__close(handle->io_watcher.fd);
+    handle->io_watcher.fd = -1;
+  }
+}
+
+
+void uv__udp_finish_close(uv_udp_t* handle) {
+  uv_udp_send_t* req;
+  QUEUE* q;
+
+  assert(!uv__io_active(&handle->io_watcher, POLLIN | POLLOUT));
+  assert(handle->io_watcher.fd == -1);
+
+  while (!QUEUE_EMPTY(&handle->write_queue)) {
+    q = QUEUE_HEAD(&handle->write_queue);
+    QUEUE_REMOVE(q);
+
+    req = QUEUE_DATA(q, uv_udp_send_t, queue);
+    req->status = -ECANCELED;
+    QUEUE_INSERT_TAIL(&handle->write_completed_queue, &req->queue);
+  }
+
+  uv__udp_run_completed(handle);
+
+  assert(handle->send_queue_size == 0);
+  assert(handle->send_queue_count == 0);
+
+  /* Now tear down the handle. */
+  handle->recv_cb = NULL;
+  handle->alloc_cb = NULL;
+  /* but _do not_ touch close_cb */
+}
+
+
+static void uv__udp_run_completed(uv_udp_t* handle) {
+  uv_udp_send_t* req;
+  QUEUE* q;
+
+  assert(!(handle->flags & UV_UDP_PROCESSING));
+  handle->flags |= UV_UDP_PROCESSING;
+
+  while (!QUEUE_EMPTY(&handle->write_completed_queue)) {
+    q = QUEUE_HEAD(&handle->write_completed_queue);
+    QUEUE_REMOVE(q);
+
+    req = QUEUE_DATA(q, uv_udp_send_t, queue);
+    uv__req_unregister(handle->loop, req);
+
+    handle->send_queue_size -= uv__count_bufs(req->bufs, req->nbufs);
+    handle->send_queue_count--;
+
+    if (req->bufs != req->bufsml)
+      uv__free(req->bufs);
+    req->bufs = NULL;
+
+    if (req->send_cb == NULL)
+      continue;
+
+    /* req->status >= 0 == bytes written
+     * req->status <  0 == errno
+     */
+    if (req->status >= 0)
+      req->send_cb(req, 0);
+    else
+      req->send_cb(req, req->status);
+  }
+
+  if (QUEUE_EMPTY(&handle->write_queue)) {
+    /* Pending queue and completion queue empty, stop watcher. */
+    uv__io_stop(handle->loop, &handle->io_watcher, POLLOUT);
+    if (!uv__io_active(&handle->io_watcher, POLLIN))
+      uv__handle_stop(handle);
+  }
+
+  handle->flags &= ~UV_UDP_PROCESSING;
+}
+
+
+static void uv__udp_io(uv_loop_t* loop, uv__io_t* w, unsigned int revents) {
+  uv_udp_t* handle;
+
+  handle = container_of(w, uv_udp_t, io_watcher);
+  assert(handle->type == UV_UDP);
+
+  if (revents & POLLIN)
+    uv__udp_recvmsg(handle);
+
+  if (revents & POLLOUT) {
+    uv__udp_sendmsg(handle);
+    uv__udp_run_completed(handle);
+  }
+}
+
+
+static void uv__udp_recvmsg(uv_udp_t* handle) {
+  struct sockaddr_storage peer;
+  struct msghdr h;
+  ssize_t nread;
+  uv_buf_t buf;
+  int flags;
+  int count;
+
+  assert(handle->recv_cb != NULL);
+  assert(handle->alloc_cb != NULL);
+
+  /* Prevent loop starvation when the data comes in as fast as (or faster than)
+   * we can read it. XXX Need to rearm fd if we switch to edge-triggered I/O.
+   */
+  count = 32;
+
+  memset(&h, 0, sizeof(h));
+  h.msg_name = &peer;
+
+  do {
+    buf = uv_buf_init(NULL, 0);
+    handle->alloc_cb((uv_handle_t*) handle, 64 * 1024, &buf);
+    if (buf.base == NULL || buf.len == 0) {
+      handle->recv_cb(handle, UV_ENOBUFS, &buf, NULL, 0);
+      return;
+    }
+    assert(buf.base != NULL);
+
+    h.msg_namelen = sizeof(peer);
+    h.msg_iov = (void*) &buf;
+    h.msg_iovlen = 1;
+
+    do {
+      nread = recvmsg(handle->io_watcher.fd, &h, 0);
+    }
+    while (nread == -1 && errno == EINTR);
+
+    if (nread == -1) {
+      if (errno == EAGAIN || errno == EWOULDBLOCK)
+        handle->recv_cb(handle, 0, &buf, NULL, 0);
+      else
+        handle->recv_cb(handle, -errno, &buf, NULL, 0);
+    }
+    else {
+      const struct sockaddr *addr;
+      if (h.msg_namelen == 0)
+        addr = NULL;
+      else
+        addr = (const struct sockaddr*) &peer;
+
+      flags = 0;
+      if (h.msg_flags & MSG_TRUNC)
+        flags |= UV_UDP_PARTIAL;
+
+      handle->recv_cb(handle, nread, &buf, addr, flags);
+    }
+  }
+  /* recv_cb callback may decide to pause or close the handle */
+  while (nread != -1
+      && count-- > 0
+      && handle->io_watcher.fd != -1
+      && handle->recv_cb != NULL);
+}
+
+
+static void uv__udp_sendmsg(uv_udp_t* handle) {
+  uv_udp_send_t* req;
+  QUEUE* q;
+  struct msghdr h;
+  ssize_t size;
+
+  while (!QUEUE_EMPTY(&handle->write_queue)) {
+    q = QUEUE_HEAD(&handle->write_queue);
+    assert(q != NULL);
+
+    req = QUEUE_DATA(q, uv_udp_send_t, queue);
+    assert(req != NULL);
+
+    memset(&h, 0, sizeof h);
+    h.msg_name = &req->addr;
+    h.msg_namelen = (req->addr.ss_family == AF_INET6 ?
+      sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
+    h.msg_iov = (struct iovec*) req->bufs;
+    h.msg_iovlen = req->nbufs;
+
+    do {
+      size = sendmsg(handle->io_watcher.fd, &h, 0);
+    } while (size == -1 && errno == EINTR);
+
+    if (size == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
+      break;
+
+    req->status = (size == -1 ? -errno : size);
+
+    /* Sending a datagram is an atomic operation: either all data
+     * is written or nothing is (and EMSGSIZE is raised). That is
+     * why we don't handle partial writes. Just pop the request
+     * off the write queue and onto the completed queue, done.
+     */
+    QUEUE_REMOVE(&req->queue);
+    QUEUE_INSERT_TAIL(&handle->write_completed_queue, &req->queue);
+    uv__io_feed(handle->loop, &handle->io_watcher);
+  }
+}
+
+
+/* On the BSDs, SO_REUSEPORT implies SO_REUSEADDR but with some additional
+ * refinements for programs that use multicast.
+ *
+ * Linux as of 3.9 has a SO_REUSEPORT socket option but with semantics that
+ * are different from the BSDs: it _shares_ the port rather than steal it
+ * from the current listener.  While useful, it's not something we can emulate
+ * on other platforms so we don't enable it.
+ */
+static int uv__set_reuse(int fd) {
+  int yes;
+
+#if defined(SO_REUSEPORT) && !defined(__linux__)
+  yes = 1;
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)))
+    return -errno;
+#else
+  yes = 1;
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)))
+    return -errno;
+#endif
+
+  return 0;
+}
+
+
+int uv__udp_bind(uv_udp_t* handle,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 unsigned int flags) {
+  int err;
+  int yes;
+  int fd;
+
+  /* Check for bad flags. */
+  if (flags & ~(UV_UDP_IPV6ONLY | UV_UDP_REUSEADDR))
+    return -EINVAL;
+
+  /* Cannot set IPv6-only mode on non-IPv6 socket. */
+  if ((flags & UV_UDP_IPV6ONLY) && addr->sa_family != AF_INET6)
+    return -EINVAL;
+
+  fd = handle->io_watcher.fd;
+  if (fd == -1) {
+    err = uv__socket(addr->sa_family, SOCK_DGRAM, 0);
+    if (err < 0)
+      return err;
+    fd = err;
+    handle->io_watcher.fd = fd;
+  }
+
+  if (flags & UV_UDP_REUSEADDR) {
+    err = uv__set_reuse(fd);
+    if (err)
+      goto out;
+  }
+
+  if (flags & UV_UDP_IPV6ONLY) {
+#ifdef IPV6_V6ONLY
+    yes = 1;
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof yes) == -1) {
+      err = -errno;
+      goto out;
+    }
+#else
+    err = -ENOTSUP;
+    goto out;
+#endif
+  }
+
+  if (bind(fd, addr, addrlen)) {
+    err = -errno;
+    if (errno == EAFNOSUPPORT)
+      /* OSX, other BSDs and SunoS fail with EAFNOSUPPORT when binding a
+       * socket created with AF_INET to an AF_INET6 address or vice versa. */
+      err = -EINVAL;
+    goto out;
+  }
+
+  if (addr->sa_family == AF_INET6)
+    handle->flags |= UV_HANDLE_IPV6;
+
+  handle->flags |= UV_HANDLE_BOUND;
+
+  return 0;
+
+out:
+  uv__close(handle->io_watcher.fd);
+  handle->io_watcher.fd = -1;
+  return err;
+}
+
+
+static int uv__udp_maybe_deferred_bind(uv_udp_t* handle,
+                                       int domain,
+                                       unsigned int flags) {
+  unsigned char taddr[sizeof(struct sockaddr_in6)];
+  socklen_t addrlen;
+
+  if (handle->io_watcher.fd != -1)
+    return 0;
+
+  switch (domain) {
+  case AF_INET:
+  {
+    struct sockaddr_in* addr = (void*)&taddr;
+    memset(addr, 0, sizeof *addr);
+    addr->sin_family = AF_INET;
+    addr->sin_addr.s_addr = INADDR_ANY;
+    addrlen = sizeof *addr;
+    break;
+  }
+  case AF_INET6:
+  {
+    struct sockaddr_in6* addr = (void*)&taddr;
+    memset(addr, 0, sizeof *addr);
+    addr->sin6_family = AF_INET6;
+    addr->sin6_addr = in6addr_any;
+    addrlen = sizeof *addr;
+    break;
+  }
+  default:
+    assert(0 && "unsupported address family");
+    abort();
+  }
+
+  return uv__udp_bind(handle, (const struct sockaddr*) &taddr, addrlen, flags);
+}
+
+
+int uv__udp_send(uv_udp_send_t* req,
+                 uv_udp_t* handle,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 uv_udp_send_cb send_cb) {
+  int err;
+  int empty_queue;
+
+  assert(nbufs > 0);
+
+  err = uv__udp_maybe_deferred_bind(handle, addr->sa_family, 0);
+  if (err)
+    return err;
+
+  /* It's legal for send_queue_count > 0 even when the write_queue is empty;
+   * it means there are error-state requests in the write_completed_queue that
+   * will touch up send_queue_size/count later.
+   */
+  empty_queue = (handle->send_queue_count == 0);
+
+  uv__req_init(handle->loop, req, UV_UDP_SEND);
+  assert(addrlen <= sizeof(req->addr));
+  memcpy(&req->addr, addr, addrlen);
+  req->send_cb = send_cb;
+  req->handle = handle;
+  req->nbufs = nbufs;
+
+  req->bufs = req->bufsml;
+  if (nbufs > ARRAY_SIZE(req->bufsml))
+    req->bufs = uv__malloc(nbufs * sizeof(bufs[0]));
+
+  if (req->bufs == NULL) {
+    uv__req_unregister(handle->loop, req);
+    return -ENOMEM;
+  }
+
+  memcpy(req->bufs, bufs, nbufs * sizeof(bufs[0]));
+  handle->send_queue_size += uv__count_bufs(req->bufs, req->nbufs);
+  handle->send_queue_count++;
+  QUEUE_INSERT_TAIL(&handle->write_queue, &req->queue);
+  uv__handle_start(handle);
+
+  if (empty_queue && !(handle->flags & UV_UDP_PROCESSING)) {
+    uv__udp_sendmsg(handle);
+  } else {
+    uv__io_start(handle->loop, &handle->io_watcher, POLLOUT);
+  }
+
+  return 0;
+}
+
+
+int uv__udp_try_send(uv_udp_t* handle,
+                     const uv_buf_t bufs[],
+                     unsigned int nbufs,
+                     const struct sockaddr* addr,
+                     unsigned int addrlen) {
+  int err;
+  struct msghdr h;
+  ssize_t size;
+
+  assert(nbufs > 0);
+
+  /* already sending a message */
+  if (handle->send_queue_count != 0)
+    return -EAGAIN;
+
+  err = uv__udp_maybe_deferred_bind(handle, addr->sa_family, 0);
+  if (err)
+    return err;
+
+  memset(&h, 0, sizeof h);
+  h.msg_name = (struct sockaddr*) addr;
+  h.msg_namelen = addrlen;
+  h.msg_iov = (struct iovec*) bufs;
+  h.msg_iovlen = nbufs;
+
+  do {
+    size = sendmsg(handle->io_watcher.fd, &h, 0);
+  } while (size == -1 && errno == EINTR);
+
+  if (size == -1) {
+    if (errno == EAGAIN || errno == EWOULDBLOCK)
+      return -EAGAIN;
+    else
+      return -errno;
+  }
+
+  return size;
+}
+
+
+static int uv__udp_set_membership4(uv_udp_t* handle,
+                                   const struct sockaddr_in* multicast_addr,
+                                   const char* interface_addr,
+                                   uv_membership membership) {
+  struct ip_mreq mreq;
+  int optname;
+  int err;
+
+  memset(&mreq, 0, sizeof mreq);
+
+  if (interface_addr) {
+    err = uv_inet_pton(AF_INET, interface_addr, &mreq.imr_interface.s_addr);
+    if (err)
+      return err;
+  } else {
+    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
+  }
+
+  mreq.imr_multiaddr.s_addr = multicast_addr->sin_addr.s_addr;
+
+  switch (membership) {
+  case UV_JOIN_GROUP:
+    optname = IP_ADD_MEMBERSHIP;
+    break;
+  case UV_LEAVE_GROUP:
+    optname = IP_DROP_MEMBERSHIP;
+    break;
+  default:
+    return -EINVAL;
+  }
+
+  if (setsockopt(handle->io_watcher.fd,
+                 IPPROTO_IP,
+                 optname,
+                 &mreq,
+                 sizeof(mreq))) {
+#if defined(__MVS__)
+  if (errno == ENXIO)
+    return -ENODEV;
+#endif
+    return -errno;
+  }
+
+  return 0;
+}
+
+
+static int uv__udp_set_membership6(uv_udp_t* handle,
+                                   const struct sockaddr_in6* multicast_addr,
+                                   const char* interface_addr,
+                                   uv_membership membership) {
+  int optname;
+  struct ipv6_mreq mreq;
+  struct sockaddr_in6 addr6;
+
+  memset(&mreq, 0, sizeof mreq);
+
+  if (interface_addr) {
+    if (uv_ip6_addr(interface_addr, 0, &addr6))
+      return -EINVAL;
+    mreq.ipv6mr_interface = addr6.sin6_scope_id;
+  } else {
+    mreq.ipv6mr_interface = 0;
+  }
+
+  mreq.ipv6mr_multiaddr = multicast_addr->sin6_addr;
+
+  switch (membership) {
+  case UV_JOIN_GROUP:
+    optname = IPV6_ADD_MEMBERSHIP;
+    break;
+  case UV_LEAVE_GROUP:
+    optname = IPV6_DROP_MEMBERSHIP;
+    break;
+  default:
+    return -EINVAL;
+  }
+
+  if (setsockopt(handle->io_watcher.fd,
+                 IPPROTO_IPV6,
+                 optname,
+                 &mreq,
+                 sizeof(mreq))) {
+#if defined(__MVS__)
+  if (errno == ENXIO)
+    return -ENODEV;
+#endif
+    return -errno;
+  }
+
+  return 0;
+}
+
+
+int uv_udp_init_ex(uv_loop_t* loop, uv_udp_t* handle, unsigned int flags) {
+  int domain;
+  int err;
+  int fd;
+
+  /* Use the lower 8 bits for the domain */
+  domain = flags & 0xFF;
+  if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNSPEC)
+    return -EINVAL;
+
+  if (flags & ~0xFF)
+    return -EINVAL;
+
+  if (domain != AF_UNSPEC) {
+    err = uv__socket(domain, SOCK_DGRAM, 0);
+    if (err < 0)
+      return err;
+    fd = err;
+  } else {
+    fd = -1;
+  }
+
+  uv__handle_init(loop, (uv_handle_t*)handle, UV_UDP);
+  handle->alloc_cb = NULL;
+  handle->recv_cb = NULL;
+  handle->send_queue_size = 0;
+  handle->send_queue_count = 0;
+  uv__io_init(&handle->io_watcher, uv__udp_io, fd);
+  QUEUE_INIT(&handle->write_queue);
+  QUEUE_INIT(&handle->write_completed_queue);
+  return 0;
+}
+
+
+int uv_udp_init(uv_loop_t* loop, uv_udp_t* handle) {
+  return uv_udp_init_ex(loop, handle, AF_UNSPEC);
+}
+
+
+int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock) {
+  int err;
+
+  /* Check for already active socket. */
+  if (handle->io_watcher.fd != -1)
+    return -EBUSY;
+
+  err = uv__nonblock(sock, 1);
+  if (err)
+    return err;
+
+  err = uv__set_reuse(sock);
+  if (err)
+    return err;
+
+  handle->io_watcher.fd = sock;
+  return 0;
+}
+
+
+int uv_udp_set_membership(uv_udp_t* handle,
+                          const char* multicast_addr,
+                          const char* interface_addr,
+                          uv_membership membership) {
+  int err;
+  struct sockaddr_in addr4;
+  struct sockaddr_in6 addr6;
+
+  if (uv_ip4_addr(multicast_addr, 0, &addr4) == 0) {
+    err = uv__udp_maybe_deferred_bind(handle, AF_INET, UV_UDP_REUSEADDR);
+    if (err)
+      return err;
+    return uv__udp_set_membership4(handle, &addr4, interface_addr, membership);
+  } else if (uv_ip6_addr(multicast_addr, 0, &addr6) == 0) {
+    err = uv__udp_maybe_deferred_bind(handle, AF_INET6, UV_UDP_REUSEADDR);
+    if (err)
+      return err;
+    return uv__udp_set_membership6(handle, &addr6, interface_addr, membership);
+  } else {
+    return -EINVAL;
+  }
+}
+
+static int uv__setsockopt(uv_udp_t* handle,
+                         int option4,
+                         int option6,
+                         const void* val,
+                         size_t size) {
+  int r;
+
+  if (handle->flags & UV_HANDLE_IPV6)
+    r = setsockopt(handle->io_watcher.fd,
+                   IPPROTO_IPV6,
+                   option6,
+                   val,
+                   size);
+  else
+    r = setsockopt(handle->io_watcher.fd,
+                   IPPROTO_IP,
+                   option4,
+                   val,
+                   size);
+  if (r)
+    return -errno;
+
+  return 0;
+}
+
+static int uv__setsockopt_maybe_char(uv_udp_t* handle,
+                                     int option4,
+                                     int option6,
+                                     int val) {
+#if defined(__sun) || defined(_AIX) || defined(__MVS__)
+  char arg = val;
+#elif defined(__OpenBSD__)
+  unsigned char arg = val;
+#else
+  int arg = val;
+#endif
+
+  if (val < 0 || val > 255)
+    return -EINVAL;
+
+  return uv__setsockopt(handle, option4, option6, &arg, sizeof(arg));
+}
+
+
+int uv_udp_set_broadcast(uv_udp_t* handle, int on) {
+  if (setsockopt(handle->io_watcher.fd,
+                 SOL_SOCKET,
+                 SO_BROADCAST,
+                 &on,
+                 sizeof(on))) {
+    return -errno;
+  }
+
+  return 0;
+}
+
+
+int uv_udp_set_ttl(uv_udp_t* handle, int ttl) {
+  if (ttl < 1 || ttl > 255)
+    return -EINVAL;
+
+#if defined(__MVS__)
+  if (!(handle->flags & UV_HANDLE_IPV6))
+    return -ENOTSUP;  /* zOS does not support setting ttl for IPv4 */
+#endif
+
+/*
+ * On Solaris and derivatives such as SmartOS, the length of socket options
+ * is sizeof(int) for IP_TTL and IPV6_UNICAST_HOPS,
+ * so hardcode the size of these options on this platform,
+ * and use the general uv__setsockopt_maybe_char call on other platforms.
+ */
+#if defined(__sun) || defined(_AIX) || defined(__OpenBSD__) || \
+    defined(__MVS__)
+
+  return uv__setsockopt(handle,
+                        IP_TTL,
+                        IPV6_UNICAST_HOPS,
+                        &ttl,
+                        sizeof(ttl));
+#endif /* defined(__sun) || defined(_AIX) || defined (__OpenBSD__) ||
+          defined(__MVS__) */
+
+  return uv__setsockopt_maybe_char(handle,
+                                   IP_TTL,
+                                   IPV6_UNICAST_HOPS,
+                                   ttl);
+}
+
+
+int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) {
+/*
+ * On Solaris and derivatives such as SmartOS, the length of socket options
+ * is sizeof(int) for IPV6_MULTICAST_HOPS and sizeof(char) for
+ * IP_MULTICAST_TTL, so hardcode the size of the option in the IPv6 case,
+ * and use the general uv__setsockopt_maybe_char call otherwise.
+ */
+#if defined(__sun) || defined(_AIX) || defined(__MVS__)
+  if (handle->flags & UV_HANDLE_IPV6)
+    return uv__setsockopt(handle,
+                          IP_MULTICAST_TTL,
+                          IPV6_MULTICAST_HOPS,
+                          &ttl,
+                          sizeof(ttl));
+#endif /* defined(__sun) || defined(_AIX) || defined(__MVS__) */
+
+  return uv__setsockopt_maybe_char(handle,
+                                   IP_MULTICAST_TTL,
+                                   IPV6_MULTICAST_HOPS,
+                                   ttl);
+}
+
+
+int uv_udp_set_multicast_loop(uv_udp_t* handle, int on) {
+/*
+ * On Solaris and derivatives such as SmartOS, the length of socket options
+ * is sizeof(int) for IPV6_MULTICAST_LOOP and sizeof(char) for
+ * IP_MULTICAST_LOOP, so hardcode the size of the option in the IPv6 case,
+ * and use the general uv__setsockopt_maybe_char call otherwise.
+ */
+#if defined(__sun) || defined(_AIX) || defined(__MVS__)
+  if (handle->flags & UV_HANDLE_IPV6)
+    return uv__setsockopt(handle,
+                          IP_MULTICAST_LOOP,
+                          IPV6_MULTICAST_LOOP,
+                          &on,
+                          sizeof(on));
+#endif /* defined(__sun) || defined(_AIX) || defined(__MVS__) */
+
+  return uv__setsockopt_maybe_char(handle,
+                                   IP_MULTICAST_LOOP,
+                                   IPV6_MULTICAST_LOOP,
+                                   on);
+}
+
+int uv_udp_set_multicast_interface(uv_udp_t* handle, const char* interface_addr) {
+  struct sockaddr_storage addr_st;
+  struct sockaddr_in* addr4;
+  struct sockaddr_in6* addr6;
+
+  addr4 = (struct sockaddr_in*) &addr_st;
+  addr6 = (struct sockaddr_in6*) &addr_st;
+
+  if (!interface_addr) {
+    memset(&addr_st, 0, sizeof addr_st);
+    if (handle->flags & UV_HANDLE_IPV6) {
+      addr_st.ss_family = AF_INET6;
+      addr6->sin6_scope_id = 0;
+    } else {
+      addr_st.ss_family = AF_INET;
+      addr4->sin_addr.s_addr = htonl(INADDR_ANY);
+    }
+  } else if (uv_ip4_addr(interface_addr, 0, addr4) == 0) {
+    /* nothing, address was parsed */
+  } else if (uv_ip6_addr(interface_addr, 0, addr6) == 0) {
+    /* nothing, address was parsed */
+  } else {
+    return -EINVAL;
+  }
+
+  if (addr_st.ss_family == AF_INET) {
+    if (setsockopt(handle->io_watcher.fd,
+                   IPPROTO_IP,
+                   IP_MULTICAST_IF,
+                   (void*) &addr4->sin_addr,
+                   sizeof(addr4->sin_addr)) == -1) {
+      return -errno;
+    }
+  } else if (addr_st.ss_family == AF_INET6) {
+    if (setsockopt(handle->io_watcher.fd,
+                   IPPROTO_IPV6,
+                   IPV6_MULTICAST_IF,
+                   &addr6->sin6_scope_id,
+                   sizeof(addr6->sin6_scope_id)) == -1) {
+      return -errno;
+    }
+  } else {
+    assert(0 && "unexpected address family");
+    abort();
+  }
+
+  return 0;
+}
+
+
+int uv_udp_getsockname(const uv_udp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  socklen_t socklen;
+
+  if (handle->io_watcher.fd == -1)
+    return -EINVAL;  /* FIXME(bnoordhuis) -EBADF */
+
+  /* sizeof(socklen_t) != sizeof(int) on some systems. */
+  socklen = (socklen_t) *namelen;
+
+  if (getsockname(handle->io_watcher.fd, name, &socklen))
+    return -errno;
+
+  *namelen = (int) socklen;
+  return 0;
+}
+
+
+int uv__udp_recv_start(uv_udp_t* handle,
+                       uv_alloc_cb alloc_cb,
+                       uv_udp_recv_cb recv_cb) {
+  int err;
+
+  if (alloc_cb == NULL || recv_cb == NULL)
+    return -EINVAL;
+
+  if (uv__io_active(&handle->io_watcher, POLLIN))
+    return -EALREADY;  /* FIXME(bnoordhuis) Should be -EBUSY. */
+
+  err = uv__udp_maybe_deferred_bind(handle, AF_INET, 0);
+  if (err)
+    return err;
+
+  handle->alloc_cb = alloc_cb;
+  handle->recv_cb = recv_cb;
+
+  uv__io_start(handle->loop, &handle->io_watcher, POLLIN);
+  uv__handle_start(handle);
+
+  return 0;
+}
+
+
+int uv__udp_recv_stop(uv_udp_t* handle) {
+  uv__io_stop(handle->loop, &handle->io_watcher, POLLIN);
+
+  if (!uv__io_active(&handle->io_watcher, POLLOUT))
+    uv__handle_stop(handle);
+
+  handle->alloc_cb = NULL;
+  handle->recv_cb = NULL;
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/uv-common.c b/Utilities/cmlibuv/src/uv-common.c
new file mode 100644
index 0000000..46d9546
--- /dev/null
+++ b/Utilities/cmlibuv/src/uv-common.c
@@ -0,0 +1,654 @@
+/* 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 <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stddef.h> /* NULL */
+#include <stdio.h>
+#include <stdlib.h> /* malloc */
+#include <string.h> /* memset */
+
+#if defined(_WIN32)
+# include <malloc.h> /* malloc */
+#else
+# include <net/if.h> /* if_nametoindex */
+#endif
+
+
+typedef struct {
+  uv_malloc_func local_malloc;
+  uv_realloc_func local_realloc;
+  uv_calloc_func local_calloc;
+  uv_free_func local_free;
+} uv__allocator_t;
+
+static uv__allocator_t uv__allocator = {
+  malloc,
+  realloc,
+  calloc,
+  free,
+};
+
+char* uv__strdup(const char* s) {
+  size_t len = strlen(s) + 1;
+  char* m = uv__malloc(len);
+  if (m == NULL)
+    return NULL;
+  return memcpy(m, s, len);
+}
+
+char* uv__strndup(const char* s, size_t n) {
+  char* m;
+  size_t len = strlen(s);
+  if (n < len)
+    len = n;
+  m = uv__malloc(len + 1);
+  if (m == NULL)
+    return NULL;
+  m[len] = '\0';
+  return memcpy(m, s, len);
+}
+
+void* uv__malloc(size_t size) {
+  return uv__allocator.local_malloc(size);
+}
+
+void uv__free(void* ptr) {
+  int saved_errno;
+
+  /* Libuv expects that free() does not clobber errno.  The system allocator
+   * honors that assumption but custom allocators may not be so careful.
+   */
+  saved_errno = errno;
+  uv__allocator.local_free(ptr);
+  errno = saved_errno;
+}
+
+void* uv__calloc(size_t count, size_t size) {
+  return uv__allocator.local_calloc(count, size);
+}
+
+void* uv__realloc(void* ptr, size_t size) {
+  return uv__allocator.local_realloc(ptr, size);
+}
+
+int uv_replace_allocator(uv_malloc_func malloc_func,
+                         uv_realloc_func realloc_func,
+                         uv_calloc_func calloc_func,
+                         uv_free_func free_func) {
+  if (malloc_func == NULL || realloc_func == NULL ||
+      calloc_func == NULL || free_func == NULL) {
+    return UV_EINVAL;
+  }
+
+  uv__allocator.local_malloc = malloc_func;
+  uv__allocator.local_realloc = realloc_func;
+  uv__allocator.local_calloc = calloc_func;
+  uv__allocator.local_free = free_func;
+
+  return 0;
+}
+
+#define XX(uc, lc) case UV_##uc: return sizeof(uv_##lc##_t);
+
+size_t uv_handle_size(uv_handle_type type) {
+  switch (type) {
+    UV_HANDLE_TYPE_MAP(XX)
+    default:
+      return -1;
+  }
+}
+
+size_t uv_req_size(uv_req_type type) {
+  switch(type) {
+    UV_REQ_TYPE_MAP(XX)
+    default:
+      return -1;
+  }
+}
+
+#undef XX
+
+
+size_t uv_loop_size(void) {
+  return sizeof(uv_loop_t);
+}
+
+
+uv_buf_t uv_buf_init(char* base, unsigned int len) {
+  uv_buf_t buf;
+  buf.base = base;
+  buf.len = len;
+  return buf;
+}
+
+
+static const char* uv__unknown_err_code(int err) {
+  char buf[32];
+  char* copy;
+
+  snprintf(buf, sizeof(buf), "Unknown system error %d", err);
+  copy = uv__strdup(buf);
+
+  return copy != NULL ? copy : "Unknown system error";
+}
+
+
+#define UV_ERR_NAME_GEN(name, _) case UV_ ## name: return #name;
+const char* uv_err_name(int err) {
+  switch (err) {
+    UV_ERRNO_MAP(UV_ERR_NAME_GEN)
+  }
+  return uv__unknown_err_code(err);
+}
+#undef UV_ERR_NAME_GEN
+
+
+#define UV_STRERROR_GEN(name, msg) case UV_ ## name: return msg;
+const char* uv_strerror(int err) {
+  switch (err) {
+    UV_ERRNO_MAP(UV_STRERROR_GEN)
+  }
+  return uv__unknown_err_code(err);
+}
+#undef UV_STRERROR_GEN
+
+
+int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr) {
+  memset(addr, 0, sizeof(*addr));
+  addr->sin_family = AF_INET;
+  addr->sin_port = htons(port);
+  return uv_inet_pton(AF_INET, ip, &(addr->sin_addr.s_addr));
+}
+
+
+int uv_ip6_addr(const char* ip, int port, struct sockaddr_in6* addr) {
+  char address_part[40];
+  size_t address_part_size;
+  const char* zone_index;
+
+  memset(addr, 0, sizeof(*addr));
+  addr->sin6_family = AF_INET6;
+  addr->sin6_port = htons(port);
+
+  zone_index = strchr(ip, '%');
+  if (zone_index != NULL) {
+    address_part_size = zone_index - ip;
+    if (address_part_size >= sizeof(address_part))
+      address_part_size = sizeof(address_part) - 1;
+
+    memcpy(address_part, ip, address_part_size);
+    address_part[address_part_size] = '\0';
+    ip = address_part;
+
+    zone_index++; /* skip '%' */
+    /* NOTE: unknown interface (id=0) is silently ignored */
+#ifdef _WIN32
+    addr->sin6_scope_id = atoi(zone_index);
+#else
+    addr->sin6_scope_id = if_nametoindex(zone_index);
+#endif
+  }
+
+  return uv_inet_pton(AF_INET6, ip, &addr->sin6_addr);
+}
+
+
+int uv_ip4_name(const struct sockaddr_in* src, char* dst, size_t size) {
+  return uv_inet_ntop(AF_INET, &src->sin_addr, dst, size);
+}
+
+
+int uv_ip6_name(const struct sockaddr_in6* src, char* dst, size_t size) {
+  return uv_inet_ntop(AF_INET6, &src->sin6_addr, dst, size);
+}
+
+
+int uv_tcp_bind(uv_tcp_t* handle,
+                const struct sockaddr* addr,
+                unsigned int flags) {
+  unsigned int addrlen;
+
+  if (handle->type != UV_TCP)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET)
+    addrlen = sizeof(struct sockaddr_in);
+  else if (addr->sa_family == AF_INET6)
+    addrlen = sizeof(struct sockaddr_in6);
+  else
+    return UV_EINVAL;
+
+  return uv__tcp_bind(handle, addr, addrlen, flags);
+}
+
+
+int uv_udp_bind(uv_udp_t* handle,
+                const struct sockaddr* addr,
+                unsigned int flags) {
+  unsigned int addrlen;
+
+  if (handle->type != UV_UDP)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET)
+    addrlen = sizeof(struct sockaddr_in);
+  else if (addr->sa_family == AF_INET6)
+    addrlen = sizeof(struct sockaddr_in6);
+  else
+    return UV_EINVAL;
+
+  return uv__udp_bind(handle, addr, addrlen, flags);
+}
+
+
+int uv_tcp_connect(uv_connect_t* req,
+                   uv_tcp_t* handle,
+                   const struct sockaddr* addr,
+                   uv_connect_cb cb) {
+  unsigned int addrlen;
+
+  if (handle->type != UV_TCP)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET)
+    addrlen = sizeof(struct sockaddr_in);
+  else if (addr->sa_family == AF_INET6)
+    addrlen = sizeof(struct sockaddr_in6);
+  else
+    return UV_EINVAL;
+
+  return uv__tcp_connect(req, handle, addr, addrlen, cb);
+}
+
+
+int uv_udp_send(uv_udp_send_t* req,
+                uv_udp_t* handle,
+                const uv_buf_t bufs[],
+                unsigned int nbufs,
+                const struct sockaddr* addr,
+                uv_udp_send_cb send_cb) {
+  unsigned int addrlen;
+
+  if (handle->type != UV_UDP)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET)
+    addrlen = sizeof(struct sockaddr_in);
+  else if (addr->sa_family == AF_INET6)
+    addrlen = sizeof(struct sockaddr_in6);
+  else
+    return UV_EINVAL;
+
+  return uv__udp_send(req, handle, bufs, nbufs, addr, addrlen, send_cb);
+}
+
+
+int uv_udp_try_send(uv_udp_t* handle,
+                    const uv_buf_t bufs[],
+                    unsigned int nbufs,
+                    const struct sockaddr* addr) {
+  unsigned int addrlen;
+
+  if (handle->type != UV_UDP)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET)
+    addrlen = sizeof(struct sockaddr_in);
+  else if (addr->sa_family == AF_INET6)
+    addrlen = sizeof(struct sockaddr_in6);
+  else
+    return UV_EINVAL;
+
+  return uv__udp_try_send(handle, bufs, nbufs, addr, addrlen);
+}
+
+
+int uv_udp_recv_start(uv_udp_t* handle,
+                      uv_alloc_cb alloc_cb,
+                      uv_udp_recv_cb recv_cb) {
+  if (handle->type != UV_UDP || alloc_cb == NULL || recv_cb == NULL)
+    return UV_EINVAL;
+  else
+    return uv__udp_recv_start(handle, alloc_cb, recv_cb);
+}
+
+
+int uv_udp_recv_stop(uv_udp_t* handle) {
+  if (handle->type != UV_UDP)
+    return UV_EINVAL;
+  else
+    return uv__udp_recv_stop(handle);
+}
+
+
+void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg) {
+  QUEUE queue;
+  QUEUE* q;
+  uv_handle_t* h;
+
+  QUEUE_MOVE(&loop->handle_queue, &queue);
+  while (!QUEUE_EMPTY(&queue)) {
+    q = QUEUE_HEAD(&queue);
+    h = QUEUE_DATA(q, uv_handle_t, handle_queue);
+
+    QUEUE_REMOVE(q);
+    QUEUE_INSERT_TAIL(&loop->handle_queue, q);
+
+    if (h->flags & UV__HANDLE_INTERNAL) continue;
+    walk_cb(h, arg);
+  }
+}
+
+
+static void uv__print_handles(uv_loop_t* loop, int only_active, FILE* stream) {
+  const char* type;
+  QUEUE* q;
+  uv_handle_t* h;
+
+  if (loop == NULL)
+    loop = uv_default_loop();
+
+  QUEUE_FOREACH(q, &loop->handle_queue) {
+    h = QUEUE_DATA(q, uv_handle_t, handle_queue);
+
+    if (only_active && !uv__is_active(h))
+      continue;
+
+    switch (h->type) {
+#define X(uc, lc) case UV_##uc: type = #lc; break;
+      UV_HANDLE_TYPE_MAP(X)
+#undef X
+      default: type = "<unknown>";
+    }
+
+    fprintf(stream,
+            "[%c%c%c] %-8s %p\n",
+            "R-"[!(h->flags & UV__HANDLE_REF)],
+            "A-"[!(h->flags & UV__HANDLE_ACTIVE)],
+            "I-"[!(h->flags & UV__HANDLE_INTERNAL)],
+            type,
+            (void*)h);
+  }
+}
+
+
+void uv_print_all_handles(uv_loop_t* loop, FILE* stream) {
+  uv__print_handles(loop, 0, stream);
+}
+
+
+void uv_print_active_handles(uv_loop_t* loop, FILE* stream) {
+  uv__print_handles(loop, 1, stream);
+}
+
+
+void uv_ref(uv_handle_t* handle) {
+  uv__handle_ref(handle);
+}
+
+
+void uv_unref(uv_handle_t* handle) {
+  uv__handle_unref(handle);
+}
+
+
+int uv_has_ref(const uv_handle_t* handle) {
+  return uv__has_ref(handle);
+}
+
+
+void uv_stop(uv_loop_t* loop) {
+  loop->stop_flag = 1;
+}
+
+
+uint64_t uv_now(const uv_loop_t* loop) {
+  return loop->time;
+}
+
+
+
+size_t uv__count_bufs(const uv_buf_t bufs[], unsigned int nbufs) {
+  unsigned int i;
+  size_t bytes;
+
+  bytes = 0;
+  for (i = 0; i < nbufs; i++)
+    bytes += (size_t) bufs[i].len;
+
+  return bytes;
+}
+
+int uv_recv_buffer_size(uv_handle_t* handle, int* value) {
+  return uv__socket_sockopt(handle, SO_RCVBUF, value);
+}
+
+int uv_send_buffer_size(uv_handle_t* handle, int *value) {
+  return uv__socket_sockopt(handle, SO_SNDBUF, value);
+}
+
+int uv_fs_event_getpath(uv_fs_event_t* handle, char* buffer, size_t* size) {
+  size_t required_len;
+
+  if (!uv__is_active(handle)) {
+    *size = 0;
+    return UV_EINVAL;
+  }
+
+  required_len = strlen(handle->path);
+  if (required_len >= *size) {
+    *size = required_len + 1;
+    return UV_ENOBUFS;
+  }
+
+  memcpy(buffer, handle->path, required_len);
+  *size = required_len;
+  buffer[required_len] = '\0';
+
+  return 0;
+}
+
+/* The windows implementation does not have the same structure layout as
+ * the unix implementation (nbufs is not directly inside req but is
+ * contained in a nested union/struct) so this function locates it.
+*/
+static unsigned int* uv__get_nbufs(uv_fs_t* req) {
+#ifdef _WIN32
+  return &req->fs.info.nbufs;
+#else
+  return &req->nbufs;
+#endif
+}
+
+/* uv_fs_scandir() uses the system allocator to allocate memory on non-Windows
+ * systems. So, the memory should be released using free(). On Windows,
+ * uv__malloc() is used, so use uv__free() to free memory.
+*/
+#ifdef _WIN32
+# define uv__fs_scandir_free uv__free
+#else
+# define uv__fs_scandir_free free
+#endif
+
+void uv__fs_scandir_cleanup(uv_fs_t* req) {
+  uv__dirent_t** dents;
+
+  unsigned int* nbufs = uv__get_nbufs(req);
+
+  dents = req->ptr;
+  if (*nbufs > 0 && *nbufs != (unsigned int) req->result)
+    (*nbufs)--;
+  for (; *nbufs < (unsigned int) req->result; (*nbufs)++)
+    uv__fs_scandir_free(dents[*nbufs]);
+
+  uv__fs_scandir_free(req->ptr);
+  req->ptr = NULL;
+}
+
+
+int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) {
+  uv__dirent_t** dents;
+  uv__dirent_t* dent;
+
+  unsigned int* nbufs = uv__get_nbufs(req);
+
+  dents = req->ptr;
+
+  /* Free previous entity */
+  if (*nbufs > 0)
+    uv__fs_scandir_free(dents[*nbufs - 1]);
+
+  /* End was already reached */
+  if (*nbufs == (unsigned int) req->result) {
+    uv__fs_scandir_free(dents);
+    req->ptr = NULL;
+    return UV_EOF;
+  }
+
+  dent = dents[(*nbufs)++];
+
+  ent->name = dent->d_name;
+#ifdef HAVE_DIRENT_TYPES
+  switch (dent->d_type) {
+    case UV__DT_DIR:
+      ent->type = UV_DIRENT_DIR;
+      break;
+    case UV__DT_FILE:
+      ent->type = UV_DIRENT_FILE;
+      break;
+    case UV__DT_LINK:
+      ent->type = UV_DIRENT_LINK;
+      break;
+    case UV__DT_FIFO:
+      ent->type = UV_DIRENT_FIFO;
+      break;
+    case UV__DT_SOCKET:
+      ent->type = UV_DIRENT_SOCKET;
+      break;
+    case UV__DT_CHAR:
+      ent->type = UV_DIRENT_CHAR;
+      break;
+    case UV__DT_BLOCK:
+      ent->type = UV_DIRENT_BLOCK;
+      break;
+    default:
+      ent->type = UV_DIRENT_UNKNOWN;
+  }
+#else
+  ent->type = UV_DIRENT_UNKNOWN;
+#endif
+
+  return 0;
+}
+
+
+int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...) {
+  va_list ap;
+  int err;
+
+  va_start(ap, option);
+  /* Any platform-agnostic options should be handled here. */
+  err = uv__loop_configure(loop, option, ap);
+  va_end(ap);
+
+  return err;
+}
+
+
+static uv_loop_t default_loop_struct;
+static uv_loop_t* default_loop_ptr;
+
+
+uv_loop_t* uv_default_loop(void) {
+  if (default_loop_ptr != NULL)
+    return default_loop_ptr;
+
+  if (uv_loop_init(&default_loop_struct))
+    return NULL;
+
+  default_loop_ptr = &default_loop_struct;
+  return default_loop_ptr;
+}
+
+
+uv_loop_t* uv_loop_new(void) {
+  uv_loop_t* loop;
+
+  loop = uv__malloc(sizeof(*loop));
+  if (loop == NULL)
+    return NULL;
+
+  if (uv_loop_init(loop)) {
+    uv__free(loop);
+    return NULL;
+  }
+
+  return loop;
+}
+
+
+int uv_loop_close(uv_loop_t* loop) {
+  QUEUE* q;
+  uv_handle_t* h;
+#ifndef NDEBUG
+  void* saved_data;
+#endif
+
+  if (!QUEUE_EMPTY(&(loop)->active_reqs))
+    return UV_EBUSY;
+
+  QUEUE_FOREACH(q, &loop->handle_queue) {
+    h = QUEUE_DATA(q, uv_handle_t, handle_queue);
+    if (!(h->flags & UV__HANDLE_INTERNAL))
+      return UV_EBUSY;
+  }
+
+  uv__loop_close(loop);
+
+#ifndef NDEBUG
+  saved_data = loop->data;
+  memset(loop, -1, sizeof(*loop));
+  loop->data = saved_data;
+#endif
+  if (loop == default_loop_ptr)
+    default_loop_ptr = NULL;
+
+  return 0;
+}
+
+
+void uv_loop_delete(uv_loop_t* loop) {
+  uv_loop_t* default_loop;
+  int err;
+
+  default_loop = default_loop_ptr;
+
+  err = uv_loop_close(loop);
+  (void) err;    /* Squelch compiler warnings. */
+  assert(err == 0);
+  if (loop != default_loop)
+    uv__free(loop);
+}
diff --git a/Utilities/cmlibuv/src/uv-common.h b/Utilities/cmlibuv/src/uv-common.h
new file mode 100644
index 0000000..27902fd
--- /dev/null
+++ b/Utilities/cmlibuv/src/uv-common.h
@@ -0,0 +1,227 @@
+/* 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_COMMON_H_
+#define UV_COMMON_H_
+
+#include <assert.h>
+#include <stdarg.h>
+#include <stddef.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#include "uv.h"
+#include "tree.h"
+#include "queue.h"
+
+#if !defined(snprintf) && defined(_MSC_VER) && _MSC_VER < 1900
+extern int snprintf(char*, size_t, const char*, ...);
+#endif
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+
+#define container_of(ptr, type, member) \
+  ((type *) ((char *) (ptr) - offsetof(type, member)))
+
+#define STATIC_ASSERT(expr)                                                   \
+  void uv__static_assert(int static_assert_failed[1 - 2 * !(expr)])
+
+#ifndef _WIN32
+enum {
+  UV__HANDLE_INTERNAL = 0x8000,
+  UV__HANDLE_ACTIVE   = 0x4000,
+  UV__HANDLE_REF      = 0x2000,
+  UV__HANDLE_CLOSING  = 0 /* no-op on unix */
+};
+#else
+# define UV__HANDLE_INTERNAL  0x80
+# define UV__HANDLE_ACTIVE    0x40
+# define UV__HANDLE_REF       0x20
+# define UV__HANDLE_CLOSING   0x01
+#endif
+
+int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap);
+
+void uv__loop_close(uv_loop_t* loop);
+
+int uv__tcp_bind(uv_tcp_t* tcp,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 unsigned int flags);
+
+int uv__tcp_connect(uv_connect_t* req,
+                   uv_tcp_t* handle,
+                   const struct sockaddr* addr,
+                   unsigned int addrlen,
+                   uv_connect_cb cb);
+
+int uv__udp_bind(uv_udp_t* handle,
+                 const struct sockaddr* addr,
+                 unsigned int  addrlen,
+                 unsigned int flags);
+
+int uv__udp_send(uv_udp_send_t* req,
+                 uv_udp_t* handle,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 uv_udp_send_cb send_cb);
+
+int uv__udp_try_send(uv_udp_t* handle,
+                     const uv_buf_t bufs[],
+                     unsigned int nbufs,
+                     const struct sockaddr* addr,
+                     unsigned int addrlen);
+
+int uv__udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloccb,
+                       uv_udp_recv_cb recv_cb);
+
+int uv__udp_recv_stop(uv_udp_t* handle);
+
+void uv__fs_poll_close(uv_fs_poll_t* handle);
+
+int uv__getaddrinfo_translate_error(int sys_err);    /* EAI_* error. */
+
+void uv__work_submit(uv_loop_t* loop,
+                     struct uv__work *w,
+                     void (*work)(struct uv__work *w),
+                     void (*done)(struct uv__work *w, int status));
+
+void uv__work_done(uv_async_t* handle);
+
+size_t uv__count_bufs(const uv_buf_t bufs[], unsigned int nbufs);
+
+int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value);
+
+void uv__fs_scandir_cleanup(uv_fs_t* req);
+
+#define uv__has_active_reqs(loop)                                             \
+  (QUEUE_EMPTY(&(loop)->active_reqs) == 0)
+
+#define uv__req_register(loop, req)                                           \
+  do {                                                                        \
+    QUEUE_INSERT_TAIL(&(loop)->active_reqs, &(req)->active_queue);            \
+  }                                                                           \
+  while (0)
+
+#define uv__req_unregister(loop, req)                                         \
+  do {                                                                        \
+    assert(uv__has_active_reqs(loop));                                        \
+    QUEUE_REMOVE(&(req)->active_queue);                                       \
+  }                                                                           \
+  while (0)
+
+#define uv__has_active_handles(loop)                                          \
+  ((loop)->active_handles > 0)
+
+#define uv__active_handle_add(h)                                              \
+  do {                                                                        \
+    (h)->loop->active_handles++;                                              \
+  }                                                                           \
+  while (0)
+
+#define uv__active_handle_rm(h)                                               \
+  do {                                                                        \
+    (h)->loop->active_handles--;                                              \
+  }                                                                           \
+  while (0)
+
+#define uv__is_active(h)                                                      \
+  (((h)->flags & UV__HANDLE_ACTIVE) != 0)
+
+#define uv__is_closing(h)                                                     \
+  (((h)->flags & (UV_CLOSING |  UV_CLOSED)) != 0)
+
+#define uv__handle_start(h)                                                   \
+  do {                                                                        \
+    assert(((h)->flags & UV__HANDLE_CLOSING) == 0);                           \
+    if (((h)->flags & UV__HANDLE_ACTIVE) != 0) break;                         \
+    (h)->flags |= UV__HANDLE_ACTIVE;                                          \
+    if (((h)->flags & UV__HANDLE_REF) != 0) uv__active_handle_add(h);         \
+  }                                                                           \
+  while (0)
+
+#define uv__handle_stop(h)                                                    \
+  do {                                                                        \
+    assert(((h)->flags & UV__HANDLE_CLOSING) == 0);                           \
+    if (((h)->flags & UV__HANDLE_ACTIVE) == 0) break;                         \
+    (h)->flags &= ~UV__HANDLE_ACTIVE;                                         \
+    if (((h)->flags & UV__HANDLE_REF) != 0) uv__active_handle_rm(h);          \
+  }                                                                           \
+  while (0)
+
+#define uv__handle_ref(h)                                                     \
+  do {                                                                        \
+    if (((h)->flags & UV__HANDLE_REF) != 0) break;                            \
+    (h)->flags |= UV__HANDLE_REF;                                             \
+    if (((h)->flags & UV__HANDLE_CLOSING) != 0) break;                        \
+    if (((h)->flags & UV__HANDLE_ACTIVE) != 0) uv__active_handle_add(h);      \
+  }                                                                           \
+  while (0)
+
+#define uv__handle_unref(h)                                                   \
+  do {                                                                        \
+    if (((h)->flags & UV__HANDLE_REF) == 0) break;                            \
+    (h)->flags &= ~UV__HANDLE_REF;                                            \
+    if (((h)->flags & UV__HANDLE_CLOSING) != 0) break;                        \
+    if (((h)->flags & UV__HANDLE_ACTIVE) != 0) uv__active_handle_rm(h);       \
+  }                                                                           \
+  while (0)
+
+#define uv__has_ref(h)                                                        \
+  (((h)->flags & UV__HANDLE_REF) != 0)
+
+#if defined(_WIN32)
+# define uv__handle_platform_init(h) ((h)->u.fd = -1)
+#else
+# define uv__handle_platform_init(h) ((h)->next_closing = NULL)
+#endif
+
+#define uv__handle_init(loop_, h, type_)                                      \
+  do {                                                                        \
+    (h)->loop = (loop_);                                                      \
+    (h)->type = (type_);                                                      \
+    (h)->flags = UV__HANDLE_REF;  /* Ref the loop when active. */             \
+    QUEUE_INSERT_TAIL(&(loop_)->handle_queue, &(h)->handle_queue);            \
+    uv__handle_platform_init(h);                                              \
+  }                                                                           \
+  while (0)
+
+
+/* Allocator prototypes */
+void *uv__calloc(size_t count, size_t size);
+char *uv__strdup(const char* s);
+char *uv__strndup(const char* s, size_t n);
+void* uv__malloc(size_t size);
+void uv__free(void* ptr);
+void* uv__realloc(void* ptr, size_t size);
+
+#endif /* UV_COMMON_H_ */
diff --git a/Utilities/cmlibuv/src/version.c b/Utilities/cmlibuv/src/version.c
new file mode 100644
index 0000000..686dedd
--- /dev/null
+++ b/Utilities/cmlibuv/src/version.c
@@ -0,0 +1,45 @@
+/* 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"
+
+#define UV_STRINGIFY(v) UV_STRINGIFY_HELPER(v)
+#define UV_STRINGIFY_HELPER(v) #v
+
+#define UV_VERSION_STRING_BASE  UV_STRINGIFY(UV_VERSION_MAJOR) "." \
+                                UV_STRINGIFY(UV_VERSION_MINOR) "." \
+                                UV_STRINGIFY(UV_VERSION_PATCH)
+
+#if UV_VERSION_IS_RELEASE
+# define UV_VERSION_STRING  UV_VERSION_STRING_BASE
+#else
+# define UV_VERSION_STRING  UV_VERSION_STRING_BASE "-" UV_VERSION_SUFFIX
+#endif
+
+
+unsigned int uv_version(void) {
+  return UV_VERSION_HEX;
+}
+
+
+const char* uv_version_string(void) {
+  return UV_VERSION_STRING;
+}
diff --git a/Utilities/cmlibuv/src/win/async.c b/Utilities/cmlibuv/src/win/async.c
new file mode 100644
index 0000000..ad240ab
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/async.c
@@ -0,0 +1,99 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "atomicops-inl.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+void uv_async_endgame(uv_loop_t* loop, uv_async_t* handle) {
+  if (handle->flags & UV__HANDLE_CLOSING &&
+      !handle->async_sent) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+    uv__handle_close(handle);
+  }
+}
+
+
+int uv_async_init(uv_loop_t* loop, uv_async_t* handle, uv_async_cb async_cb) {
+  uv_req_t* req;
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_ASYNC);
+  handle->async_sent = 0;
+  handle->async_cb = async_cb;
+
+  req = &handle->async_req;
+  uv_req_init(loop, req);
+  req->type = UV_WAKEUP;
+  req->data = handle;
+
+  uv__handle_start(handle);
+
+  return 0;
+}
+
+
+void uv_async_close(uv_loop_t* loop, uv_async_t* handle) {
+  if (!((uv_async_t*)handle)->async_sent) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+
+  uv__handle_closing(handle);
+}
+
+
+int uv_async_send(uv_async_t* handle) {
+  uv_loop_t* loop = handle->loop;
+
+  if (handle->type != UV_ASYNC) {
+    /* Can't set errno because that's not thread-safe. */
+    return -1;
+  }
+
+  /* The user should make sure never to call uv_async_send to a closing */
+  /* or closed handle. */
+  assert(!(handle->flags & UV__HANDLE_CLOSING));
+
+  if (!uv__atomic_exchange_set(&handle->async_sent)) {
+    POST_COMPLETION_FOR_REQ(loop, &handle->async_req);
+  }
+
+  return 0;
+}
+
+
+void uv_process_async_wakeup_req(uv_loop_t* loop, uv_async_t* handle,
+    uv_req_t* req) {
+  assert(handle->type == UV_ASYNC);
+  assert(req->type == UV_WAKEUP);
+
+  handle->async_sent = 0;
+
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  } else if (handle->async_cb != NULL) {
+    handle->async_cb(handle);
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/atomicops-inl.h b/Utilities/cmlibuv/src/win/atomicops-inl.h
new file mode 100644
index 0000000..61e0060
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/atomicops-inl.h
@@ -0,0 +1,56 @@
+/* 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_WIN_ATOMICOPS_INL_H_
+#define UV_WIN_ATOMICOPS_INL_H_
+
+#include "uv.h"
+
+
+/* Atomic set operation on char */
+#ifdef _MSC_VER /* MSVC */
+
+/* _InterlockedOr8 is supported by MSVC on x32 and x64. It is  slightly less */
+/* efficient than InterlockedExchange, but InterlockedExchange8 does not */
+/* exist, and interlocked operations on larger targets might require the */
+/* target to be aligned. */
+#pragma intrinsic(_InterlockedOr8)
+
+static char __declspec(inline) uv__atomic_exchange_set(char volatile* target) {
+  return _InterlockedOr8(target, 1);
+}
+
+#else /* GCC */
+
+/* Mingw-32 version, hopefully this works for 64-bit gcc as well. */
+static inline char uv__atomic_exchange_set(char volatile* target) {
+  const char one = 1;
+  char old_value;
+  __asm__ __volatile__ ("lock xchgb %0, %1\n\t"
+                        : "=r"(old_value), "=m"(*target)
+                        : "0"(one), "m"(*target)
+                        : "memory");
+  return old_value;
+}
+
+#endif
+
+#endif /* UV_WIN_ATOMICOPS_INL_H_ */
diff --git a/Utilities/cmlibuv/src/win/core.c b/Utilities/cmlibuv/src/win/core.c
new file mode 100644
index 0000000..9d00afc
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/core.c
@@ -0,0 +1,602 @@
+/* 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 <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
+#include <crtdbg.h>
+#endif
+
+#include "uv.h"
+#include "internal.h"
+#include "queue.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+static uv_loop_t default_loop_struct;
+static uv_loop_t* default_loop_ptr;
+
+/* uv_once initialization guards */
+static uv_once_t uv_init_guard_ = UV_ONCE_INIT;
+
+
+#if defined(_DEBUG) && (defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR))
+/* Our crt debug report handler allows us to temporarily disable asserts
+ * just for the current thread.
+ */
+
+UV_THREAD_LOCAL int uv__crt_assert_enabled = TRUE;
+
+static int uv__crt_dbg_report_handler(int report_type, char *message, int *ret_val) {
+  if (uv__crt_assert_enabled || report_type != _CRT_ASSERT)
+    return FALSE;
+
+  if (ret_val) {
+    /* Set ret_val to 0 to continue with normal execution.
+     * Set ret_val to 1 to trigger a breakpoint.
+    */
+
+    if(IsDebuggerPresent())
+      *ret_val = 1;
+    else
+      *ret_val = 0;
+  }
+
+  /* Don't call _CrtDbgReport. */
+  return TRUE;
+}
+#else
+UV_THREAD_LOCAL int uv__crt_assert_enabled = FALSE;
+#endif
+
+
+#if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800
+static void uv__crt_invalid_parameter_handler(const wchar_t* expression,
+    const wchar_t* function, const wchar_t * file, unsigned int line,
+    uintptr_t reserved) {
+  /* No-op. */
+}
+#endif
+
+static uv_loop_t** uv__loops;
+static int uv__loops_size;
+static int uv__loops_capacity;
+#define UV__LOOPS_CHUNK_SIZE 8
+static uv_mutex_t uv__loops_lock;
+
+static void uv__loops_init() {
+  uv_mutex_init(&uv__loops_lock);
+  uv__loops = uv__calloc(UV__LOOPS_CHUNK_SIZE, sizeof(uv_loop_t*));
+  if (!uv__loops)
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  uv__loops_size = 0;
+  uv__loops_capacity = UV__LOOPS_CHUNK_SIZE;
+}
+
+static int uv__loops_add(uv_loop_t* loop) {
+  uv_loop_t** new_loops;
+  int new_capacity, i;
+
+  uv_mutex_lock(&uv__loops_lock);
+
+  if (uv__loops_size == uv__loops_capacity) {
+    new_capacity = uv__loops_capacity + UV__LOOPS_CHUNK_SIZE;
+    new_loops = uv__realloc(uv__loops, sizeof(uv_loop_t*) * new_capacity);
+    if (!new_loops)
+      goto failed_loops_realloc;
+    uv__loops = new_loops;
+    for (i = uv__loops_capacity; i < new_capacity; ++i)
+      uv__loops[i] = NULL;
+    uv__loops_capacity = new_capacity;
+  }
+  uv__loops[uv__loops_size] = loop;
+  ++uv__loops_size;
+
+  uv_mutex_unlock(&uv__loops_lock);
+  return 0;
+
+failed_loops_realloc:
+  uv_mutex_unlock(&uv__loops_lock);
+  return ERROR_OUTOFMEMORY;
+}
+
+static void uv__loops_remove(uv_loop_t* loop) {
+  int loop_index;
+  int smaller_capacity;
+  uv_loop_t** new_loops;
+
+  uv_mutex_lock(&uv__loops_lock);
+
+  for (loop_index = 0; loop_index < uv__loops_size; ++loop_index) {
+    if (uv__loops[loop_index] == loop)
+      break;
+  }
+  /* If loop was not found, ignore */
+  if (loop_index == uv__loops_size)
+    goto loop_removed;
+
+  uv__loops[loop_index] = uv__loops[uv__loops_size - 1];
+  uv__loops[uv__loops_size - 1] = NULL;
+  --uv__loops_size;
+
+  /* If we didn't grow to big skip downsizing */
+  if (uv__loops_capacity < 4 * UV__LOOPS_CHUNK_SIZE)
+    goto loop_removed;
+
+  /* Downsize only if more than half of buffer is free */
+  smaller_capacity = uv__loops_capacity / 2;
+  if (uv__loops_size >= smaller_capacity)
+    goto loop_removed;
+  new_loops = uv__realloc(uv__loops, sizeof(uv_loop_t*) * smaller_capacity);
+  if (!new_loops)
+    goto loop_removed;
+  uv__loops = new_loops;
+  uv__loops_capacity = smaller_capacity;
+
+loop_removed:
+  uv_mutex_unlock(&uv__loops_lock);
+}
+
+void uv__wake_all_loops() {
+  int i;
+  uv_loop_t* loop;
+
+  uv_mutex_lock(&uv__loops_lock);
+  for (i = 0; i < uv__loops_size; ++i) {
+    loop = uv__loops[i];
+    assert(loop);
+    if (loop->iocp != INVALID_HANDLE_VALUE)
+      PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL);
+  }
+  uv_mutex_unlock(&uv__loops_lock);
+}
+
+static void uv_init(void) {
+  /* Tell Windows that we will handle critical errors. */
+  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
+               SEM_NOOPENFILEERRORBOX);
+
+  /* Tell the CRT to not exit the application when an invalid parameter is
+   * passed. The main issue is that invalid FDs will trigger this behavior.
+   */
+#if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800
+  _set_invalid_parameter_handler(uv__crt_invalid_parameter_handler);
+#endif
+
+  /* We also need to setup our debug report handler because some CRT
+   * functions (eg _get_osfhandle) raise an assert when called with invalid
+   * FDs even though they return the proper error code in the release build.
+   */
+#if defined(_DEBUG) && (defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR))
+  _CrtSetReportHook(uv__crt_dbg_report_handler);
+#endif
+
+  /* Initialize tracking of all uv loops */
+  uv__loops_init();
+
+  /* Fetch winapi function pointers. This must be done first because other
+   * initialization code might need these function pointers to be loaded.
+   */
+  uv_winapi_init();
+
+  /* Initialize winsock */
+  uv_winsock_init();
+
+  /* Initialize FS */
+  uv_fs_init();
+
+  /* Initialize signal stuff */
+  uv_signals_init();
+
+  /* Initialize console */
+  uv_console_init();
+
+  /* Initialize utilities */
+  uv__util_init();
+
+  /* Initialize system wakeup detection */
+  uv__init_detect_system_wakeup();
+}
+
+
+int uv_loop_init(uv_loop_t* loop) {
+  int err;
+
+  /* Initialize libuv itself first */
+  uv__once_init();
+
+  /* Create an I/O completion port */
+  loop->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
+  if (loop->iocp == NULL)
+    return uv_translate_sys_error(GetLastError());
+
+  /* To prevent uninitialized memory access, loop->time must be initialized
+   * to zero before calling uv_update_time for the first time.
+   */
+  loop->time = 0;
+  uv_update_time(loop);
+
+  QUEUE_INIT(&loop->wq);
+  QUEUE_INIT(&loop->handle_queue);
+  QUEUE_INIT(&loop->active_reqs);
+  loop->active_handles = 0;
+
+  loop->pending_reqs_tail = NULL;
+
+  loop->endgame_handles = NULL;
+
+  RB_INIT(&loop->timers);
+
+  loop->check_handles = NULL;
+  loop->prepare_handles = NULL;
+  loop->idle_handles = NULL;
+
+  loop->next_prepare_handle = NULL;
+  loop->next_check_handle = NULL;
+  loop->next_idle_handle = NULL;
+
+  memset(&loop->poll_peer_sockets, 0, sizeof loop->poll_peer_sockets);
+
+  loop->active_tcp_streams = 0;
+  loop->active_udp_streams = 0;
+
+  loop->timer_counter = 0;
+  loop->stop_flag = 0;
+
+  err = uv_mutex_init(&loop->wq_mutex);
+  if (err)
+    goto fail_mutex_init;
+
+  err = uv_async_init(loop, &loop->wq_async, uv__work_done);
+  if (err)
+    goto fail_async_init;
+
+  uv__handle_unref(&loop->wq_async);
+  loop->wq_async.flags |= UV__HANDLE_INTERNAL;
+
+  err = uv__loops_add(loop);
+  if (err)
+    goto fail_async_init;
+
+  return 0;
+
+fail_async_init:
+  uv_mutex_destroy(&loop->wq_mutex);
+
+fail_mutex_init:
+  CloseHandle(loop->iocp);
+  loop->iocp = INVALID_HANDLE_VALUE;
+
+  return err;
+}
+
+
+void uv__once_init(void) {
+  uv_once(&uv_init_guard_, uv_init);
+}
+
+
+void uv__loop_close(uv_loop_t* loop) {
+  size_t i;
+
+  uv__loops_remove(loop);
+
+  /* close the async handle without needing an extra loop iteration */
+  assert(!loop->wq_async.async_sent);
+  loop->wq_async.close_cb = NULL;
+  uv__handle_closing(&loop->wq_async);
+  uv__handle_close(&loop->wq_async);
+
+  for (i = 0; i < ARRAY_SIZE(loop->poll_peer_sockets); i++) {
+    SOCKET sock = loop->poll_peer_sockets[i];
+    if (sock != 0 && sock != INVALID_SOCKET)
+      closesocket(sock);
+  }
+
+  uv_mutex_lock(&loop->wq_mutex);
+  assert(QUEUE_EMPTY(&loop->wq) && "thread pool work queue not empty!");
+  assert(!uv__has_active_reqs(loop));
+  uv_mutex_unlock(&loop->wq_mutex);
+  uv_mutex_destroy(&loop->wq_mutex);
+
+  CloseHandle(loop->iocp);
+}
+
+
+int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) {
+  return UV_ENOSYS;
+}
+
+
+int uv_backend_fd(const uv_loop_t* loop) {
+  return -1;
+}
+
+
+int uv_backend_timeout(const uv_loop_t* loop) {
+  if (loop->stop_flag != 0)
+    return 0;
+
+  if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
+    return 0;
+
+  if (loop->pending_reqs_tail)
+    return 0;
+
+  if (loop->endgame_handles)
+    return 0;
+
+  if (loop->idle_handles)
+    return 0;
+
+  return uv__next_timeout(loop);
+}
+
+
+static void uv_poll(uv_loop_t* loop, DWORD timeout) {
+  DWORD bytes;
+  ULONG_PTR key;
+  OVERLAPPED* overlapped;
+  uv_req_t* req;
+  int repeat;
+  uint64_t timeout_time;
+
+  timeout_time = loop->time + timeout;
+
+  for (repeat = 0; ; repeat++) {
+    GetQueuedCompletionStatus(loop->iocp,
+                              &bytes,
+                              &key,
+                              &overlapped,
+                              timeout);
+
+    if (overlapped) {
+      /* Package was dequeued */
+      req = uv_overlapped_to_req(overlapped);
+      uv_insert_pending_req(loop, req);
+
+      /* Some time might have passed waiting for I/O,
+       * so update the loop time here.
+       */
+      uv_update_time(loop);
+    } else if (GetLastError() != WAIT_TIMEOUT) {
+      /* Serious error */
+      uv_fatal_error(GetLastError(), "GetQueuedCompletionStatus");
+    } else if (timeout > 0) {
+      /* GetQueuedCompletionStatus can occasionally return a little early.
+       * Make sure that the desired timeout target time is reached.
+       */
+      uv_update_time(loop);
+      if (timeout_time > loop->time) {
+        timeout = (DWORD)(timeout_time - loop->time);
+        /* The first call to GetQueuedCompletionStatus should return very
+         * close to the target time and the second should reach it, but
+         * this is not stated in the documentation. To make sure a busy
+         * loop cannot happen, the timeout is increased exponentially
+         * starting on the third round.
+         */
+        timeout += repeat ? (1 << (repeat - 1)) : 0;
+        continue;
+      }
+    }
+    break;
+  }
+}
+
+
+static void uv_poll_ex(uv_loop_t* loop, DWORD timeout) {
+  BOOL success;
+  uv_req_t* req;
+  OVERLAPPED_ENTRY overlappeds[128];
+  ULONG count;
+  ULONG i;
+  int repeat;
+  uint64_t timeout_time;
+
+  timeout_time = loop->time + timeout;
+
+  for (repeat = 0; ; repeat++) {
+    success = pGetQueuedCompletionStatusEx(loop->iocp,
+                                           overlappeds,
+                                           ARRAY_SIZE(overlappeds),
+                                           &count,
+                                           timeout,
+                                           FALSE);
+
+    if (success) {
+      for (i = 0; i < count; i++) {
+        /* Package was dequeued, but see if it is not a empty package
+         * meant only to wake us up.
+         */
+        if (overlappeds[i].lpOverlapped) {
+          req = uv_overlapped_to_req(overlappeds[i].lpOverlapped);
+          uv_insert_pending_req(loop, req);
+        }
+      }
+
+      /* Some time might have passed waiting for I/O,
+       * so update the loop time here.
+       */
+      uv_update_time(loop);
+    } else if (GetLastError() != WAIT_TIMEOUT) {
+      /* Serious error */
+      uv_fatal_error(GetLastError(), "GetQueuedCompletionStatusEx");
+    } else if (timeout > 0) {
+      /* GetQueuedCompletionStatus can occasionally return a little early.
+       * Make sure that the desired timeout target time is reached.
+       */
+      uv_update_time(loop);
+      if (timeout_time > loop->time) {
+        timeout = (DWORD)(timeout_time - loop->time);
+        /* The first call to GetQueuedCompletionStatus should return very
+         * close to the target time and the second should reach it, but
+         * this is not stated in the documentation. To make sure a busy
+         * loop cannot happen, the timeout is increased exponentially
+         * starting on the third round.
+         */
+        timeout += repeat ? (1 << (repeat - 1)) : 0;
+        continue;
+      }
+    }
+    break;
+  }
+}
+
+
+static int uv__loop_alive(const uv_loop_t* loop) {
+  return loop->active_handles > 0 ||
+         !QUEUE_EMPTY(&loop->active_reqs) ||
+         loop->endgame_handles != NULL;
+}
+
+
+int uv_loop_alive(const uv_loop_t* loop) {
+    return uv__loop_alive(loop);
+}
+
+
+int uv_run(uv_loop_t *loop, uv_run_mode mode) {
+  DWORD timeout;
+  int r;
+  int ran_pending;
+  void (*poll)(uv_loop_t* loop, DWORD timeout);
+
+  if (pGetQueuedCompletionStatusEx)
+    poll = &uv_poll_ex;
+  else
+    poll = &uv_poll;
+
+  r = uv__loop_alive(loop);
+  if (!r)
+    uv_update_time(loop);
+
+  while (r != 0 && loop->stop_flag == 0) {
+    uv_update_time(loop);
+    uv_process_timers(loop);
+
+    ran_pending = uv_process_reqs(loop);
+    uv_idle_invoke(loop);
+    uv_prepare_invoke(loop);
+
+    timeout = 0;
+    if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
+      timeout = uv_backend_timeout(loop);
+
+    (*poll)(loop, timeout);
+
+    uv_check_invoke(loop);
+    uv_process_endgames(loop);
+
+    if (mode == UV_RUN_ONCE) {
+      /* UV_RUN_ONCE implies forward progress: at least one callback must have
+       * been invoked when it returns. uv__io_poll() can return without doing
+       * I/O (meaning: no callbacks) when its timeout expires - which means we
+       * have pending timers that satisfy the forward progress constraint.
+       *
+       * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
+       * the check.
+       */
+      uv_process_timers(loop);
+    }
+
+    r = uv__loop_alive(loop);
+    if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
+      break;
+  }
+
+  /* The if statement lets the compiler compile it to a conditional store.
+   * Avoids dirtying a cache line.
+   */
+  if (loop->stop_flag != 0)
+    loop->stop_flag = 0;
+
+  return r;
+}
+
+
+int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
+  uv_os_fd_t fd_out;
+
+  switch (handle->type) {
+  case UV_TCP:
+    fd_out = (uv_os_fd_t)((uv_tcp_t*) handle)->socket;
+    break;
+
+  case UV_NAMED_PIPE:
+    fd_out = ((uv_pipe_t*) handle)->handle;
+    break;
+
+  case UV_TTY:
+    fd_out = ((uv_tty_t*) handle)->handle;
+    break;
+
+  case UV_UDP:
+    fd_out = (uv_os_fd_t)((uv_udp_t*) handle)->socket;
+    break;
+
+  case UV_POLL:
+    fd_out = (uv_os_fd_t)((uv_poll_t*) handle)->socket;
+    break;
+
+  default:
+    return UV_EINVAL;
+  }
+
+  if (uv_is_closing(handle) || fd_out == INVALID_HANDLE_VALUE)
+    return UV_EBADF;
+
+  *fd = fd_out;
+  return 0;
+}
+
+
+int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
+  int r;
+  int len;
+  SOCKET socket;
+
+  if (handle == NULL || value == NULL)
+    return UV_EINVAL;
+
+  if (handle->type == UV_TCP)
+    socket = ((uv_tcp_t*) handle)->socket;
+  else if (handle->type == UV_UDP)
+    socket = ((uv_udp_t*) handle)->socket;
+  else
+    return UV_ENOTSUP;
+
+  len = sizeof(*value);
+
+  if (*value == 0)
+    r = getsockopt(socket, SOL_SOCKET, optname, (char*) value, &len);
+  else
+    r = setsockopt(socket, SOL_SOCKET, optname, (const char*) value, len);
+
+  if (r == SOCKET_ERROR)
+    return uv_translate_sys_error(WSAGetLastError());
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/win/detect-wakeup.c b/Utilities/cmlibuv/src/win/detect-wakeup.c
new file mode 100644
index 0000000..a12179f
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/detect-wakeup.c
@@ -0,0 +1,35 @@
+#include "uv.h"
+#include "internal.h"
+#include "winapi.h"
+
+static void uv__register_system_resume_callback();
+
+void uv__init_detect_system_wakeup() {
+  /* Try registering system power event callback. This is the cleanest
+   * method, but it will only work on Win8 and above.
+   */
+  uv__register_system_resume_callback();
+}
+
+static ULONG CALLBACK uv__system_resume_callback(PVOID Context,
+                                                 ULONG Type,
+                                                 PVOID Setting) {
+  if (Type == PBT_APMRESUMESUSPEND || Type == PBT_APMRESUMEAUTOMATIC)
+    uv__wake_all_loops();
+
+  return 0;
+}
+
+static void uv__register_system_resume_callback() {
+  _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS recipient;
+  _HPOWERNOTIFY registration_handle;
+
+  if (pPowerRegisterSuspendResumeNotification == NULL)
+    return;
+
+  recipient.Callback = uv__system_resume_callback;
+  recipient.Context = NULL;
+  (*pPowerRegisterSuspendResumeNotification)(DEVICE_NOTIFY_CALLBACK,
+                                             &recipient,
+                                             &registration_handle);
+}
diff --git a/Utilities/cmlibuv/src/win/dl.c b/Utilities/cmlibuv/src/win/dl.c
new file mode 100644
index 0000000..39e400a
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/dl.c
@@ -0,0 +1,118 @@
+/* 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 "internal.h"
+
+static int uv__dlerror(uv_lib_t* lib, int errorno);
+
+
+int uv_dlopen(const char* filename, uv_lib_t* lib) {
+  WCHAR filename_w[32768];
+
+  lib->handle = NULL;
+  lib->errmsg = NULL;
+
+  if (!MultiByteToWideChar(CP_UTF8,
+                           0,
+                           filename,
+                           -1,
+                           filename_w,
+                           ARRAY_SIZE(filename_w))) {
+    return uv__dlerror(lib, GetLastError());
+  }
+
+  lib->handle = LoadLibraryExW(filename_w, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
+  if (lib->handle == NULL) {
+    return uv__dlerror(lib, GetLastError());
+  }
+
+  return 0;
+}
+
+
+void uv_dlclose(uv_lib_t* lib) {
+  if (lib->errmsg) {
+    LocalFree((void*)lib->errmsg);
+    lib->errmsg = NULL;
+  }
+
+  if (lib->handle) {
+    /* Ignore errors. No good way to signal them without leaking memory. */
+    FreeLibrary(lib->handle);
+    lib->handle = NULL;
+  }
+}
+
+
+int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr) {
+  *ptr = (void*) GetProcAddress(lib->handle, name);
+  return uv__dlerror(lib, *ptr ? 0 : GetLastError());
+}
+
+
+const char* uv_dlerror(const uv_lib_t* lib) {
+  return lib->errmsg ? lib->errmsg : "no error";
+}
+
+
+static void uv__format_fallback_error(uv_lib_t* lib, int errorno){
+  DWORD_PTR args[1] = { (DWORD_PTR) errorno };
+  LPSTR fallback_error = "error: %1!d!";
+
+  FormatMessageA(FORMAT_MESSAGE_FROM_STRING |
+                 FORMAT_MESSAGE_ARGUMENT_ARRAY |
+                 FORMAT_MESSAGE_ALLOCATE_BUFFER,
+                 fallback_error, 0, 0,
+                 (LPSTR) &lib->errmsg,
+                 0, (va_list*) args);
+}
+
+
+
+static int uv__dlerror(uv_lib_t* lib, int errorno) {
+  DWORD res;
+
+  if (lib->errmsg) {
+    LocalFree((void*)lib->errmsg);
+    lib->errmsg = NULL;
+  }
+
+  if (errorno) {
+    res = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                         FORMAT_MESSAGE_FROM_SYSTEM |
+                         FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
+                         MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
+                         (LPSTR) &lib->errmsg, 0, NULL);
+    if (!res && GetLastError() == ERROR_MUI_FILE_NOT_FOUND) {
+      res = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                           FORMAT_MESSAGE_FROM_SYSTEM |
+                           FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
+                           0, (LPSTR) &lib->errmsg, 0, NULL);
+    }
+
+    if (!res) {
+      uv__format_fallback_error(lib, errorno);
+    }
+  }
+
+  return errorno ? -1 : 0;
+}
diff --git a/Utilities/cmlibuv/src/win/error.c b/Utilities/cmlibuv/src/win/error.c
new file mode 100644
index 0000000..c512f35
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/error.c
@@ -0,0 +1,170 @@
+/* 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 <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+/*
+ * Display an error message and abort the event loop.
+ */
+void uv_fatal_error(const int errorno, const char* syscall) {
+  char* buf = NULL;
+  const char* errmsg;
+
+  FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
+      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
+
+  if (buf) {
+    errmsg = buf;
+  } else {
+    errmsg = "Unknown error";
+  }
+
+  /* FormatMessage messages include a newline character already, */
+  /* so don't add another. */
+  if (syscall) {
+    fprintf(stderr, "%s: (%d) %s", syscall, errorno, errmsg);
+  } else {
+    fprintf(stderr, "(%d) %s", errorno, errmsg);
+  }
+
+  if (buf) {
+    LocalFree(buf);
+  }
+
+  *((char*)NULL) = 0xff; /* Force debug break */
+  abort();
+}
+
+
+int uv_translate_sys_error(int sys_errno) {
+  if (sys_errno <= 0) {
+    return sys_errno;  /* If < 0 then it's already a libuv error. */
+  }
+
+  switch (sys_errno) {
+    case ERROR_NOACCESS:                    return UV_EACCES;
+    case WSAEACCES:                         return UV_EACCES;
+    case ERROR_ADDRESS_ALREADY_ASSOCIATED:  return UV_EADDRINUSE;
+    case WSAEADDRINUSE:                     return UV_EADDRINUSE;
+    case WSAEADDRNOTAVAIL:                  return UV_EADDRNOTAVAIL;
+    case WSAEAFNOSUPPORT:                   return UV_EAFNOSUPPORT;
+    case WSAEWOULDBLOCK:                    return UV_EAGAIN;
+    case WSAEALREADY:                       return UV_EALREADY;
+    case ERROR_INVALID_FLAGS:               return UV_EBADF;
+    case ERROR_INVALID_HANDLE:              return UV_EBADF;
+    case ERROR_LOCK_VIOLATION:              return UV_EBUSY;
+    case ERROR_PIPE_BUSY:                   return UV_EBUSY;
+    case ERROR_SHARING_VIOLATION:           return UV_EBUSY;
+    case ERROR_OPERATION_ABORTED:           return UV_ECANCELED;
+    case WSAEINTR:                          return UV_ECANCELED;
+    case ERROR_NO_UNICODE_TRANSLATION:      return UV_ECHARSET;
+    case ERROR_CONNECTION_ABORTED:          return UV_ECONNABORTED;
+    case WSAECONNABORTED:                   return UV_ECONNABORTED;
+    case ERROR_CONNECTION_REFUSED:          return UV_ECONNREFUSED;
+    case WSAECONNREFUSED:                   return UV_ECONNREFUSED;
+    case ERROR_NETNAME_DELETED:             return UV_ECONNRESET;
+    case WSAECONNRESET:                     return UV_ECONNRESET;
+    case ERROR_ALREADY_EXISTS:              return UV_EEXIST;
+    case ERROR_FILE_EXISTS:                 return UV_EEXIST;
+    case ERROR_BUFFER_OVERFLOW:             return UV_EFAULT;
+    case WSAEFAULT:                         return UV_EFAULT;
+    case ERROR_HOST_UNREACHABLE:            return UV_EHOSTUNREACH;
+    case WSAEHOSTUNREACH:                   return UV_EHOSTUNREACH;
+    case ERROR_INSUFFICIENT_BUFFER:         return UV_EINVAL;
+    case ERROR_INVALID_DATA:                return UV_EINVAL;
+    case ERROR_INVALID_PARAMETER:           return UV_EINVAL;
+    case ERROR_SYMLINK_NOT_SUPPORTED:       return UV_EINVAL;
+    case WSAEINVAL:                         return UV_EINVAL;
+    case WSAEPFNOSUPPORT:                   return UV_EINVAL;
+    case WSAESOCKTNOSUPPORT:                return UV_EINVAL;
+    case ERROR_BEGINNING_OF_MEDIA:          return UV_EIO;
+    case ERROR_BUS_RESET:                   return UV_EIO;
+    case ERROR_CRC:                         return UV_EIO;
+    case ERROR_DEVICE_DOOR_OPEN:            return UV_EIO;
+    case ERROR_DEVICE_REQUIRES_CLEANING:    return UV_EIO;
+    case ERROR_DISK_CORRUPT:                return UV_EIO;
+    case ERROR_EOM_OVERFLOW:                return UV_EIO;
+    case ERROR_FILEMARK_DETECTED:           return UV_EIO;
+    case ERROR_GEN_FAILURE:                 return UV_EIO;
+    case ERROR_INVALID_BLOCK_LENGTH:        return UV_EIO;
+    case ERROR_IO_DEVICE:                   return UV_EIO;
+    case ERROR_NO_DATA_DETECTED:            return UV_EIO;
+    case ERROR_NO_SIGNAL_SENT:              return UV_EIO;
+    case ERROR_OPEN_FAILED:                 return UV_EIO;
+    case ERROR_SETMARK_DETECTED:            return UV_EIO;
+    case ERROR_SIGNAL_REFUSED:              return UV_EIO;
+    case WSAEISCONN:                        return UV_EISCONN;
+    case ERROR_CANT_RESOLVE_FILENAME:       return UV_ELOOP;
+    case ERROR_TOO_MANY_OPEN_FILES:         return UV_EMFILE;
+    case WSAEMFILE:                         return UV_EMFILE;
+    case WSAEMSGSIZE:                       return UV_EMSGSIZE;
+    case ERROR_FILENAME_EXCED_RANGE:        return UV_ENAMETOOLONG;
+    case ERROR_NETWORK_UNREACHABLE:         return UV_ENETUNREACH;
+    case WSAENETUNREACH:                    return UV_ENETUNREACH;
+    case WSAENOBUFS:                        return UV_ENOBUFS;
+    case ERROR_BAD_PATHNAME:                return UV_ENOENT;
+    case ERROR_DIRECTORY:                   return UV_ENOENT;
+    case ERROR_FILE_NOT_FOUND:              return UV_ENOENT;
+    case ERROR_INVALID_NAME:                return UV_ENOENT;
+    case ERROR_INVALID_DRIVE:               return UV_ENOENT;
+    case ERROR_INVALID_REPARSE_DATA:        return UV_ENOENT;
+    case ERROR_MOD_NOT_FOUND:               return UV_ENOENT;
+    case ERROR_PATH_NOT_FOUND:              return UV_ENOENT;
+    case WSAHOST_NOT_FOUND:                 return UV_ENOENT;
+    case WSANO_DATA:                        return UV_ENOENT;
+    case ERROR_NOT_ENOUGH_MEMORY:           return UV_ENOMEM;
+    case ERROR_OUTOFMEMORY:                 return UV_ENOMEM;
+    case ERROR_CANNOT_MAKE:                 return UV_ENOSPC;
+    case ERROR_DISK_FULL:                   return UV_ENOSPC;
+    case ERROR_EA_TABLE_FULL:               return UV_ENOSPC;
+    case ERROR_END_OF_MEDIA:                return UV_ENOSPC;
+    case ERROR_HANDLE_DISK_FULL:            return UV_ENOSPC;
+    case ERROR_NOT_CONNECTED:               return UV_ENOTCONN;
+    case WSAENOTCONN:                       return UV_ENOTCONN;
+    case ERROR_DIR_NOT_EMPTY:               return UV_ENOTEMPTY;
+    case WSAENOTSOCK:                       return UV_ENOTSOCK;
+    case ERROR_NOT_SUPPORTED:               return UV_ENOTSUP;
+    case ERROR_BROKEN_PIPE:                 return UV_EOF;
+    case ERROR_ACCESS_DENIED:               return UV_EPERM;
+    case ERROR_PRIVILEGE_NOT_HELD:          return UV_EPERM;
+    case ERROR_BAD_PIPE:                    return UV_EPIPE;
+    case ERROR_NO_DATA:                     return UV_EPIPE;
+    case ERROR_PIPE_NOT_CONNECTED:          return UV_EPIPE;
+    case WSAESHUTDOWN:                      return UV_EPIPE;
+    case WSAEPROTONOSUPPORT:                return UV_EPROTONOSUPPORT;
+    case ERROR_WRITE_PROTECT:               return UV_EROFS;
+    case ERROR_SEM_TIMEOUT:                 return UV_ETIMEDOUT;
+    case WSAETIMEDOUT:                      return UV_ETIMEDOUT;
+    case ERROR_NOT_SAME_DEVICE:             return UV_EXDEV;
+    case ERROR_INVALID_FUNCTION:            return UV_EISDIR;
+    case ERROR_META_EXPANSION_TOO_LONG:     return UV_E2BIG;
+    default:                                return UV_UNKNOWN;
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/fs-event.c b/Utilities/cmlibuv/src/win/fs-event.c
new file mode 100644
index 0000000..03e4adc
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/fs-event.c
@@ -0,0 +1,545 @@
+/* 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 <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+const unsigned int uv_directory_watcher_buffer_size = 4096;
+
+
+static void uv_fs_event_queue_readdirchanges(uv_loop_t* loop,
+    uv_fs_event_t* handle) {
+  assert(handle->dir_handle != INVALID_HANDLE_VALUE);
+  assert(!handle->req_pending);
+
+  memset(&(handle->req.u.io.overlapped), 0,
+         sizeof(handle->req.u.io.overlapped));
+  if (!ReadDirectoryChangesW(handle->dir_handle,
+                             handle->buffer,
+                             uv_directory_watcher_buffer_size,
+                             (handle->flags & UV_FS_EVENT_RECURSIVE) ? TRUE : FALSE,
+                             FILE_NOTIFY_CHANGE_FILE_NAME      |
+                               FILE_NOTIFY_CHANGE_DIR_NAME     |
+                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
+                               FILE_NOTIFY_CHANGE_SIZE         |
+                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
+                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
+                               FILE_NOTIFY_CHANGE_CREATION     |
+                               FILE_NOTIFY_CHANGE_SECURITY,
+                             NULL,
+                             &handle->req.u.io.overlapped,
+                             NULL)) {
+    /* Make this req pending reporting an error. */
+    SET_REQ_ERROR(&handle->req, GetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)&handle->req);
+  }
+
+  handle->req_pending = 1;
+}
+
+static void uv_relative_path(const WCHAR* filename,
+                             const WCHAR* dir,
+                             WCHAR** relpath) {
+  size_t relpathlen;
+  size_t filenamelen = wcslen(filename);
+  size_t dirlen = wcslen(dir);
+  if (dirlen > 0 && dir[dirlen - 1] == '\\')
+    dirlen--;
+  relpathlen = filenamelen - dirlen - 1;
+  *relpath = uv__malloc((relpathlen + 1) * sizeof(WCHAR));
+  if (!*relpath)
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  wcsncpy(*relpath, filename + dirlen + 1, relpathlen);
+  (*relpath)[relpathlen] = L'\0';
+}
+
+static int uv_split_path(const WCHAR* filename, WCHAR** dir,
+    WCHAR** file) {
+  int len = wcslen(filename);
+  int i = len;
+  while (i > 0 && filename[--i] != '\\' && filename[i] != '/');
+
+  if (i == 0) {
+    if (dir) {
+      *dir = (WCHAR*)uv__malloc((MAX_PATH + 1) * sizeof(WCHAR));
+      if (!*dir) {
+        uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+      }
+
+      if (!GetCurrentDirectoryW(MAX_PATH, *dir)) {
+        uv__free(*dir);
+        *dir = NULL;
+        return -1;
+      }
+    }
+
+    *file = wcsdup(filename);
+  } else {
+    if (dir) {
+      *dir = (WCHAR*)uv__malloc((i + 2) * sizeof(WCHAR));
+      if (!*dir) {
+        uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+      }
+      wcsncpy(*dir, filename, i + 1);
+      (*dir)[i + 1] = L'\0';
+    }
+
+    *file = (WCHAR*)uv__malloc((len - i) * sizeof(WCHAR));
+    if (!*file) {
+      uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+    }
+    wcsncpy(*file, filename + i + 1, len - i - 1);
+    (*file)[len - i - 1] = L'\0';
+  }
+
+  return 0;
+}
+
+
+int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_FS_EVENT);
+  handle->dir_handle = INVALID_HANDLE_VALUE;
+  handle->buffer = NULL;
+  handle->req_pending = 0;
+  handle->filew = NULL;
+  handle->short_filew = NULL;
+  handle->dirw = NULL;
+
+  uv_req_init(loop, (uv_req_t*)&handle->req);
+  handle->req.type = UV_FS_EVENT_REQ;
+  handle->req.data = handle;
+
+  return 0;
+}
+
+
+int uv_fs_event_start(uv_fs_event_t* handle,
+                      uv_fs_event_cb cb,
+                      const char* path,
+                      unsigned int flags) {
+  int name_size, is_path_dir;
+  DWORD attr, last_error;
+  WCHAR* dir = NULL, *dir_to_watch, *pathw = NULL;
+  WCHAR short_path[MAX_PATH];
+
+  if (uv__is_active(handle))
+    return UV_EINVAL;
+
+  handle->cb = cb;
+  handle->path = uv__strdup(path);
+  if (!handle->path) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  uv__handle_start(handle);
+
+  /* Convert name to UTF16. */
+
+  name_size = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0) *
+              sizeof(WCHAR);
+  pathw = (WCHAR*)uv__malloc(name_size);
+  if (!pathw) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  if (!MultiByteToWideChar(CP_UTF8,
+                           0,
+                           path,
+                           -1,
+                           pathw,
+                           name_size / sizeof(WCHAR))) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  /* Determine whether path is a file or a directory. */
+  attr = GetFileAttributesW(pathw);
+  if (attr == INVALID_FILE_ATTRIBUTES) {
+    last_error = GetLastError();
+    goto error;
+  }
+
+  is_path_dir = (attr & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0;
+
+  if (is_path_dir) {
+     /* path is a directory, so that's the directory that we will watch. */
+    handle->dirw = pathw;
+    dir_to_watch = pathw;
+  } else {
+    /*
+     * path is a file.  So we split path into dir & file parts, and
+     * watch the dir directory.
+     */
+
+    /* Convert to short path. */
+    if (!GetShortPathNameW(pathw, short_path, ARRAY_SIZE(short_path))) {
+      last_error = GetLastError();
+      goto error;
+    }
+
+    if (uv_split_path(pathw, &dir, &handle->filew) != 0) {
+      last_error = GetLastError();
+      goto error;
+    }
+
+    if (uv_split_path(short_path, NULL, &handle->short_filew) != 0) {
+      last_error = GetLastError();
+      goto error;
+    }
+
+    dir_to_watch = dir;
+    uv__free(pathw);
+    pathw = NULL;
+  }
+
+  handle->dir_handle = CreateFileW(dir_to_watch,
+                                   FILE_LIST_DIRECTORY,
+                                   FILE_SHARE_READ | FILE_SHARE_DELETE |
+                                     FILE_SHARE_WRITE,
+                                   NULL,
+                                   OPEN_EXISTING,
+                                   FILE_FLAG_BACKUP_SEMANTICS |
+                                     FILE_FLAG_OVERLAPPED,
+                                   NULL);
+
+  if (dir) {
+    uv__free(dir);
+    dir = NULL;
+  }
+
+  if (handle->dir_handle == INVALID_HANDLE_VALUE) {
+    last_error = GetLastError();
+    goto error;
+  }
+
+  if (CreateIoCompletionPort(handle->dir_handle,
+                             handle->loop->iocp,
+                             (ULONG_PTR)handle,
+                             0) == NULL) {
+    last_error = GetLastError();
+    goto error;
+  }
+
+  if (!handle->buffer) {
+    handle->buffer = (char*)uv__malloc(uv_directory_watcher_buffer_size);
+  }
+  if (!handle->buffer) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  memset(&(handle->req.u.io.overlapped), 0,
+         sizeof(handle->req.u.io.overlapped));
+
+  if (!ReadDirectoryChangesW(handle->dir_handle,
+                             handle->buffer,
+                             uv_directory_watcher_buffer_size,
+                             (flags & UV_FS_EVENT_RECURSIVE) ? TRUE : FALSE,
+                             FILE_NOTIFY_CHANGE_FILE_NAME      |
+                               FILE_NOTIFY_CHANGE_DIR_NAME     |
+                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
+                               FILE_NOTIFY_CHANGE_SIZE         |
+                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
+                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
+                               FILE_NOTIFY_CHANGE_CREATION     |
+                               FILE_NOTIFY_CHANGE_SECURITY,
+                             NULL,
+                             &handle->req.u.io.overlapped,
+                             NULL)) {
+    last_error = GetLastError();
+    goto error;
+  }
+
+  handle->req_pending = 1;
+  return 0;
+
+error:
+  if (handle->path) {
+    uv__free(handle->path);
+    handle->path = NULL;
+  }
+
+  if (handle->filew) {
+    uv__free(handle->filew);
+    handle->filew = NULL;
+  }
+
+  if (handle->short_filew) {
+    uv__free(handle->short_filew);
+    handle->short_filew = NULL;
+  }
+
+  uv__free(pathw);
+
+  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
+    CloseHandle(handle->dir_handle);
+    handle->dir_handle = INVALID_HANDLE_VALUE;
+  }
+
+  if (handle->buffer) {
+    uv__free(handle->buffer);
+    handle->buffer = NULL;
+  }
+
+  return uv_translate_sys_error(last_error);
+}
+
+
+int uv_fs_event_stop(uv_fs_event_t* handle) {
+  if (!uv__is_active(handle))
+    return 0;
+
+  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
+    CloseHandle(handle->dir_handle);
+    handle->dir_handle = INVALID_HANDLE_VALUE;
+  }
+
+  uv__handle_stop(handle);
+
+  if (handle->filew) {
+    uv__free(handle->filew);
+    handle->filew = NULL;
+  }
+
+  if (handle->short_filew) {
+    uv__free(handle->short_filew);
+    handle->short_filew = NULL;
+  }
+
+  if (handle->path) {
+    uv__free(handle->path);
+    handle->path = NULL;
+  }
+
+  if (handle->dirw) {
+    uv__free(handle->dirw);
+    handle->dirw = NULL;
+  }
+
+  return 0;
+}
+
+
+static int file_info_cmp(WCHAR* str, WCHAR* file_name, int file_name_len) {
+  int str_len;
+
+  str_len = wcslen(str);
+
+  /*
+    Since we only care about equality, return early if the strings
+    aren't the same length
+  */
+  if (str_len != (file_name_len / sizeof(WCHAR)))
+    return -1;
+
+  return _wcsnicmp(str, file_name, str_len);
+}
+
+
+void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req,
+    uv_fs_event_t* handle) {
+  FILE_NOTIFY_INFORMATION* file_info;
+  int err, sizew, size;
+  char* filename = NULL;
+  WCHAR* filenamew = NULL;
+  WCHAR* long_filenamew = NULL;
+  DWORD offset = 0;
+
+  assert(req->type == UV_FS_EVENT_REQ);
+  assert(handle->req_pending);
+  handle->req_pending = 0;
+
+  /* Don't report any callbacks if:
+   * - We're closing, just push the handle onto the endgame queue
+   * - We are not active, just ignore the callback
+   */
+  if (!uv__is_active(handle)) {
+    if (handle->flags & UV__HANDLE_CLOSING) {
+      uv_want_endgame(loop, (uv_handle_t*) handle);
+    }
+    return;
+  }
+
+  file_info = (FILE_NOTIFY_INFORMATION*)(handle->buffer + offset);
+
+  if (REQ_SUCCESS(req)) {
+    if (req->u.io.overlapped.InternalHigh > 0) {
+      do {
+        file_info = (FILE_NOTIFY_INFORMATION*)((char*)file_info + offset);
+        assert(!filename);
+        assert(!filenamew);
+        assert(!long_filenamew);
+
+        /*
+         * Fire the event only if we were asked to watch a directory,
+         * or if the filename filter matches.
+         */
+        if (handle->dirw ||
+            file_info_cmp(handle->filew,
+                          file_info->FileName,
+                          file_info->FileNameLength) == 0 ||
+            file_info_cmp(handle->short_filew,
+                          file_info->FileName,
+                          file_info->FileNameLength) == 0) {
+
+          if (handle->dirw) {
+            /*
+             * We attempt to resolve the long form of the file name explicitly.
+             * We only do this for file names that might still exist on disk.
+             * If this fails, we use the name given by ReadDirectoryChangesW.
+             * This may be the long form or the 8.3 short name in some cases.
+             */
+            if (file_info->Action != FILE_ACTION_REMOVED &&
+              file_info->Action != FILE_ACTION_RENAMED_OLD_NAME) {
+              /* Construct a full path to the file. */
+              size = wcslen(handle->dirw) +
+                file_info->FileNameLength / sizeof(WCHAR) + 2;
+
+              filenamew = (WCHAR*)uv__malloc(size * sizeof(WCHAR));
+              if (!filenamew) {
+                uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+              }
+
+              _snwprintf(filenamew, size, L"%s\\%.*s", handle->dirw,
+                file_info->FileNameLength / (DWORD)sizeof(WCHAR),
+                file_info->FileName);
+
+              filenamew[size - 1] = L'\0';
+
+              /* Convert to long name. */
+              size = GetLongPathNameW(filenamew, NULL, 0);
+
+              if (size) {
+                long_filenamew = (WCHAR*)uv__malloc(size * sizeof(WCHAR));
+                if (!long_filenamew) {
+                  uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+                }
+
+                size = GetLongPathNameW(filenamew, long_filenamew, size);
+                if (size) {
+                  long_filenamew[size] = '\0';
+                } else {
+                  uv__free(long_filenamew);
+                  long_filenamew = NULL;
+                }
+              }
+
+              uv__free(filenamew);
+
+              if (long_filenamew) {
+                /* Get the file name out of the long path. */
+                uv_relative_path(long_filenamew,
+                                 handle->dirw,
+                                 &filenamew);
+                uv__free(long_filenamew);
+                long_filenamew = filenamew;
+                sizew = -1;
+              } else {
+                /* We couldn't get the long filename, use the one reported. */
+                filenamew = file_info->FileName;
+                sizew = file_info->FileNameLength / sizeof(WCHAR);
+              }
+            } else {
+              /*
+               * Removed or renamed events cannot be resolved to the long form.
+               * We therefore use the name given by ReadDirectoryChangesW.
+               * This may be the long form or the 8.3 short name in some cases.
+               */
+              filenamew = file_info->FileName;
+              sizew = file_info->FileNameLength / sizeof(WCHAR);
+            }
+          } else {
+            /* We already have the long name of the file, so just use it. */
+            filenamew = handle->filew;
+            sizew = -1;
+          }
+
+          /* Convert the filename to utf8. */
+          uv__convert_utf16_to_utf8(filenamew, sizew, &filename);
+
+          switch (file_info->Action) {
+            case FILE_ACTION_ADDED:
+            case FILE_ACTION_REMOVED:
+            case FILE_ACTION_RENAMED_OLD_NAME:
+            case FILE_ACTION_RENAMED_NEW_NAME:
+              handle->cb(handle, filename, UV_RENAME, 0);
+              break;
+
+            case FILE_ACTION_MODIFIED:
+              handle->cb(handle, filename, UV_CHANGE, 0);
+              break;
+          }
+
+          uv__free(filename);
+          filename = NULL;
+          uv__free(long_filenamew);
+          long_filenamew = NULL;
+          filenamew = NULL;
+        }
+
+        offset = file_info->NextEntryOffset;
+      } while (offset && !(handle->flags & UV__HANDLE_CLOSING));
+    } else {
+      handle->cb(handle, NULL, UV_CHANGE, 0);
+    }
+  } else {
+    err = GET_REQ_ERROR(req);
+    handle->cb(handle, NULL, 0, uv_translate_sys_error(err));
+  }
+
+  if (!(handle->flags & UV__HANDLE_CLOSING)) {
+    uv_fs_event_queue_readdirchanges(loop, handle);
+  } else {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+}
+
+
+void uv_fs_event_close(uv_loop_t* loop, uv_fs_event_t* handle) {
+  uv_fs_event_stop(handle);
+
+  uv__handle_closing(handle);
+
+  if (!handle->req_pending) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+
+}
+
+
+void uv_fs_event_endgame(uv_loop_t* loop, uv_fs_event_t* handle) {
+  if ((handle->flags & UV__HANDLE_CLOSING) && !handle->req_pending) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+    if (handle->buffer) {
+      uv__free(handle->buffer);
+      handle->buffer = NULL;
+    }
+
+    uv__handle_close(handle);
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/fs.c b/Utilities/cmlibuv/src/win/fs.c
new file mode 100644
index 0000000..f1711ac
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/fs.c
@@ -0,0 +1,2496 @@
+/* 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 <assert.h>
+#include <stdlib.h>
+#include <direct.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <io.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <sys/utime.h>
+#include <stdio.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "req-inl.h"
+#include "handle-inl.h"
+
+#include <wincrypt.h>
+
+
+#define UV_FS_FREE_PATHS         0x0002
+#define UV_FS_FREE_PTR           0x0008
+#define UV_FS_CLEANEDUP          0x0010
+
+
+#define QUEUE_FS_TP_JOB(loop, req)                                          \
+  do {                                                                      \
+    uv__req_register(loop, req);                                            \
+    uv__work_submit((loop), &(req)->work_req, uv__fs_work, uv__fs_done);    \
+  } while (0)
+
+#define SET_REQ_RESULT(req, result_value)                                   \
+  do {                                                                      \
+    req->result = (result_value);                                           \
+    if (req->result == -1) {                                                \
+      req->sys_errno_ = _doserrno;                                          \
+      req->result = uv_translate_sys_error(req->sys_errno_);                \
+    }                                                                       \
+  } while (0)
+
+#define SET_REQ_WIN32_ERROR(req, sys_errno)                                 \
+  do {                                                                      \
+    req->sys_errno_ = (sys_errno);                                          \
+    req->result = uv_translate_sys_error(req->sys_errno_);                  \
+  } while (0)
+
+#define SET_REQ_UV_ERROR(req, uv_errno, sys_errno)                          \
+  do {                                                                      \
+    req->result = (uv_errno);                                               \
+    req->sys_errno_ = (sys_errno);                                          \
+  } while (0)
+
+#define VERIFY_FD(fd, req)                                                  \
+  if (fd == -1) {                                                           \
+    req->result = UV_EBADF;                                                 \
+    req->sys_errno_ = ERROR_INVALID_HANDLE;                                 \
+    return;                                                                 \
+  }
+
+#define FILETIME_TO_UINT(filetime)                                          \
+   (*((uint64_t*) &(filetime)) - 116444736000000000ULL)
+
+#define FILETIME_TO_TIME_T(filetime)                                        \
+   (FILETIME_TO_UINT(filetime) / 10000000ULL)
+
+#define FILETIME_TO_TIME_NS(filetime, secs)                                 \
+   ((FILETIME_TO_UINT(filetime) - (secs * 10000000ULL)) * 100)
+
+#define FILETIME_TO_TIMESPEC(ts, filetime)                                  \
+   do {                                                                     \
+     (ts).tv_sec = (long) FILETIME_TO_TIME_T(filetime);                     \
+     (ts).tv_nsec = (long) FILETIME_TO_TIME_NS(filetime, (ts).tv_sec);      \
+   } while(0)
+
+#define TIME_T_TO_FILETIME(time, filetime_ptr)                              \
+  do {                                                                      \
+    uint64_t bigtime = ((uint64_t) ((time) * 10000000ULL)) +                \
+                                  116444736000000000ULL;                    \
+    (filetime_ptr)->dwLowDateTime = bigtime & 0xFFFFFFFF;                   \
+    (filetime_ptr)->dwHighDateTime = bigtime >> 32;                         \
+  } while(0)
+
+#define IS_SLASH(c) ((c) == L'\\' || (c) == L'/')
+#define IS_LETTER(c) (((c) >= L'a' && (c) <= L'z') || \
+  ((c) >= L'A' && (c) <= L'Z'))
+
+const WCHAR JUNCTION_PREFIX[] = L"\\??\\";
+const WCHAR JUNCTION_PREFIX_LEN = 4;
+
+const WCHAR LONG_PATH_PREFIX[] = L"\\\\?\\";
+const WCHAR LONG_PATH_PREFIX_LEN = 4;
+
+const WCHAR UNC_PATH_PREFIX[] = L"\\\\?\\UNC\\";
+const WCHAR UNC_PATH_PREFIX_LEN = 8;
+
+
+void uv_fs_init() {
+  _fmode = _O_BINARY;
+}
+
+
+INLINE static int fs__capture_path(uv_fs_t* req, const char* path,
+    const char* new_path, const int copy_path) {
+  char* buf;
+  char* pos;
+  ssize_t buf_sz = 0, path_len, pathw_len = 0, new_pathw_len = 0;
+
+  /* new_path can only be set if path is also set. */
+  assert(new_path == NULL || path != NULL);
+
+  if (path != NULL) {
+    pathw_len = MultiByteToWideChar(CP_UTF8,
+                                    0,
+                                    path,
+                                    -1,
+                                    NULL,
+                                    0);
+    if (pathw_len == 0) {
+      return GetLastError();
+    }
+
+    buf_sz += pathw_len * sizeof(WCHAR);
+  }
+
+  if (path != NULL && copy_path) {
+    path_len = 1 + strlen(path);
+    buf_sz += path_len;
+  }
+
+  if (new_path != NULL) {
+    new_pathw_len = MultiByteToWideChar(CP_UTF8,
+                                        0,
+                                        new_path,
+                                        -1,
+                                        NULL,
+                                        0);
+    if (new_pathw_len == 0) {
+      return GetLastError();
+    }
+
+    buf_sz += new_pathw_len * sizeof(WCHAR);
+  }
+
+
+  if (buf_sz == 0) {
+    req->file.pathw = NULL;
+    req->fs.info.new_pathw = NULL;
+    req->path = NULL;
+    return 0;
+  }
+
+  buf = (char*) uv__malloc(buf_sz);
+  if (buf == NULL) {
+    return ERROR_OUTOFMEMORY;
+  }
+
+  pos = buf;
+
+  if (path != NULL) {
+    DWORD r = MultiByteToWideChar(CP_UTF8,
+                                  0,
+                                  path,
+                                  -1,
+                                  (WCHAR*) pos,
+                                  pathw_len);
+    assert(r == (DWORD) pathw_len);
+    req->file.pathw = (WCHAR*) pos;
+    pos += r * sizeof(WCHAR);
+  } else {
+    req->file.pathw = NULL;
+  }
+
+  if (new_path != NULL) {
+    DWORD r = MultiByteToWideChar(CP_UTF8,
+                                  0,
+                                  new_path,
+                                  -1,
+                                  (WCHAR*) pos,
+                                  new_pathw_len);
+    assert(r == (DWORD) new_pathw_len);
+    req->fs.info.new_pathw = (WCHAR*) pos;
+    pos += r * sizeof(WCHAR);
+  } else {
+    req->fs.info.new_pathw = NULL;
+  }
+
+  req->path = path;
+  if (path != NULL && copy_path) {
+    memcpy(pos, path, path_len);
+    assert(path_len == buf_sz - (pos - buf));
+    req->path = pos;
+  }
+
+  req->flags |= UV_FS_FREE_PATHS;
+
+  return 0;
+}
+
+
+
+INLINE static void uv_fs_req_init(uv_loop_t* loop, uv_fs_t* req,
+    uv_fs_type fs_type, const uv_fs_cb cb) {
+  uv_req_init(loop, (uv_req_t*) req);
+
+  req->type = UV_FS;
+  req->loop = loop;
+  req->flags = 0;
+  req->fs_type = fs_type;
+  req->result = 0;
+  req->ptr = NULL;
+  req->path = NULL;
+  req->cb = cb;
+  memset(&req->fs, 0, sizeof(req->fs));
+}
+
+
+static int fs__wide_to_utf8(WCHAR* w_source_ptr,
+                               DWORD w_source_len,
+                               char** target_ptr,
+                               uint64_t* target_len_ptr) {
+  int r;
+  int target_len;
+  char* target;
+  target_len = WideCharToMultiByte(CP_UTF8,
+                                   0,
+                                   w_source_ptr,
+                                   w_source_len,
+                                   NULL,
+                                   0,
+                                   NULL,
+                                   NULL);
+
+  if (target_len == 0) {
+    return -1;
+  }
+
+  if (target_len_ptr != NULL) {
+    *target_len_ptr = target_len;
+  }
+
+  if (target_ptr == NULL) {
+    return 0;
+  }
+
+  target = uv__malloc(target_len + 1);
+  if (target == NULL) {
+    SetLastError(ERROR_OUTOFMEMORY);
+    return -1;
+  }
+
+  r = WideCharToMultiByte(CP_UTF8,
+                          0,
+                          w_source_ptr,
+                          w_source_len,
+                          target,
+                          target_len,
+                          NULL,
+                          NULL);
+  assert(r == target_len);
+  target[target_len] = '\0';
+  *target_ptr = target;
+  return 0;
+}
+
+
+INLINE static int fs__readlink_handle(HANDLE handle, char** target_ptr,
+    uint64_t* target_len_ptr) {
+  char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+  REPARSE_DATA_BUFFER* reparse_data = (REPARSE_DATA_BUFFER*) buffer;
+  WCHAR* w_target;
+  DWORD w_target_len;
+  DWORD bytes;
+
+  if (!DeviceIoControl(handle,
+                       FSCTL_GET_REPARSE_POINT,
+                       NULL,
+                       0,
+                       buffer,
+                       sizeof buffer,
+                       &bytes,
+                       NULL)) {
+    return -1;
+  }
+
+  if (reparse_data->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
+    /* Real symlink */
+    w_target = reparse_data->SymbolicLinkReparseBuffer.PathBuffer +
+        (reparse_data->SymbolicLinkReparseBuffer.SubstituteNameOffset /
+        sizeof(WCHAR));
+    w_target_len =
+        reparse_data->SymbolicLinkReparseBuffer.SubstituteNameLength /
+        sizeof(WCHAR);
+
+    /* Real symlinks can contain pretty much everything, but the only thing */
+    /* we really care about is undoing the implicit conversion to an NT */
+    /* namespaced path that CreateSymbolicLink will perform on absolute */
+    /* paths. If the path is win32-namespaced then the user must have */
+    /* explicitly made it so, and we better just return the unmodified */
+    /* reparse data. */
+    if (w_target_len >= 4 &&
+        w_target[0] == L'\\' &&
+        w_target[1] == L'?' &&
+        w_target[2] == L'?' &&
+        w_target[3] == L'\\') {
+      /* Starts with \??\ */
+      if (w_target_len >= 6 &&
+          ((w_target[4] >= L'A' && w_target[4] <= L'Z') ||
+           (w_target[4] >= L'a' && w_target[4] <= L'z')) &&
+          w_target[5] == L':' &&
+          (w_target_len == 6 || w_target[6] == L'\\')) {
+        /* \??\<drive>:\ */
+        w_target += 4;
+        w_target_len -= 4;
+
+      } else if (w_target_len >= 8 &&
+                 (w_target[4] == L'U' || w_target[4] == L'u') &&
+                 (w_target[5] == L'N' || w_target[5] == L'n') &&
+                 (w_target[6] == L'C' || w_target[6] == L'c') &&
+                 w_target[7] == L'\\') {
+        /* \??\UNC\<server>\<share>\ - make sure the final path looks like */
+        /* \\<server>\<share>\ */
+        w_target += 6;
+        w_target[0] = L'\\';
+        w_target_len -= 6;
+      }
+    }
+
+  } else if (reparse_data->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
+    /* Junction. */
+    w_target = reparse_data->MountPointReparseBuffer.PathBuffer +
+        (reparse_data->MountPointReparseBuffer.SubstituteNameOffset /
+        sizeof(WCHAR));
+    w_target_len = reparse_data->MountPointReparseBuffer.SubstituteNameLength /
+        sizeof(WCHAR);
+
+    /* Only treat junctions that look like \??\<drive>:\ as symlink. */
+    /* Junctions can also be used as mount points, like \??\Volume{<guid>}, */
+    /* but that's confusing for programs since they wouldn't be able to */
+    /* actually understand such a path when returned by uv_readlink(). */
+    /* UNC paths are never valid for junctions so we don't care about them. */
+    if (!(w_target_len >= 6 &&
+          w_target[0] == L'\\' &&
+          w_target[1] == L'?' &&
+          w_target[2] == L'?' &&
+          w_target[3] == L'\\' &&
+          ((w_target[4] >= L'A' && w_target[4] <= L'Z') ||
+           (w_target[4] >= L'a' && w_target[4] <= L'z')) &&
+          w_target[5] == L':' &&
+          (w_target_len == 6 || w_target[6] == L'\\'))) {
+      SetLastError(ERROR_SYMLINK_NOT_SUPPORTED);
+      return -1;
+    }
+
+    /* Remove leading \??\ */
+    w_target += 4;
+    w_target_len -= 4;
+
+  } else {
+    /* Reparse tag does not indicate a symlink. */
+    SetLastError(ERROR_SYMLINK_NOT_SUPPORTED);
+    return -1;
+  }
+
+  return fs__wide_to_utf8(w_target, w_target_len, target_ptr, target_len_ptr);
+}
+
+
+void fs__open(uv_fs_t* req) {
+  DWORD access;
+  DWORD share;
+  DWORD disposition;
+  DWORD attributes = 0;
+  HANDLE file;
+  int fd, current_umask;
+  int flags = req->fs.info.file_flags;
+
+  /* Obtain the active umask. umask() never fails and returns the previous */
+  /* umask. */
+  current_umask = umask(0);
+  umask(current_umask);
+
+  /* convert flags and mode to CreateFile parameters */
+  switch (flags & (_O_RDONLY | _O_WRONLY | _O_RDWR)) {
+  case _O_RDONLY:
+    access = FILE_GENERIC_READ;
+    attributes |= FILE_FLAG_BACKUP_SEMANTICS;
+    break;
+  case _O_WRONLY:
+    access = FILE_GENERIC_WRITE;
+    break;
+  case _O_RDWR:
+    access = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
+    break;
+  default:
+    goto einval;
+  }
+
+  if (flags & _O_APPEND) {
+    access &= ~FILE_WRITE_DATA;
+    access |= FILE_APPEND_DATA;
+    attributes &= ~FILE_FLAG_BACKUP_SEMANTICS;
+  }
+
+  /*
+   * Here is where we deviate significantly from what CRT's _open()
+   * does. We indiscriminately use all the sharing modes, to match
+   * UNIX semantics. In particular, this ensures that the file can
+   * be deleted even whilst it's open, fixing issue #1449.
+   */
+  share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
+
+  switch (flags & (_O_CREAT | _O_EXCL | _O_TRUNC)) {
+  case 0:
+  case _O_EXCL:
+    disposition = OPEN_EXISTING;
+    break;
+  case _O_CREAT:
+    disposition = OPEN_ALWAYS;
+    break;
+  case _O_CREAT | _O_EXCL:
+  case _O_CREAT | _O_TRUNC | _O_EXCL:
+    disposition = CREATE_NEW;
+    break;
+  case _O_TRUNC:
+  case _O_TRUNC | _O_EXCL:
+    disposition = TRUNCATE_EXISTING;
+    break;
+  case _O_CREAT | _O_TRUNC:
+    disposition = CREATE_ALWAYS;
+    break;
+  default:
+    goto einval;
+  }
+
+  attributes |= FILE_ATTRIBUTE_NORMAL;
+  if (flags & _O_CREAT) {
+    if (!((req->fs.info.mode & ~current_umask) & _S_IWRITE)) {
+      attributes |= FILE_ATTRIBUTE_READONLY;
+    }
+  }
+
+  if (flags & _O_TEMPORARY ) {
+    attributes |= FILE_FLAG_DELETE_ON_CLOSE | FILE_ATTRIBUTE_TEMPORARY;
+    access |= DELETE;
+  }
+
+  if (flags & _O_SHORT_LIVED) {
+    attributes |= FILE_ATTRIBUTE_TEMPORARY;
+  }
+
+  switch (flags & (_O_SEQUENTIAL | _O_RANDOM)) {
+  case 0:
+    break;
+  case _O_SEQUENTIAL:
+    attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
+    break;
+  case _O_RANDOM:
+    attributes |= FILE_FLAG_RANDOM_ACCESS;
+    break;
+  default:
+    goto einval;
+  }
+
+  /* Setting this flag makes it possible to open a directory. */
+  attributes |= FILE_FLAG_BACKUP_SEMANTICS;
+
+  file = CreateFileW(req->file.pathw,
+                     access,
+                     share,
+                     NULL,
+                     disposition,
+                     attributes,
+                     NULL);
+  if (file == INVALID_HANDLE_VALUE) {
+    DWORD error = GetLastError();
+    if (error == ERROR_FILE_EXISTS && (flags & _O_CREAT) &&
+        !(flags & _O_EXCL)) {
+      /* Special case: when ERROR_FILE_EXISTS happens and O_CREAT was */
+      /* specified, it means the path referred to a directory. */
+      SET_REQ_UV_ERROR(req, UV_EISDIR, error);
+    } else {
+      SET_REQ_WIN32_ERROR(req, GetLastError());
+    }
+    return;
+  }
+
+  fd = _open_osfhandle((intptr_t) file, flags);
+  if (fd < 0) {
+    /* The only known failure mode for _open_osfhandle() is EMFILE, in which
+     * case GetLastError() will return zero. However we'll try to handle other
+     * errors as well, should they ever occur.
+     */
+    if (errno == EMFILE)
+      SET_REQ_UV_ERROR(req, UV_EMFILE, ERROR_TOO_MANY_OPEN_FILES);
+    else if (GetLastError() != ERROR_SUCCESS)
+      SET_REQ_WIN32_ERROR(req, GetLastError());
+    else
+      SET_REQ_WIN32_ERROR(req, UV_UNKNOWN);
+    CloseHandle(file);
+    return;
+  }
+
+  SET_REQ_RESULT(req, fd);
+  return;
+
+ einval:
+  SET_REQ_UV_ERROR(req, UV_EINVAL, ERROR_INVALID_PARAMETER);
+}
+
+void fs__close(uv_fs_t* req) {
+  int fd = req->file.fd;
+  int result;
+
+  VERIFY_FD(fd, req);
+
+  if (fd > 2)
+    result = _close(fd);
+  else
+    result = 0;
+
+  /* _close doesn't set _doserrno on failure, but it does always set errno
+   * to EBADF on failure.
+   */
+  if (result == -1) {
+    assert(errno == EBADF);
+    SET_REQ_UV_ERROR(req, UV_EBADF, ERROR_INVALID_HANDLE);
+  } else {
+    req->result = 0;
+  }
+}
+
+
+void fs__read(uv_fs_t* req) {
+  int fd = req->file.fd;
+  int64_t offset = req->fs.info.offset;
+  HANDLE handle;
+  OVERLAPPED overlapped, *overlapped_ptr;
+  LARGE_INTEGER offset_;
+  DWORD bytes;
+  DWORD error;
+  int result;
+  unsigned int index;
+
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, ERROR_INVALID_HANDLE);
+    return;
+  }
+
+  if (offset != -1) {
+    memset(&overlapped, 0, sizeof overlapped);
+    overlapped_ptr = &overlapped;
+  } else {
+    overlapped_ptr = NULL;
+  }
+
+  index = 0;
+  bytes = 0;
+  do {
+    DWORD incremental_bytes;
+
+    if (offset != -1) {
+      offset_.QuadPart = offset + bytes;
+      overlapped.Offset = offset_.LowPart;
+      overlapped.OffsetHigh = offset_.HighPart;
+    }
+
+    result = ReadFile(handle,
+                      req->fs.info.bufs[index].base,
+                      req->fs.info.bufs[index].len,
+                      &incremental_bytes,
+                      overlapped_ptr);
+    bytes += incremental_bytes;
+    ++index;
+  } while (result && index < req->fs.info.nbufs);
+
+  if (result || bytes > 0) {
+    SET_REQ_RESULT(req, bytes);
+  } else {
+    error = GetLastError();
+    if (error == ERROR_HANDLE_EOF) {
+      SET_REQ_RESULT(req, bytes);
+    } else {
+      SET_REQ_WIN32_ERROR(req, error);
+    }
+  }
+}
+
+
+void fs__write(uv_fs_t* req) {
+  int fd = req->file.fd;
+  int64_t offset = req->fs.info.offset;
+  HANDLE handle;
+  OVERLAPPED overlapped, *overlapped_ptr;
+  LARGE_INTEGER offset_;
+  DWORD bytes;
+  int result;
+  unsigned int index;
+
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, ERROR_INVALID_HANDLE);
+    return;
+  }
+
+  if (offset != -1) {
+    memset(&overlapped, 0, sizeof overlapped);
+    overlapped_ptr = &overlapped;
+  } else {
+    overlapped_ptr = NULL;
+  }
+
+  index = 0;
+  bytes = 0;
+  do {
+    DWORD incremental_bytes;
+
+    if (offset != -1) {
+      offset_.QuadPart = offset + bytes;
+      overlapped.Offset = offset_.LowPart;
+      overlapped.OffsetHigh = offset_.HighPart;
+    }
+
+    result = WriteFile(handle,
+                       req->fs.info.bufs[index].base,
+                       req->fs.info.bufs[index].len,
+                       &incremental_bytes,
+                       overlapped_ptr);
+    bytes += incremental_bytes;
+    ++index;
+  } while (result && index < req->fs.info.nbufs);
+
+  if (result || bytes > 0) {
+    SET_REQ_RESULT(req, bytes);
+  } else {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+  }
+}
+
+
+void fs__rmdir(uv_fs_t* req) {
+  int result = _wrmdir(req->file.pathw);
+  SET_REQ_RESULT(req, result);
+}
+
+
+void fs__unlink(uv_fs_t* req) {
+  const WCHAR* pathw = req->file.pathw;
+  HANDLE handle;
+  BY_HANDLE_FILE_INFORMATION info;
+  FILE_DISPOSITION_INFORMATION disposition;
+  IO_STATUS_BLOCK iosb;
+  NTSTATUS status;
+
+  handle = CreateFileW(pathw,
+                       FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | DELETE,
+                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+                       NULL,
+                       OPEN_EXISTING,
+                       FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
+                       NULL);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  if (!GetFileInformationByHandle(handle, &info)) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    CloseHandle(handle);
+    return;
+  }
+
+  if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
+    /* Do not allow deletion of directories, unless it is a symlink. When */
+    /* the path refers to a non-symlink directory, report EPERM as mandated */
+    /* by POSIX.1. */
+
+    /* Check if it is a reparse point. If it's not, it's a normal directory. */
+    if (!(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
+      SET_REQ_WIN32_ERROR(req, ERROR_ACCESS_DENIED);
+      CloseHandle(handle);
+      return;
+    }
+
+    /* Read the reparse point and check if it is a valid symlink. */
+    /* If not, don't unlink. */
+    if (fs__readlink_handle(handle, NULL, NULL) < 0) {
+      DWORD error = GetLastError();
+      if (error == ERROR_SYMLINK_NOT_SUPPORTED)
+        error = ERROR_ACCESS_DENIED;
+      SET_REQ_WIN32_ERROR(req, error);
+      CloseHandle(handle);
+      return;
+    }
+  }
+
+  if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
+    /* Remove read-only attribute */
+    FILE_BASIC_INFORMATION basic = { 0 };
+
+    basic.FileAttributes = info.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY);
+
+    status = pNtSetInformationFile(handle,
+                                   &iosb,
+                                   &basic,
+                                   sizeof basic,
+                                   FileBasicInformation);
+    if (!NT_SUCCESS(status)) {
+      SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status));
+      CloseHandle(handle);
+      return;
+    }
+  }
+
+  /* Try to set the delete flag. */
+  disposition.DeleteFile = TRUE;
+  status = pNtSetInformationFile(handle,
+                                 &iosb,
+                                 &disposition,
+                                 sizeof disposition,
+                                 FileDispositionInformation);
+  if (NT_SUCCESS(status)) {
+    SET_REQ_SUCCESS(req);
+  } else {
+    SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status));
+  }
+
+  CloseHandle(handle);
+}
+
+
+void fs__mkdir(uv_fs_t* req) {
+  /* TODO: use req->mode. */
+  int result = _wmkdir(req->file.pathw);
+  SET_REQ_RESULT(req, result);
+}
+
+
+/* OpenBSD original: lib/libc/stdio/mktemp.c */
+void fs__mkdtemp(uv_fs_t* req) {
+  static const WCHAR *tempchars =
+    L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+  static const size_t num_chars = 62;
+  static const size_t num_x = 6;
+  WCHAR *cp, *ep;
+  unsigned int tries, i;
+  size_t len;
+  HCRYPTPROV h_crypt_prov;
+  uint64_t v;
+  BOOL released;
+
+  len = wcslen(req->file.pathw);
+  ep = req->file.pathw + len;
+  if (len < num_x || wcsncmp(ep - num_x, L"XXXXXX", num_x)) {
+    SET_REQ_UV_ERROR(req, UV_EINVAL, ERROR_INVALID_PARAMETER);
+    return;
+  }
+
+  if (!CryptAcquireContext(&h_crypt_prov, NULL, NULL, PROV_RSA_FULL,
+                           CRYPT_VERIFYCONTEXT)) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  tries = TMP_MAX;
+  do {
+    if (!CryptGenRandom(h_crypt_prov, sizeof(v), (BYTE*) &v)) {
+      SET_REQ_WIN32_ERROR(req, GetLastError());
+      break;
+    }
+
+    cp = ep - num_x;
+    for (i = 0; i < num_x; i++) {
+      *cp++ = tempchars[v % num_chars];
+      v /= num_chars;
+    }
+
+    if (_wmkdir(req->file.pathw) == 0) {
+      len = strlen(req->path);
+      wcstombs((char*) req->path + len - num_x, ep - num_x, num_x);
+      SET_REQ_RESULT(req, 0);
+      break;
+    } else if (errno != EEXIST) {
+      SET_REQ_RESULT(req, -1);
+      break;
+    }
+  } while (--tries);
+
+  released = CryptReleaseContext(h_crypt_prov, 0);
+  assert(released);
+  if (tries == 0) {
+    SET_REQ_RESULT(req, -1);
+  }
+}
+
+
+void fs__scandir(uv_fs_t* req) {
+  static const size_t dirents_initial_size = 32;
+
+  HANDLE dir_handle = INVALID_HANDLE_VALUE;
+
+  uv__dirent_t** dirents = NULL;
+  size_t dirents_size = 0;
+  size_t dirents_used = 0;
+
+  IO_STATUS_BLOCK iosb;
+  NTSTATUS status;
+
+  /* Buffer to hold directory entries returned by NtQueryDirectoryFile.
+   * It's important that this buffer can hold at least one entry, regardless
+   * of the length of the file names present in the enumerated directory.
+   * A file name is at most 256 WCHARs long.
+   * According to MSDN, the buffer must be aligned at an 8-byte boundary.
+   */
+#if _MSC_VER
+  __declspec(align(8)) char buffer[8192];
+#else
+  __attribute__ ((aligned (8))) char buffer[8192];
+#endif
+
+  STATIC_ASSERT(sizeof buffer >=
+                sizeof(FILE_DIRECTORY_INFORMATION) + 256 * sizeof(WCHAR));
+
+  /* Open the directory. */
+  dir_handle =
+      CreateFileW(req->file.pathw,
+                  FILE_LIST_DIRECTORY | SYNCHRONIZE,
+                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+                  NULL,
+                  OPEN_EXISTING,
+                  FILE_FLAG_BACKUP_SEMANTICS,
+                  NULL);
+  if (dir_handle == INVALID_HANDLE_VALUE)
+    goto win32_error;
+
+  /* Read the first chunk. */
+  status = pNtQueryDirectoryFile(dir_handle,
+                                 NULL,
+                                 NULL,
+                                 NULL,
+                                 &iosb,
+                                 &buffer,
+                                 sizeof buffer,
+                                 FileDirectoryInformation,
+                                 FALSE,
+                                 NULL,
+                                 TRUE);
+
+  /* If the handle is not a directory, we'll get STATUS_INVALID_PARAMETER.
+   * This should be reported back as UV_ENOTDIR.
+   */
+  if (status == STATUS_INVALID_PARAMETER)
+    goto not_a_directory_error;
+
+  while (NT_SUCCESS(status)) {
+    char* position = buffer;
+    size_t next_entry_offset = 0;
+
+    do {
+      FILE_DIRECTORY_INFORMATION* info;
+      uv__dirent_t* dirent;
+
+      size_t wchar_len;
+      size_t utf8_len;
+
+      /* Obtain a pointer to the current directory entry. */
+      position += next_entry_offset;
+      info = (FILE_DIRECTORY_INFORMATION*) position;
+
+      /* Fetch the offset to the next directory entry. */
+      next_entry_offset = info->NextEntryOffset;
+
+      /* Compute the length of the filename in WCHARs. */
+      wchar_len = info->FileNameLength / sizeof info->FileName[0];
+
+      /* Skip over '.' and '..' entries.  It has been reported that
+       * the SharePoint driver includes the terminating zero byte in
+       * the filename length.  Strip those first.
+       */
+      while (wchar_len > 0 && info->FileName[wchar_len - 1] == L'\0')
+        wchar_len -= 1;
+
+      if (wchar_len == 0)
+        continue;
+      if (wchar_len == 1 && info->FileName[0] == L'.')
+        continue;
+      if (wchar_len == 2 && info->FileName[0] == L'.' &&
+          info->FileName[1] == L'.')
+        continue;
+
+      /* Compute the space required to store the filename as UTF-8. */
+      utf8_len = WideCharToMultiByte(
+          CP_UTF8, 0, &info->FileName[0], wchar_len, NULL, 0, NULL, NULL);
+      if (utf8_len == 0)
+        goto win32_error;
+
+      /* Resize the dirent array if needed. */
+      if (dirents_used >= dirents_size) {
+        size_t new_dirents_size =
+            dirents_size == 0 ? dirents_initial_size : dirents_size << 1;
+        uv__dirent_t** new_dirents =
+            uv__realloc(dirents, new_dirents_size * sizeof *dirents);
+
+        if (new_dirents == NULL)
+          goto out_of_memory_error;
+
+        dirents_size = new_dirents_size;
+        dirents = new_dirents;
+      }
+
+      /* Allocate space for the uv dirent structure. The dirent structure
+       * includes room for the first character of the filename, but `utf8_len`
+       * doesn't count the NULL terminator at this point.
+       */
+      dirent = uv__malloc(sizeof *dirent + utf8_len);
+      if (dirent == NULL)
+        goto out_of_memory_error;
+
+      dirents[dirents_used++] = dirent;
+
+      /* Convert file name to UTF-8. */
+      if (WideCharToMultiByte(CP_UTF8,
+                              0,
+                              &info->FileName[0],
+                              wchar_len,
+                              &dirent->d_name[0],
+                              utf8_len,
+                              NULL,
+                              NULL) == 0)
+        goto win32_error;
+
+      /* Add a null terminator to the filename. */
+      dirent->d_name[utf8_len] = '\0';
+
+      /* Fill out the type field. */
+      if (info->FileAttributes & FILE_ATTRIBUTE_DEVICE)
+        dirent->d_type = UV__DT_CHAR;
+      else if (info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+        dirent->d_type = UV__DT_LINK;
+      else if (info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+        dirent->d_type = UV__DT_DIR;
+      else
+        dirent->d_type = UV__DT_FILE;
+    } while (next_entry_offset != 0);
+
+    /* Read the next chunk. */
+    status = pNtQueryDirectoryFile(dir_handle,
+                                   NULL,
+                                   NULL,
+                                   NULL,
+                                   &iosb,
+                                   &buffer,
+                                   sizeof buffer,
+                                   FileDirectoryInformation,
+                                   FALSE,
+                                   NULL,
+                                   FALSE);
+
+    /* After the first pNtQueryDirectoryFile call, the function may return
+     * STATUS_SUCCESS even if the buffer was too small to hold at least one
+     * directory entry.
+     */
+    if (status == STATUS_SUCCESS && iosb.Information == 0)
+      status = STATUS_BUFFER_OVERFLOW;
+  }
+
+  if (status != STATUS_NO_MORE_FILES)
+    goto nt_error;
+
+  CloseHandle(dir_handle);
+
+  /* Store the result in the request object. */
+  req->ptr = dirents;
+  if (dirents != NULL)
+    req->flags |= UV_FS_FREE_PTR;
+
+  SET_REQ_RESULT(req, dirents_used);
+
+  /* `nbufs` will be used as index by uv_fs_scandir_next. */
+  req->fs.info.nbufs = 0;
+
+  return;
+
+nt_error:
+  SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status));
+  goto cleanup;
+
+win32_error:
+  SET_REQ_WIN32_ERROR(req, GetLastError());
+  goto cleanup;
+
+not_a_directory_error:
+  SET_REQ_UV_ERROR(req, UV_ENOTDIR, ERROR_DIRECTORY);
+  goto cleanup;
+
+out_of_memory_error:
+  SET_REQ_UV_ERROR(req, UV_ENOMEM, ERROR_OUTOFMEMORY);
+  goto cleanup;
+
+cleanup:
+  if (dir_handle != INVALID_HANDLE_VALUE)
+    CloseHandle(dir_handle);
+  while (dirents_used > 0)
+    uv__free(dirents[--dirents_used]);
+  if (dirents != NULL)
+    uv__free(dirents);
+}
+
+
+INLINE static int fs__stat_handle(HANDLE handle, uv_stat_t* statbuf) {
+  FILE_ALL_INFORMATION file_info;
+  FILE_FS_VOLUME_INFORMATION volume_info;
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+
+  nt_status = pNtQueryInformationFile(handle,
+                                      &io_status,
+                                      &file_info,
+                                      sizeof file_info,
+                                      FileAllInformation);
+
+  /* Buffer overflow (a warning status code) is expected here. */
+  if (NT_ERROR(nt_status)) {
+    SetLastError(pRtlNtStatusToDosError(nt_status));
+    return -1;
+  }
+
+  nt_status = pNtQueryVolumeInformationFile(handle,
+                                            &io_status,
+                                            &volume_info,
+                                            sizeof volume_info,
+                                            FileFsVolumeInformation);
+
+  /* Buffer overflow (a warning status code) is expected here. */
+  if (io_status.Status == STATUS_NOT_IMPLEMENTED) {
+    statbuf->st_dev = 0;
+  } else if (NT_ERROR(nt_status)) {
+    SetLastError(pRtlNtStatusToDosError(nt_status));
+    return -1;
+  } else {
+    statbuf->st_dev = volume_info.VolumeSerialNumber;
+  }
+
+  /* Todo: st_mode should probably always be 0666 for everyone. We might also
+   * want to report 0777 if the file is a .exe or a directory.
+   *
+   * Currently it's based on whether the 'readonly' attribute is set, which
+   * makes little sense because the semantics are so different: the 'read-only'
+   * flag is just a way for a user to protect against accidental deletion, and
+   * serves no security purpose. Windows uses ACLs for that.
+   *
+   * Also people now use uv_fs_chmod() to take away the writable bit for good
+   * reasons. Windows however just makes the file read-only, which makes it
+   * impossible to delete the file afterwards, since read-only files can't be
+   * deleted.
+   *
+   * IOW it's all just a clusterfuck and we should think of something that
+   * makes slightly more sense.
+   *
+   * And uv_fs_chmod should probably just fail on windows or be a total no-op.
+   * There's nothing sensible it can do anyway.
+   */
+  statbuf->st_mode = 0;
+
+  if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+    /*
+     * It is possible for a file to have FILE_ATTRIBUTE_REPARSE_POINT but not have
+     * any link data. In that case DeviceIoControl() in fs__readlink_handle() sets
+     * the last error to ERROR_NOT_A_REPARSE_POINT. Then the stat result mode
+     * calculated below will indicate a normal directory or file, as if
+     * FILE_ATTRIBUTE_REPARSE_POINT was not present.
+     */
+    if (fs__readlink_handle(handle, NULL, &statbuf->st_size) == 0) {
+      statbuf->st_mode |= S_IFLNK;
+    } else if (GetLastError() != ERROR_NOT_A_REPARSE_POINT) {
+      return -1;
+    }
+  }
+
+  if (statbuf->st_mode == 0) {
+    if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
+      statbuf->st_mode |= _S_IFDIR;
+      statbuf->st_size = 0;
+    } else {
+      statbuf->st_mode |= _S_IFREG;
+      statbuf->st_size = file_info.StandardInformation.EndOfFile.QuadPart;
+    }
+  }
+
+  if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_READONLY)
+    statbuf->st_mode |= _S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6);
+  else
+    statbuf->st_mode |= (_S_IREAD | _S_IWRITE) | ((_S_IREAD | _S_IWRITE) >> 3) |
+                        ((_S_IREAD | _S_IWRITE) >> 6);
+
+  FILETIME_TO_TIMESPEC(statbuf->st_atim, file_info.BasicInformation.LastAccessTime);
+  FILETIME_TO_TIMESPEC(statbuf->st_ctim, file_info.BasicInformation.ChangeTime);
+  FILETIME_TO_TIMESPEC(statbuf->st_mtim, file_info.BasicInformation.LastWriteTime);
+  FILETIME_TO_TIMESPEC(statbuf->st_birthtim, file_info.BasicInformation.CreationTime);
+
+  statbuf->st_ino = file_info.InternalInformation.IndexNumber.QuadPart;
+
+  /* st_blocks contains the on-disk allocation size in 512-byte units. */
+  statbuf->st_blocks =
+      file_info.StandardInformation.AllocationSize.QuadPart >> 9ULL;
+
+  statbuf->st_nlink = file_info.StandardInformation.NumberOfLinks;
+
+  /* The st_blksize is supposed to be the 'optimal' number of bytes for reading
+   * and writing to the disk. That is, for any definition of 'optimal' - it's
+   * supposed to at least avoid read-update-write behavior when writing to the
+   * disk.
+   *
+   * However nobody knows this and even fewer people actually use this value,
+   * and in order to fill it out we'd have to make another syscall to query the
+   * volume for FILE_FS_SECTOR_SIZE_INFORMATION.
+   *
+   * Therefore we'll just report a sensible value that's quite commonly okay
+   * on modern hardware.
+   */
+  statbuf->st_blksize = 2048;
+
+  /* Todo: set st_flags to something meaningful. Also provide a wrapper for
+   * chattr(2).
+   */
+  statbuf->st_flags = 0;
+
+  /* Windows has nothing sensible to say about these values, so they'll just
+   * remain empty.
+   */
+  statbuf->st_gid = 0;
+  statbuf->st_uid = 0;
+  statbuf->st_rdev = 0;
+  statbuf->st_gen = 0;
+
+  return 0;
+}
+
+
+INLINE static void fs__stat_prepare_path(WCHAR* pathw) {
+  size_t len = wcslen(pathw);
+
+  /* TODO: ignore namespaced paths. */
+  if (len > 1 && pathw[len - 2] != L':' &&
+      (pathw[len - 1] == L'\\' || pathw[len - 1] == L'/')) {
+    pathw[len - 1] = '\0';
+  }
+}
+
+
+INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) {
+  HANDLE handle;
+  DWORD flags;
+
+  flags = FILE_FLAG_BACKUP_SEMANTICS;
+  if (do_lstat) {
+    flags |= FILE_FLAG_OPEN_REPARSE_POINT;
+  }
+
+  handle = CreateFileW(req->file.pathw,
+                       FILE_READ_ATTRIBUTES,
+                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+                       NULL,
+                       OPEN_EXISTING,
+                       flags,
+                       NULL);
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  if (fs__stat_handle(handle, &req->statbuf) != 0) {
+    DWORD error = GetLastError();
+    if (do_lstat && error == ERROR_SYMLINK_NOT_SUPPORTED) {
+      /* We opened a reparse point but it was not a symlink. Try again. */
+      fs__stat_impl(req, 0);
+
+    } else {
+      /* Stat failed. */
+      SET_REQ_WIN32_ERROR(req, GetLastError());
+    }
+
+    CloseHandle(handle);
+    return;
+  }
+
+  req->ptr = &req->statbuf;
+  req->result = 0;
+  CloseHandle(handle);
+}
+
+
+static void fs__stat(uv_fs_t* req) {
+  fs__stat_prepare_path(req->file.pathw);
+  fs__stat_impl(req, 0);
+}
+
+
+static void fs__lstat(uv_fs_t* req) {
+  fs__stat_prepare_path(req->file.pathw);
+  fs__stat_impl(req, 1);
+}
+
+
+static void fs__fstat(uv_fs_t* req) {
+  int fd = req->file.fd;
+  HANDLE handle;
+
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, ERROR_INVALID_HANDLE);
+    return;
+  }
+
+  if (fs__stat_handle(handle, &req->statbuf) != 0) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  req->ptr = &req->statbuf;
+  req->result = 0;
+}
+
+
+static void fs__rename(uv_fs_t* req) {
+  if (!MoveFileExW(req->file.pathw, req->fs.info.new_pathw, MOVEFILE_REPLACE_EXISTING)) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  SET_REQ_RESULT(req, 0);
+}
+
+
+INLINE static void fs__sync_impl(uv_fs_t* req) {
+  int fd = req->file.fd;
+  int result;
+
+  VERIFY_FD(fd, req);
+
+  result = FlushFileBuffers(uv__get_osfhandle(fd)) ? 0 : -1;
+  if (result == -1) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+  } else {
+    SET_REQ_RESULT(req, result);
+  }
+}
+
+
+static void fs__fsync(uv_fs_t* req) {
+  fs__sync_impl(req);
+}
+
+
+static void fs__fdatasync(uv_fs_t* req) {
+  fs__sync_impl(req);
+}
+
+
+static void fs__ftruncate(uv_fs_t* req) {
+  int fd = req->file.fd;
+  HANDLE handle;
+  NTSTATUS status;
+  IO_STATUS_BLOCK io_status;
+  FILE_END_OF_FILE_INFORMATION eof_info;
+
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+
+  eof_info.EndOfFile.QuadPart = req->fs.info.offset;
+
+  status = pNtSetInformationFile(handle,
+                                 &io_status,
+                                 &eof_info,
+                                 sizeof eof_info,
+                                 FileEndOfFileInformation);
+
+  if (NT_SUCCESS(status)) {
+    SET_REQ_RESULT(req, 0);
+  } else {
+    SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status));
+  }
+}
+
+
+static void fs__sendfile(uv_fs_t* req) {
+  int fd_in = req->file.fd, fd_out = req->fs.info.fd_out;
+  size_t length = req->fs.info.bufsml[0].len;
+  int64_t offset = req->fs.info.offset;
+  const size_t max_buf_size = 65536;
+  size_t buf_size = length < max_buf_size ? length : max_buf_size;
+  int n, result = 0;
+  int64_t result_offset = 0;
+  char* buf = (char*) uv__malloc(buf_size);
+  if (!buf) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  if (offset != -1) {
+    result_offset = _lseeki64(fd_in, offset, SEEK_SET);
+  }
+
+  if (result_offset == -1) {
+    result = -1;
+  } else {
+    while (length > 0) {
+      n = _read(fd_in, buf, length < buf_size ? length : buf_size);
+      if (n == 0) {
+        break;
+      } else if (n == -1) {
+        result = -1;
+        break;
+      }
+
+      length -= n;
+
+      n = _write(fd_out, buf, n);
+      if (n == -1) {
+        result = -1;
+        break;
+      }
+
+      result += n;
+    }
+  }
+
+  uv__free(buf);
+
+  SET_REQ_RESULT(req, result);
+}
+
+
+static void fs__access(uv_fs_t* req) {
+  DWORD attr = GetFileAttributesW(req->file.pathw);
+
+  if (attr == INVALID_FILE_ATTRIBUTES) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  /*
+   * Access is possible if
+   * - write access wasn't requested,
+   * - or the file isn't read-only,
+   * - or it's a directory.
+   * (Directories cannot be read-only on Windows.)
+   */
+  if (!(req->flags & W_OK) ||
+      !(attr & FILE_ATTRIBUTE_READONLY) ||
+      (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+    SET_REQ_RESULT(req, 0);
+  } else {
+    SET_REQ_WIN32_ERROR(req, UV_EPERM);
+  }
+
+}
+
+
+static void fs__chmod(uv_fs_t* req) {
+  int result = _wchmod(req->file.pathw, req->fs.info.mode);
+  SET_REQ_RESULT(req, result);
+}
+
+
+static void fs__fchmod(uv_fs_t* req) {
+  int fd = req->file.fd;
+  HANDLE handle;
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+  FILE_BASIC_INFORMATION file_info;
+
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+
+  nt_status = pNtQueryInformationFile(handle,
+                                      &io_status,
+                                      &file_info,
+                                      sizeof file_info,
+                                      FileBasicInformation);
+
+  if (!NT_SUCCESS(nt_status)) {
+    SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(nt_status));
+    return;
+  }
+
+  if (req->fs.info.mode & _S_IWRITE) {
+    file_info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
+  } else {
+    file_info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
+  }
+
+  nt_status = pNtSetInformationFile(handle,
+                                    &io_status,
+                                    &file_info,
+                                    sizeof file_info,
+                                    FileBasicInformation);
+
+  if (!NT_SUCCESS(nt_status)) {
+    SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(nt_status));
+    return;
+  }
+
+  SET_REQ_SUCCESS(req);
+}
+
+
+INLINE static int fs__utime_handle(HANDLE handle, double atime, double mtime) {
+  FILETIME filetime_a, filetime_m;
+
+  TIME_T_TO_FILETIME(atime, &filetime_a);
+  TIME_T_TO_FILETIME(mtime, &filetime_m);
+
+  if (!SetFileTime(handle, NULL, &filetime_a, &filetime_m)) {
+    return -1;
+  }
+
+  return 0;
+}
+
+
+static void fs__utime(uv_fs_t* req) {
+  HANDLE handle;
+
+  handle = CreateFileW(req->file.pathw,
+                       FILE_WRITE_ATTRIBUTES,
+                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+                       NULL,
+                       OPEN_EXISTING,
+                       FILE_FLAG_BACKUP_SEMANTICS,
+                       NULL);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    CloseHandle(handle);
+    return;
+  }
+
+  CloseHandle(handle);
+
+  req->result = 0;
+}
+
+
+static void fs__futime(uv_fs_t* req) {
+  int fd = req->file.fd;
+  HANDLE handle;
+  VERIFY_FD(fd, req);
+
+  handle = uv__get_osfhandle(fd);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, ERROR_INVALID_HANDLE);
+    return;
+  }
+
+  if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  req->result = 0;
+}
+
+
+static void fs__link(uv_fs_t* req) {
+  DWORD r = CreateHardLinkW(req->fs.info.new_pathw, req->file.pathw, NULL);
+  if (r == 0) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+  } else {
+    req->result = 0;
+  }
+}
+
+
+static void fs__create_junction(uv_fs_t* req, const WCHAR* path,
+    const WCHAR* new_path) {
+  HANDLE handle = INVALID_HANDLE_VALUE;
+  REPARSE_DATA_BUFFER *buffer = NULL;
+  int created = 0;
+  int target_len;
+  int is_absolute, is_long_path;
+  int needed_buf_size, used_buf_size, used_data_size, path_buf_len;
+  int start, len, i;
+  int add_slash;
+  DWORD bytes;
+  WCHAR* path_buf;
+
+  target_len = wcslen(path);
+  is_long_path = wcsncmp(path, LONG_PATH_PREFIX, LONG_PATH_PREFIX_LEN) == 0;
+
+  if (is_long_path) {
+    is_absolute = 1;
+  } else {
+    is_absolute = target_len >= 3 && IS_LETTER(path[0]) &&
+      path[1] == L':' && IS_SLASH(path[2]);
+  }
+
+  if (!is_absolute) {
+    /* Not supporting relative paths */
+    SET_REQ_UV_ERROR(req, UV_EINVAL, ERROR_NOT_SUPPORTED);
+    return;
+  }
+
+  /* Do a pessimistic calculation of the required buffer size */
+  needed_buf_size =
+      FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer) +
+      JUNCTION_PREFIX_LEN * sizeof(WCHAR) +
+      2 * (target_len + 2) * sizeof(WCHAR);
+
+  /* Allocate the buffer */
+  buffer = (REPARSE_DATA_BUFFER*)uv__malloc(needed_buf_size);
+  if (!buffer) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  /* Grab a pointer to the part of the buffer where filenames go */
+  path_buf = (WCHAR*)&(buffer->MountPointReparseBuffer.PathBuffer);
+  path_buf_len = 0;
+
+  /* Copy the substitute (internal) target path */
+  start = path_buf_len;
+
+  wcsncpy((WCHAR*)&path_buf[path_buf_len], JUNCTION_PREFIX,
+    JUNCTION_PREFIX_LEN);
+  path_buf_len += JUNCTION_PREFIX_LEN;
+
+  add_slash = 0;
+  for (i = is_long_path ? LONG_PATH_PREFIX_LEN : 0; path[i] != L'\0'; i++) {
+    if (IS_SLASH(path[i])) {
+      add_slash = 1;
+      continue;
+    }
+
+    if (add_slash) {
+      path_buf[path_buf_len++] = L'\\';
+      add_slash = 0;
+    }
+
+    path_buf[path_buf_len++] = path[i];
+  }
+  path_buf[path_buf_len++] = L'\\';
+  len = path_buf_len - start;
+
+  /* Set the info about the substitute name */
+  buffer->MountPointReparseBuffer.SubstituteNameOffset = start * sizeof(WCHAR);
+  buffer->MountPointReparseBuffer.SubstituteNameLength = len * sizeof(WCHAR);
+
+  /* Insert null terminator */
+  path_buf[path_buf_len++] = L'\0';
+
+  /* Copy the print name of the target path */
+  start = path_buf_len;
+  add_slash = 0;
+  for (i = is_long_path ? LONG_PATH_PREFIX_LEN : 0; path[i] != L'\0'; i++) {
+    if (IS_SLASH(path[i])) {
+      add_slash = 1;
+      continue;
+    }
+
+    if (add_slash) {
+      path_buf[path_buf_len++] = L'\\';
+      add_slash = 0;
+    }
+
+    path_buf[path_buf_len++] = path[i];
+  }
+  len = path_buf_len - start;
+  if (len == 2) {
+    path_buf[path_buf_len++] = L'\\';
+    len++;
+  }
+
+  /* Set the info about the print name */
+  buffer->MountPointReparseBuffer.PrintNameOffset = start * sizeof(WCHAR);
+  buffer->MountPointReparseBuffer.PrintNameLength = len * sizeof(WCHAR);
+
+  /* Insert another null terminator */
+  path_buf[path_buf_len++] = L'\0';
+
+  /* Calculate how much buffer space was actually used */
+  used_buf_size = FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer) +
+    path_buf_len * sizeof(WCHAR);
+  used_data_size = used_buf_size -
+    FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer);
+
+  /* Put general info in the data buffer */
+  buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
+  buffer->ReparseDataLength = used_data_size;
+  buffer->Reserved = 0;
+
+  /* Create a new directory */
+  if (!CreateDirectoryW(new_path, NULL)) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    goto error;
+  }
+  created = 1;
+
+  /* Open the directory */
+  handle = CreateFileW(new_path,
+                       GENERIC_WRITE,
+                       0,
+                       NULL,
+                       OPEN_EXISTING,
+                       FILE_FLAG_BACKUP_SEMANTICS |
+                         FILE_FLAG_OPEN_REPARSE_POINT,
+                       NULL);
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    goto error;
+  }
+
+  /* Create the actual reparse point */
+  if (!DeviceIoControl(handle,
+                       FSCTL_SET_REPARSE_POINT,
+                       buffer,
+                       used_buf_size,
+                       NULL,
+                       0,
+                       &bytes,
+                       NULL)) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    goto error;
+  }
+
+  /* Clean up */
+  CloseHandle(handle);
+  uv__free(buffer);
+
+  SET_REQ_RESULT(req, 0);
+  return;
+
+error:
+  uv__free(buffer);
+
+  if (handle != INVALID_HANDLE_VALUE) {
+    CloseHandle(handle);
+  }
+
+  if (created) {
+    RemoveDirectoryW(new_path);
+  }
+}
+
+
+static void fs__symlink(uv_fs_t* req) {
+  WCHAR* pathw = req->file.pathw;
+  WCHAR* new_pathw = req->fs.info.new_pathw;
+  int flags = req->fs.info.file_flags;
+  int result;
+
+
+  if (flags & UV_FS_SYMLINK_JUNCTION) {
+    fs__create_junction(req, pathw, new_pathw);
+  } else if (pCreateSymbolicLinkW) {
+    result = pCreateSymbolicLinkW(new_pathw,
+                                  pathw,
+                                  flags & UV_FS_SYMLINK_DIR ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0) ? 0 : -1;
+    if (result == -1) {
+      SET_REQ_WIN32_ERROR(req, GetLastError());
+    } else {
+      SET_REQ_RESULT(req, result);
+    }
+  } else {
+    SET_REQ_UV_ERROR(req, UV_ENOSYS, ERROR_NOT_SUPPORTED);
+  }
+}
+
+
+static void fs__readlink(uv_fs_t* req) {
+  HANDLE handle;
+
+  handle = CreateFileW(req->file.pathw,
+                       0,
+                       0,
+                       NULL,
+                       OPEN_EXISTING,
+                       FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
+                       NULL);
+
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  if (fs__readlink_handle(handle, (char**) &req->ptr, NULL) != 0) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    CloseHandle(handle);
+    return;
+  }
+
+  req->flags |= UV_FS_FREE_PTR;
+  SET_REQ_RESULT(req, 0);
+
+  CloseHandle(handle);
+}
+
+
+static size_t fs__realpath_handle(HANDLE handle, char** realpath_ptr) {
+  int r;
+  DWORD w_realpath_len;
+  WCHAR* w_realpath_ptr = NULL;
+  WCHAR* w_realpath_buf;
+
+  w_realpath_len = pGetFinalPathNameByHandleW(handle, NULL, 0, VOLUME_NAME_DOS);
+  if (w_realpath_len == 0) {
+    return -1;
+  }
+
+  w_realpath_buf = uv__malloc((w_realpath_len + 1) * sizeof(WCHAR));
+  if (w_realpath_buf == NULL) {
+    SetLastError(ERROR_OUTOFMEMORY);
+    return -1;
+  }
+  w_realpath_ptr = w_realpath_buf;
+
+  if (pGetFinalPathNameByHandleW(handle,
+                                w_realpath_ptr,
+                                w_realpath_len,
+                                VOLUME_NAME_DOS) == 0) {
+    uv__free(w_realpath_buf);
+    SetLastError(ERROR_INVALID_HANDLE);
+    return -1;
+  }
+
+  /* convert UNC path to long path */
+  if (wcsncmp(w_realpath_ptr,
+              UNC_PATH_PREFIX,
+              UNC_PATH_PREFIX_LEN) == 0) {
+    w_realpath_ptr += 6;
+    *w_realpath_ptr = L'\\';
+    w_realpath_len -= 6;
+  } else if (wcsncmp(w_realpath_ptr,
+                      LONG_PATH_PREFIX,
+                      LONG_PATH_PREFIX_LEN) == 0) {
+    w_realpath_ptr += 4;
+    w_realpath_len -= 4;
+  } else {
+    uv__free(w_realpath_buf);
+    SetLastError(ERROR_INVALID_HANDLE);
+    return -1;
+  }
+
+  r = fs__wide_to_utf8(w_realpath_ptr, w_realpath_len, realpath_ptr, NULL);
+  uv__free(w_realpath_buf);
+  return r;
+}
+
+static void fs__realpath(uv_fs_t* req) {
+  HANDLE handle;
+
+  if (!pGetFinalPathNameByHandleW) {
+    SET_REQ_UV_ERROR(req, UV_ENOSYS, ERROR_NOT_SUPPORTED);
+    return;
+  }
+
+  handle = CreateFileW(req->file.pathw,
+                       0,
+                       0,
+                       NULL,
+                       OPEN_EXISTING,
+                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
+                       NULL);
+  if (handle == INVALID_HANDLE_VALUE) {
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  if (fs__realpath_handle(handle, (char**) &req->ptr) == -1) {
+    CloseHandle(handle);
+    SET_REQ_WIN32_ERROR(req, GetLastError());
+    return;
+  }
+
+  CloseHandle(handle);
+  req->flags |= UV_FS_FREE_PTR;
+  SET_REQ_RESULT(req, 0);
+}
+
+
+static void fs__chown(uv_fs_t* req) {
+  req->result = 0;
+}
+
+
+static void fs__fchown(uv_fs_t* req) {
+  req->result = 0;
+}
+
+
+static void uv__fs_work(struct uv__work* w) {
+  uv_fs_t* req;
+
+  req = container_of(w, uv_fs_t, work_req);
+  assert(req->type == UV_FS);
+
+#define XX(uc, lc)  case UV_FS_##uc: fs__##lc(req); break;
+  switch (req->fs_type) {
+    XX(OPEN, open)
+    XX(CLOSE, close)
+    XX(READ, read)
+    XX(WRITE, write)
+    XX(SENDFILE, sendfile)
+    XX(STAT, stat)
+    XX(LSTAT, lstat)
+    XX(FSTAT, fstat)
+    XX(FTRUNCATE, ftruncate)
+    XX(UTIME, utime)
+    XX(FUTIME, futime)
+    XX(ACCESS, access)
+    XX(CHMOD, chmod)
+    XX(FCHMOD, fchmod)
+    XX(FSYNC, fsync)
+    XX(FDATASYNC, fdatasync)
+    XX(UNLINK, unlink)
+    XX(RMDIR, rmdir)
+    XX(MKDIR, mkdir)
+    XX(MKDTEMP, mkdtemp)
+    XX(RENAME, rename)
+    XX(SCANDIR, scandir)
+    XX(LINK, link)
+    XX(SYMLINK, symlink)
+    XX(READLINK, readlink)
+    XX(REALPATH, realpath)
+    XX(CHOWN, chown)
+    XX(FCHOWN, fchown);
+    default:
+      assert(!"bad uv_fs_type");
+  }
+}
+
+
+static void uv__fs_done(struct uv__work* w, int status) {
+  uv_fs_t* req;
+
+  req = container_of(w, uv_fs_t, work_req);
+  uv__req_unregister(req->loop, req);
+
+  if (status == UV_ECANCELED) {
+    assert(req->result == 0);
+    req->result = UV_ECANCELED;
+  }
+
+  req->cb(req);
+}
+
+
+void uv_fs_req_cleanup(uv_fs_t* req) {
+  if (req->flags & UV_FS_CLEANEDUP)
+    return;
+
+  if (req->flags & UV_FS_FREE_PATHS)
+    uv__free(req->file.pathw);
+
+  if (req->flags & UV_FS_FREE_PTR) {
+    if (req->fs_type == UV_FS_SCANDIR && req->ptr != NULL)
+      uv__fs_scandir_cleanup(req);
+    else
+      uv__free(req->ptr);
+  }
+
+  if (req->fs.info.bufs != req->fs.info.bufsml)
+    uv__free(req->fs.info.bufs);
+
+  req->path = NULL;
+  req->file.pathw = NULL;
+  req->fs.info.new_pathw = NULL;
+  req->fs.info.bufs = NULL;
+  req->ptr = NULL;
+
+  req->flags |= UV_FS_CLEANEDUP;
+}
+
+
+int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags,
+    int mode, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_OPEN, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.info.file_flags = flags;
+  req->fs.info.mode = mode;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__open(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_CLOSE, cb);
+  req->file.fd = fd;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__close(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_read(uv_loop_t* loop,
+               uv_fs_t* req,
+               uv_file fd,
+               const uv_buf_t bufs[],
+               unsigned int nbufs,
+               int64_t offset,
+               uv_fs_cb cb) {
+  if (bufs == NULL || nbufs == 0)
+    return UV_EINVAL;
+
+  uv_fs_req_init(loop, req, UV_FS_READ, cb);
+
+  req->file.fd = fd;
+
+  req->fs.info.nbufs = nbufs;
+  req->fs.info.bufs = req->fs.info.bufsml;
+  if (nbufs > ARRAY_SIZE(req->fs.info.bufsml))
+    req->fs.info.bufs = uv__malloc(nbufs * sizeof(*bufs));
+
+  if (req->fs.info.bufs == NULL)
+    return UV_ENOMEM;
+
+  memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs));
+
+  req->fs.info.offset = offset;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__read(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_write(uv_loop_t* loop,
+                uv_fs_t* req,
+                uv_file fd,
+                const uv_buf_t bufs[],
+                unsigned int nbufs,
+                int64_t offset,
+                uv_fs_cb cb) {
+  if (bufs == NULL || nbufs == 0)
+    return UV_EINVAL;
+
+  uv_fs_req_init(loop, req, UV_FS_WRITE, cb);
+
+  req->file.fd = fd;
+
+  req->fs.info.nbufs = nbufs;
+  req->fs.info.bufs = req->fs.info.bufsml;
+  if (nbufs > ARRAY_SIZE(req->fs.info.bufsml))
+    req->fs.info.bufs = uv__malloc(nbufs * sizeof(*bufs));
+
+  if (req->fs.info.bufs == NULL)
+    return UV_ENOMEM;
+
+  memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs));
+
+  req->fs.info.offset = offset;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__write(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_UNLINK, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__unlink(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_MKDIR, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.info.mode = mode;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__mkdir(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_MKDTEMP, cb);
+
+  err = fs__capture_path(req, tpl, NULL, TRUE);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__mkdtemp(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_RMDIR, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__rmdir(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_SCANDIR, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.info.file_flags = flags;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__scandir(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    const char* new_path, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_LINK, cb);
+
+  err = fs__capture_path(req, path, new_path, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__link(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    const char* new_path, int flags, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_SYMLINK, cb);
+
+  err = fs__capture_path(req, path, new_path, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.info.file_flags = flags;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__symlink(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_READLINK, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__readlink(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_realpath(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    uv_fs_cb cb) {
+  int err;
+
+  if (!req || !path) {
+    return UV_EINVAL;
+  }
+
+  uv_fs_req_init(loop, req, UV_FS_REALPATH, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__realpath(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid,
+    uv_gid_t gid, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_CHOWN, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__chown(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_uid_t uid,
+    uv_gid_t gid, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FCHOWN, cb);
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__fchown(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_STAT, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__stat(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_LSTAT, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__lstat(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FSTAT, cb);
+  req->file.fd = fd;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__fstat(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path,
+    const char* new_path, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_RENAME, cb);
+
+  err = fs__capture_path(req, path, new_path, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__rename(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FSYNC, cb);
+  req->file.fd = fd;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__fsync(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FDATASYNC, cb);
+  req->file.fd = fd;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__fdatasync(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file fd,
+    int64_t offset, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FTRUNCATE, cb);
+
+  req->file.fd = fd;
+  req->fs.info.offset = offset;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__ftruncate(req);
+    return req->result;
+  }
+}
+
+
+
+int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file fd_out,
+    uv_file fd_in, int64_t in_offset, size_t length, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_SENDFILE, cb);
+
+  req->file.fd = fd_in;
+  req->fs.info.fd_out = fd_out;
+  req->fs.info.offset = in_offset;
+  req->fs.info.bufsml[0].len = length;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__sendfile(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_access(uv_loop_t* loop,
+                 uv_fs_t* req,
+                 const char* path,
+                 int flags,
+                 uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_ACCESS, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  req->flags = flags;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  }
+
+  fs__access(req);
+  return req->result;
+}
+
+
+int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode,
+    uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_CHMOD, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.info.mode = mode;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__chmod(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file fd, int mode,
+    uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FCHMOD, cb);
+
+  req->file.fd = fd;
+  req->fs.info.mode = mode;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__fchmod(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime,
+    double mtime, uv_fs_cb cb) {
+  int err;
+
+  uv_fs_req_init(loop, req, UV_FS_UTIME, cb);
+
+  err = fs__capture_path(req, path, NULL, cb != NULL);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  req->fs.time.atime = atime;
+  req->fs.time.mtime = mtime;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__utime(req);
+    return req->result;
+  }
+}
+
+
+int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file fd, double atime,
+    double mtime, uv_fs_cb cb) {
+  uv_fs_req_init(loop, req, UV_FS_FUTIME, cb);
+
+  req->file.fd = fd;
+  req->fs.time.atime = atime;
+  req->fs.time.mtime = mtime;
+
+  if (cb) {
+    QUEUE_FS_TP_JOB(loop, req);
+    return 0;
+  } else {
+    fs__futime(req);
+    return req->result;
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/getaddrinfo.c b/Utilities/cmlibuv/src/win/getaddrinfo.c
new file mode 100644
index 0000000..744f8e0
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/getaddrinfo.c
@@ -0,0 +1,385 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "req-inl.h"
+
+/* EAI_* constants. */
+#include <winsock2.h>
+
+
+int uv__getaddrinfo_translate_error(int sys_err) {
+  switch (sys_err) {
+    case 0:                       return 0;
+    case WSATRY_AGAIN:            return UV_EAI_AGAIN;
+    case WSAEINVAL:               return UV_EAI_BADFLAGS;
+    case WSANO_RECOVERY:          return UV_EAI_FAIL;
+    case WSAEAFNOSUPPORT:         return UV_EAI_FAMILY;
+    case WSA_NOT_ENOUGH_MEMORY:   return UV_EAI_MEMORY;
+    case WSAHOST_NOT_FOUND:       return UV_EAI_NONAME;
+    case WSATYPE_NOT_FOUND:       return UV_EAI_SERVICE;
+    case WSAESOCKTNOSUPPORT:      return UV_EAI_SOCKTYPE;
+    default:                      return uv_translate_sys_error(sys_err);
+  }
+}
+
+
+/*
+ * MinGW is missing this
+ */
+#if !defined(_MSC_VER) && !defined(__MINGW64_VERSION_MAJOR)
+  typedef struct addrinfoW {
+    int ai_flags;
+    int ai_family;
+    int ai_socktype;
+    int ai_protocol;
+    size_t ai_addrlen;
+    WCHAR* ai_canonname;
+    struct sockaddr* ai_addr;
+    struct addrinfoW* ai_next;
+  } ADDRINFOW, *PADDRINFOW;
+
+  DECLSPEC_IMPORT int WSAAPI GetAddrInfoW(const WCHAR* node,
+                                          const WCHAR* service,
+                                          const ADDRINFOW* hints,
+                                          PADDRINFOW* result);
+
+  DECLSPEC_IMPORT void WSAAPI FreeAddrInfoW(PADDRINFOW pAddrInfo);
+#endif
+
+
+/* adjust size value to be multiple of 4. Use to keep pointer aligned */
+/* Do we need different versions of this for different architectures? */
+#define ALIGNED_SIZE(X)     ((((X) + 3) >> 2) << 2)
+
+
+static void uv__getaddrinfo_work(struct uv__work* w) {
+  uv_getaddrinfo_t* req;
+  struct addrinfoW* hints;
+  int err;
+
+  req = container_of(w, uv_getaddrinfo_t, work_req);
+  hints = req->addrinfow;
+  req->addrinfow = NULL;
+  err = GetAddrInfoW(req->node, req->service, hints, &req->addrinfow);
+  req->retcode = uv__getaddrinfo_translate_error(err);
+}
+
+
+/*
+ * Called from uv_run when complete. Call user specified callback
+ * then free returned addrinfo
+ * Returned addrinfo strings are converted from UTF-16 to UTF-8.
+ *
+ * To minimize allocation we calculate total size required,
+ * and copy all structs and referenced strings into the one block.
+ * Each size calculation is adjusted to avoid unaligned pointers.
+ */
+static void uv__getaddrinfo_done(struct uv__work* w, int status) {
+  uv_getaddrinfo_t* req;
+  int addrinfo_len = 0;
+  int name_len = 0;
+  size_t addrinfo_struct_len = ALIGNED_SIZE(sizeof(struct addrinfo));
+  struct addrinfoW* addrinfow_ptr;
+  struct addrinfo* addrinfo_ptr;
+  char* alloc_ptr = NULL;
+  char* cur_ptr = NULL;
+
+  req = container_of(w, uv_getaddrinfo_t, work_req);
+
+  /* release input parameter memory */
+  uv__free(req->alloc);
+  req->alloc = NULL;
+
+  if (status == UV_ECANCELED) {
+    assert(req->retcode == 0);
+    req->retcode = UV_EAI_CANCELED;
+    goto complete;
+  }
+
+  if (req->retcode == 0) {
+    /* convert addrinfoW to addrinfo */
+    /* first calculate required length */
+    addrinfow_ptr = req->addrinfow;
+    while (addrinfow_ptr != NULL) {
+      addrinfo_len += addrinfo_struct_len +
+          ALIGNED_SIZE(addrinfow_ptr->ai_addrlen);
+      if (addrinfow_ptr->ai_canonname != NULL) {
+        name_len = WideCharToMultiByte(CP_UTF8,
+                                       0,
+                                       addrinfow_ptr->ai_canonname,
+                                       -1,
+                                       NULL,
+                                       0,
+                                       NULL,
+                                       NULL);
+        if (name_len == 0) {
+          req->retcode = uv_translate_sys_error(GetLastError());
+          goto complete;
+        }
+        addrinfo_len += ALIGNED_SIZE(name_len);
+      }
+      addrinfow_ptr = addrinfow_ptr->ai_next;
+    }
+
+    /* allocate memory for addrinfo results */
+    alloc_ptr = (char*)uv__malloc(addrinfo_len);
+
+    /* do conversions */
+    if (alloc_ptr != NULL) {
+      cur_ptr = alloc_ptr;
+      addrinfow_ptr = req->addrinfow;
+
+      while (addrinfow_ptr != NULL) {
+        /* copy addrinfo struct data */
+        assert(cur_ptr + addrinfo_struct_len <= alloc_ptr + addrinfo_len);
+        addrinfo_ptr = (struct addrinfo*)cur_ptr;
+        addrinfo_ptr->ai_family = addrinfow_ptr->ai_family;
+        addrinfo_ptr->ai_socktype = addrinfow_ptr->ai_socktype;
+        addrinfo_ptr->ai_protocol = addrinfow_ptr->ai_protocol;
+        addrinfo_ptr->ai_flags = addrinfow_ptr->ai_flags;
+        addrinfo_ptr->ai_addrlen = addrinfow_ptr->ai_addrlen;
+        addrinfo_ptr->ai_canonname = NULL;
+        addrinfo_ptr->ai_addr = NULL;
+        addrinfo_ptr->ai_next = NULL;
+
+        cur_ptr += addrinfo_struct_len;
+
+        /* copy sockaddr */
+        if (addrinfo_ptr->ai_addrlen > 0) {
+          assert(cur_ptr + addrinfo_ptr->ai_addrlen <=
+                 alloc_ptr + addrinfo_len);
+          memcpy(cur_ptr, addrinfow_ptr->ai_addr, addrinfo_ptr->ai_addrlen);
+          addrinfo_ptr->ai_addr = (struct sockaddr*)cur_ptr;
+          cur_ptr += ALIGNED_SIZE(addrinfo_ptr->ai_addrlen);
+        }
+
+        /* convert canonical name to UTF-8 */
+        if (addrinfow_ptr->ai_canonname != NULL) {
+          name_len = WideCharToMultiByte(CP_UTF8,
+                                         0,
+                                         addrinfow_ptr->ai_canonname,
+                                         -1,
+                                         NULL,
+                                         0,
+                                         NULL,
+                                         NULL);
+          assert(name_len > 0);
+          assert(cur_ptr + name_len <= alloc_ptr + addrinfo_len);
+          name_len = WideCharToMultiByte(CP_UTF8,
+                                         0,
+                                         addrinfow_ptr->ai_canonname,
+                                         -1,
+                                         cur_ptr,
+                                         name_len,
+                                         NULL,
+                                         NULL);
+          assert(name_len > 0);
+          addrinfo_ptr->ai_canonname = cur_ptr;
+          cur_ptr += ALIGNED_SIZE(name_len);
+        }
+        assert(cur_ptr <= alloc_ptr + addrinfo_len);
+
+        /* set next ptr */
+        addrinfow_ptr = addrinfow_ptr->ai_next;
+        if (addrinfow_ptr != NULL) {
+          addrinfo_ptr->ai_next = (struct addrinfo*)cur_ptr;
+        }
+      }
+      req->addrinfo = (struct addrinfo*)alloc_ptr;
+    } else {
+      req->retcode = UV_EAI_MEMORY;
+    }
+  }
+
+  /* return memory to system */
+  if (req->addrinfow != NULL) {
+    FreeAddrInfoW(req->addrinfow);
+    req->addrinfow = NULL;
+  }
+
+complete:
+  uv__req_unregister(req->loop, req);
+
+  /* finally do callback with converted result */
+  if (req->getaddrinfo_cb)
+    req->getaddrinfo_cb(req, req->retcode, req->addrinfo);
+}
+
+
+void uv_freeaddrinfo(struct addrinfo* ai) {
+  char* alloc_ptr = (char*)ai;
+
+  /* release copied result memory */
+  uv__free(alloc_ptr);
+}
+
+
+/*
+ * Entry point for getaddrinfo
+ * we convert the UTF-8 strings to UNICODE
+ * and save the UNICODE string pointers in the req
+ * We also copy hints so that caller does not need to keep memory until the
+ * callback.
+ * return 0 if a callback will be made
+ * return error code if validation fails
+ *
+ * To minimize allocation we calculate total size required,
+ * and copy all structs and referenced strings into the one block.
+ * Each size calculation is adjusted to avoid unaligned pointers.
+ */
+int uv_getaddrinfo(uv_loop_t* loop,
+                   uv_getaddrinfo_t* req,
+                   uv_getaddrinfo_cb getaddrinfo_cb,
+                   const char* node,
+                   const char* service,
+                   const struct addrinfo* hints) {
+  int nodesize = 0;
+  int servicesize = 0;
+  int hintssize = 0;
+  char* alloc_ptr = NULL;
+  int err;
+
+  if (req == NULL || (node == NULL && service == NULL)) {
+    err = WSAEINVAL;
+    goto error;
+  }
+
+  uv_req_init(loop, (uv_req_t*)req);
+
+  req->getaddrinfo_cb = getaddrinfo_cb;
+  req->addrinfo = NULL;
+  req->type = UV_GETADDRINFO;
+  req->loop = loop;
+  req->retcode = 0;
+
+  /* calculate required memory size for all input values */
+  if (node != NULL) {
+    nodesize = ALIGNED_SIZE(MultiByteToWideChar(CP_UTF8, 0, node, -1, NULL, 0) *
+                            sizeof(WCHAR));
+    if (nodesize == 0) {
+      err = GetLastError();
+      goto error;
+    }
+  }
+
+  if (service != NULL) {
+    servicesize = ALIGNED_SIZE(MultiByteToWideChar(CP_UTF8,
+                                                   0,
+                                                   service,
+                                                   -1,
+                                                   NULL,
+                                                   0) *
+                               sizeof(WCHAR));
+    if (servicesize == 0) {
+      err = GetLastError();
+      goto error;
+    }
+  }
+  if (hints != NULL) {
+    hintssize = ALIGNED_SIZE(sizeof(struct addrinfoW));
+  }
+
+  /* allocate memory for inputs, and partition it as needed */
+  alloc_ptr = (char*)uv__malloc(nodesize + servicesize + hintssize);
+  if (!alloc_ptr) {
+    err = WSAENOBUFS;
+    goto error;
+  }
+
+  /* save alloc_ptr now so we can free if error */
+  req->alloc = (void*)alloc_ptr;
+
+  /* convert node string to UTF16 into allocated memory and save pointer in */
+  /* the request. */
+  if (node != NULL) {
+    req->node = (WCHAR*)alloc_ptr;
+    if (MultiByteToWideChar(CP_UTF8,
+                            0,
+                            node,
+                            -1,
+                            (WCHAR*) alloc_ptr,
+                            nodesize / sizeof(WCHAR)) == 0) {
+      err = GetLastError();
+      goto error;
+    }
+    alloc_ptr += nodesize;
+  } else {
+    req->node = NULL;
+  }
+
+  /* convert service string to UTF16 into allocated memory and save pointer */
+  /* in the req. */
+  if (service != NULL) {
+    req->service = (WCHAR*)alloc_ptr;
+    if (MultiByteToWideChar(CP_UTF8,
+                            0,
+                            service,
+                            -1,
+                            (WCHAR*) alloc_ptr,
+                            servicesize / sizeof(WCHAR)) == 0) {
+      err = GetLastError();
+      goto error;
+    }
+    alloc_ptr += servicesize;
+  } else {
+    req->service = NULL;
+  }
+
+  /* copy hints to allocated memory and save pointer in req */
+  if (hints != NULL) {
+    req->addrinfow = (struct addrinfoW*)alloc_ptr;
+    req->addrinfow->ai_family = hints->ai_family;
+    req->addrinfow->ai_socktype = hints->ai_socktype;
+    req->addrinfow->ai_protocol = hints->ai_protocol;
+    req->addrinfow->ai_flags = hints->ai_flags;
+    req->addrinfow->ai_addrlen = 0;
+    req->addrinfow->ai_canonname = NULL;
+    req->addrinfow->ai_addr = NULL;
+    req->addrinfow->ai_next = NULL;
+  } else {
+    req->addrinfow = NULL;
+  }
+
+  uv__req_register(loop, req);
+
+  if (getaddrinfo_cb) {
+    uv__work_submit(loop,
+                    &req->work_req,
+                    uv__getaddrinfo_work,
+                    uv__getaddrinfo_done);
+    return 0;
+  } else {
+    uv__getaddrinfo_work(&req->work_req);
+    uv__getaddrinfo_done(&req->work_req, 0);
+    return req->retcode;
+  }
+
+error:
+  if (req != NULL) {
+    uv__free(req->alloc);
+    req->alloc = NULL;
+  }
+  return uv_translate_sys_error(err);
+}
diff --git a/Utilities/cmlibuv/src/win/getnameinfo.c b/Utilities/cmlibuv/src/win/getnameinfo.c
new file mode 100644
index 0000000..66b64b8
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/getnameinfo.c
@@ -0,0 +1,150 @@
+/* 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 <assert.h>
+#include <stdio.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "req-inl.h"
+
+#ifndef GetNameInfo
+int WSAAPI GetNameInfoW(
+  const SOCKADDR *pSockaddr,
+  socklen_t SockaddrLength,
+  PWCHAR pNodeBuffer,
+  DWORD NodeBufferSize,
+  PWCHAR pServiceBuffer,
+  DWORD ServiceBufferSize,
+  INT Flags
+);
+#endif
+
+static void uv__getnameinfo_work(struct uv__work* w) {
+  uv_getnameinfo_t* req;
+  WCHAR host[NI_MAXHOST];
+  WCHAR service[NI_MAXSERV];
+  int ret = 0;
+
+  req = container_of(w, uv_getnameinfo_t, work_req);
+  if (GetNameInfoW((struct sockaddr*)&req->storage,
+                   sizeof(req->storage),
+                   host,
+                   ARRAY_SIZE(host),
+                   service,
+                   ARRAY_SIZE(service),
+                   req->flags)) {
+    ret = WSAGetLastError();
+  }
+  req->retcode = uv__getaddrinfo_translate_error(ret);
+
+  /* convert results to UTF-8 */
+  WideCharToMultiByte(CP_UTF8,
+                      0,
+                      host,
+                      -1,
+                      req->host,
+                      sizeof(req->host),
+                      NULL,
+                      NULL);
+
+  WideCharToMultiByte(CP_UTF8,
+                      0,
+                      service,
+                      -1,
+                      req->service,
+                      sizeof(req->service),
+                      NULL,
+                      NULL);
+}
+
+
+/*
+* Called from uv_run when complete.
+*/
+static void uv__getnameinfo_done(struct uv__work* w, int status) {
+  uv_getnameinfo_t* req;
+  char* host;
+  char* service;
+
+  req = container_of(w, uv_getnameinfo_t, work_req);
+  uv__req_unregister(req->loop, req);
+  host = service = NULL;
+
+  if (status == UV_ECANCELED) {
+    assert(req->retcode == 0);
+    req->retcode = UV_EAI_CANCELED;
+  } else if (req->retcode == 0) {
+    host = req->host;
+    service = req->service;
+  }
+
+  if (req->getnameinfo_cb)
+    req->getnameinfo_cb(req, req->retcode, host, service);
+}
+
+
+/*
+* Entry point for getnameinfo
+* return 0 if a callback will be made
+* return error code if validation fails
+*/
+int uv_getnameinfo(uv_loop_t* loop,
+                   uv_getnameinfo_t* req,
+                   uv_getnameinfo_cb getnameinfo_cb,
+                   const struct sockaddr* addr,
+                   int flags) {
+  if (req == NULL || addr == NULL)
+    return UV_EINVAL;
+
+  if (addr->sa_family == AF_INET) {
+    memcpy(&req->storage,
+           addr,
+           sizeof(struct sockaddr_in));
+  } else if (addr->sa_family == AF_INET6) {
+    memcpy(&req->storage,
+           addr,
+           sizeof(struct sockaddr_in6));
+  } else {
+    return UV_EINVAL;
+  }
+
+  uv_req_init(loop, (uv_req_t*)req);
+  uv__req_register(loop, req);
+
+  req->getnameinfo_cb = getnameinfo_cb;
+  req->flags = flags;
+  req->type = UV_GETNAMEINFO;
+  req->loop = loop;
+  req->retcode = 0;
+
+  if (getnameinfo_cb) {
+    uv__work_submit(loop,
+                    &req->work_req,
+                    uv__getnameinfo_work,
+                    uv__getnameinfo_done);
+    return 0;
+  } else {
+    uv__getnameinfo_work(&req->work_req);
+    uv__getnameinfo_done(&req->work_req, 0);
+    return req->retcode;
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/handle-inl.h b/Utilities/cmlibuv/src/win/handle-inl.h
new file mode 100644
index 0000000..8d0334c
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/handle-inl.h
@@ -0,0 +1,179 @@
+/* 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_WIN_HANDLE_INL_H_
+#define UV_WIN_HANDLE_INL_H_
+
+#include <assert.h>
+#include <io.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+#define DECREASE_ACTIVE_COUNT(loop, handle)                             \
+  do {                                                                  \
+    if (--(handle)->activecnt == 0 &&                                   \
+        !((handle)->flags & UV__HANDLE_CLOSING)) {                      \
+      uv__handle_stop((handle));                                        \
+    }                                                                   \
+    assert((handle)->activecnt >= 0);                                   \
+  } while (0)
+
+
+#define INCREASE_ACTIVE_COUNT(loop, handle)                             \
+  do {                                                                  \
+    if ((handle)->activecnt++ == 0) {                                   \
+      uv__handle_start((handle));                                       \
+    }                                                                   \
+    assert((handle)->activecnt > 0);                                    \
+  } while (0)
+
+
+#define DECREASE_PENDING_REQ_COUNT(handle)                              \
+  do {                                                                  \
+    assert(handle->reqs_pending > 0);                                   \
+    handle->reqs_pending--;                                             \
+                                                                        \
+    if (handle->flags & UV__HANDLE_CLOSING &&                           \
+        handle->reqs_pending == 0) {                                    \
+      uv_want_endgame(loop, (uv_handle_t*)handle);                      \
+    }                                                                   \
+  } while (0)
+
+
+#define uv__handle_closing(handle)                                      \
+  do {                                                                  \
+    assert(!((handle)->flags & UV__HANDLE_CLOSING));                    \
+                                                                        \
+    if (!(((handle)->flags & UV__HANDLE_ACTIVE) &&                      \
+          ((handle)->flags & UV__HANDLE_REF)))                          \
+      uv__active_handle_add((uv_handle_t*) (handle));                   \
+                                                                        \
+    (handle)->flags |= UV__HANDLE_CLOSING;                              \
+    (handle)->flags &= ~UV__HANDLE_ACTIVE;                              \
+  } while (0)
+
+
+#define uv__handle_close(handle)                                        \
+  do {                                                                  \
+    QUEUE_REMOVE(&(handle)->handle_queue);                              \
+    uv__active_handle_rm((uv_handle_t*) (handle));                      \
+                                                                        \
+    (handle)->flags |= UV_HANDLE_CLOSED;                                \
+                                                                        \
+    if ((handle)->close_cb)                                             \
+      (handle)->close_cb((uv_handle_t*) (handle));                      \
+  } while (0)
+
+
+INLINE static void uv_want_endgame(uv_loop_t* loop, uv_handle_t* handle) {
+  if (!(handle->flags & UV_HANDLE_ENDGAME_QUEUED)) {
+    handle->flags |= UV_HANDLE_ENDGAME_QUEUED;
+
+    handle->endgame_next = loop->endgame_handles;
+    loop->endgame_handles = handle;
+  }
+}
+
+
+INLINE static void uv_process_endgames(uv_loop_t* loop) {
+  uv_handle_t* handle;
+
+  while (loop->endgame_handles) {
+    handle = loop->endgame_handles;
+    loop->endgame_handles = handle->endgame_next;
+
+    handle->flags &= ~UV_HANDLE_ENDGAME_QUEUED;
+
+    switch (handle->type) {
+      case UV_TCP:
+        uv_tcp_endgame(loop, (uv_tcp_t*) handle);
+        break;
+
+      case UV_NAMED_PIPE:
+        uv_pipe_endgame(loop, (uv_pipe_t*) handle);
+        break;
+
+      case UV_TTY:
+        uv_tty_endgame(loop, (uv_tty_t*) handle);
+        break;
+
+      case UV_UDP:
+        uv_udp_endgame(loop, (uv_udp_t*) handle);
+        break;
+
+      case UV_POLL:
+        uv_poll_endgame(loop, (uv_poll_t*) handle);
+        break;
+
+      case UV_TIMER:
+        uv_timer_endgame(loop, (uv_timer_t*) handle);
+        break;
+
+      case UV_PREPARE:
+      case UV_CHECK:
+      case UV_IDLE:
+        uv_loop_watcher_endgame(loop, handle);
+        break;
+
+      case UV_ASYNC:
+        uv_async_endgame(loop, (uv_async_t*) handle);
+        break;
+
+      case UV_SIGNAL:
+        uv_signal_endgame(loop, (uv_signal_t*) handle);
+        break;
+
+      case UV_PROCESS:
+        uv_process_endgame(loop, (uv_process_t*) handle);
+        break;
+
+      case UV_FS_EVENT:
+        uv_fs_event_endgame(loop, (uv_fs_event_t*) handle);
+        break;
+
+      case UV_FS_POLL:
+        uv__fs_poll_endgame(loop, (uv_fs_poll_t*) handle);
+        break;
+
+      default:
+        assert(0);
+        break;
+    }
+  }
+}
+
+INLINE static HANDLE uv__get_osfhandle(int fd)
+{
+  /* _get_osfhandle() raises an assert in debug builds if the FD is invalid. */
+  /* But  it also correctly checks the FD and returns INVALID_HANDLE_VALUE */
+  /* for invalid FDs in release builds (or if you let the assert continue).  */
+  /* So this wrapper function disables asserts when calling _get_osfhandle. */
+
+  HANDLE handle;
+  UV_BEGIN_DISABLE_CRT_ASSERT();
+  handle = (HANDLE) _get_osfhandle(fd);
+  UV_END_DISABLE_CRT_ASSERT();
+  return handle;
+}
+
+#endif /* UV_WIN_HANDLE_INL_H_ */
diff --git a/Utilities/cmlibuv/src/win/handle.c b/Utilities/cmlibuv/src/win/handle.c
new file mode 100644
index 0000000..72b49d9
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/handle.c
@@ -0,0 +1,154 @@
+/* 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 <assert.h>
+#include <io.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+
+
+uv_handle_type uv_guess_handle(uv_file file) {
+  HANDLE handle;
+  DWORD mode;
+
+  if (file < 0) {
+    return UV_UNKNOWN_HANDLE;
+  }
+
+  handle = uv__get_osfhandle(file);
+
+  switch (GetFileType(handle)) {
+    case FILE_TYPE_CHAR:
+      if (GetConsoleMode(handle, &mode)) {
+        return UV_TTY;
+      } else {
+        return UV_FILE;
+      }
+
+    case FILE_TYPE_PIPE:
+      return UV_NAMED_PIPE;
+
+    case FILE_TYPE_DISK:
+      return UV_FILE;
+
+    default:
+      return UV_UNKNOWN_HANDLE;
+  }
+}
+
+
+int uv_is_active(const uv_handle_t* handle) {
+  return (handle->flags & UV__HANDLE_ACTIVE) &&
+        !(handle->flags & UV__HANDLE_CLOSING);
+}
+
+
+void uv_close(uv_handle_t* handle, uv_close_cb cb) {
+  uv_loop_t* loop = handle->loop;
+
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    assert(0);
+    return;
+  }
+
+  handle->close_cb = cb;
+
+  /* Handle-specific close actions */
+  switch (handle->type) {
+    case UV_TCP:
+      uv_tcp_close(loop, (uv_tcp_t*)handle);
+      return;
+
+    case UV_NAMED_PIPE:
+      uv_pipe_close(loop, (uv_pipe_t*) handle);
+      return;
+
+    case UV_TTY:
+      uv_tty_close((uv_tty_t*) handle);
+      return;
+
+    case UV_UDP:
+      uv_udp_close(loop, (uv_udp_t*) handle);
+      return;
+
+    case UV_POLL:
+      uv_poll_close(loop, (uv_poll_t*) handle);
+      return;
+
+    case UV_TIMER:
+      uv_timer_stop((uv_timer_t*)handle);
+      uv__handle_closing(handle);
+      uv_want_endgame(loop, handle);
+      return;
+
+    case UV_PREPARE:
+      uv_prepare_stop((uv_prepare_t*)handle);
+      uv__handle_closing(handle);
+      uv_want_endgame(loop, handle);
+      return;
+
+    case UV_CHECK:
+      uv_check_stop((uv_check_t*)handle);
+      uv__handle_closing(handle);
+      uv_want_endgame(loop, handle);
+      return;
+
+    case UV_IDLE:
+      uv_idle_stop((uv_idle_t*)handle);
+      uv__handle_closing(handle);
+      uv_want_endgame(loop, handle);
+      return;
+
+    case UV_ASYNC:
+      uv_async_close(loop, (uv_async_t*) handle);
+      return;
+
+    case UV_SIGNAL:
+      uv_signal_close(loop, (uv_signal_t*) handle);
+      return;
+
+    case UV_PROCESS:
+      uv_process_close(loop, (uv_process_t*) handle);
+      return;
+
+    case UV_FS_EVENT:
+      uv_fs_event_close(loop, (uv_fs_event_t*) handle);
+      return;
+
+    case UV_FS_POLL:
+      uv__fs_poll_close((uv_fs_poll_t*) handle);
+      uv__handle_closing(handle);
+      uv_want_endgame(loop, handle);
+      return;
+
+    default:
+      /* Not supported */
+      abort();
+  }
+}
+
+
+int uv_is_closing(const uv_handle_t* handle) {
+  return !!(handle->flags & (UV__HANDLE_CLOSING | UV_HANDLE_CLOSED));
+}
diff --git a/Utilities/cmlibuv/src/win/internal.h b/Utilities/cmlibuv/src/win/internal.h
new file mode 100644
index 0000000..8a17e94
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/internal.h
@@ -0,0 +1,398 @@
+/* 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_WIN_INTERNAL_H_
+#define UV_WIN_INTERNAL_H_
+
+#if defined(_MSC_VER)
+# pragma warning(push,1)
+#endif
+
+#include "uv.h"
+#include "../uv-common.h"
+
+#include "tree.h"
+#include "winapi.h"
+#include "winsock.h"
+
+#ifdef _MSC_VER
+# define INLINE __inline
+# define UV_THREAD_LOCAL __declspec( thread )
+#else
+# define INLINE inline
+# define UV_THREAD_LOCAL __thread
+#endif
+
+
+#ifdef _DEBUG
+
+extern UV_THREAD_LOCAL int uv__crt_assert_enabled;
+
+#define UV_BEGIN_DISABLE_CRT_ASSERT()                           \
+  {                                                             \
+    int uv__saved_crt_assert_enabled = uv__crt_assert_enabled;  \
+    uv__crt_assert_enabled = FALSE;
+
+
+#define UV_END_DISABLE_CRT_ASSERT()                             \
+    uv__crt_assert_enabled = uv__saved_crt_assert_enabled;      \
+  }
+
+#else
+#define UV_BEGIN_DISABLE_CRT_ASSERT()
+#define UV_END_DISABLE_CRT_ASSERT()
+#endif
+
+/*
+ * Handles
+ * (also see handle-inl.h)
+ */
+
+/* Used by all handles. */
+#define UV_HANDLE_CLOSED                        0x00000002
+#define UV_HANDLE_ENDGAME_QUEUED                0x00000008
+
+/* uv-common.h: #define UV__HANDLE_CLOSING      0x00000001 */
+/* uv-common.h: #define UV__HANDLE_ACTIVE       0x00000040 */
+/* uv-common.h: #define UV__HANDLE_REF          0x00000020 */
+/* uv-common.h: #define UV_HANDLE_INTERNAL      0x00000080 */
+
+/* Used by streams and UDP handles. */
+#define UV_HANDLE_READING                       0x00000100
+#define UV_HANDLE_BOUND                         0x00000200
+#define UV_HANDLE_LISTENING                     0x00000800
+#define UV_HANDLE_CONNECTION                    0x00001000
+#define UV_HANDLE_READABLE                      0x00008000
+#define UV_HANDLE_WRITABLE                      0x00010000
+#define UV_HANDLE_READ_PENDING                  0x00020000
+#define UV_HANDLE_SYNC_BYPASS_IOCP              0x00040000
+#define UV_HANDLE_ZERO_READ                     0x00080000
+#define UV_HANDLE_EMULATE_IOCP                  0x00100000
+#define UV_HANDLE_BLOCKING_WRITES               0x00200000
+#define UV_HANDLE_CANCELLATION_PENDING          0x00400000
+
+/* Used by uv_tcp_t and uv_udp_t handles */
+#define UV_HANDLE_IPV6                          0x01000000
+
+/* Only used by uv_tcp_t handles. */
+#define UV_HANDLE_TCP_NODELAY                   0x02000000
+#define UV_HANDLE_TCP_KEEPALIVE                 0x04000000
+#define UV_HANDLE_TCP_SINGLE_ACCEPT             0x08000000
+#define UV_HANDLE_TCP_ACCEPT_STATE_CHANGING     0x10000000
+#define UV_HANDLE_TCP_SOCKET_CLOSED             0x20000000
+#define UV_HANDLE_SHARED_TCP_SOCKET             0x40000000
+
+/* Only used by uv_pipe_t handles. */
+#define UV_HANDLE_NON_OVERLAPPED_PIPE           0x01000000
+#define UV_HANDLE_PIPESERVER                    0x02000000
+#define UV_HANDLE_PIPE_READ_CANCELABLE          0x04000000
+
+/* Only used by uv_tty_t handles. */
+#define UV_HANDLE_TTY_READABLE                  0x01000000
+#define UV_HANDLE_TTY_RAW                       0x02000000
+#define UV_HANDLE_TTY_SAVED_POSITION            0x04000000
+#define UV_HANDLE_TTY_SAVED_ATTRIBUTES          0x08000000
+
+/* Only used by uv_poll_t handles. */
+#define UV_HANDLE_POLL_SLOW                     0x02000000
+
+
+/*
+ * Requests: see req-inl.h
+ */
+
+
+/*
+ * Streams: see stream-inl.h
+ */
+
+
+/*
+ * TCP
+ */
+
+typedef struct {
+  WSAPROTOCOL_INFOW socket_info;
+  int delayed_error;
+} uv__ipc_socket_info_ex;
+
+int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb);
+int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client);
+int uv_tcp_read_start(uv_tcp_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb);
+int uv_tcp_write(uv_loop_t* loop, uv_write_t* req, uv_tcp_t* handle,
+    const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb);
+int uv__tcp_try_write(uv_tcp_t* handle, const uv_buf_t bufs[],
+    unsigned int nbufs);
+
+void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, uv_req_t* req);
+void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_write_t* req);
+void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_req_t* req);
+void uv_process_tcp_connect_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_connect_t* req);
+
+void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp);
+void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle);
+
+int uv_tcp_import(uv_tcp_t* tcp, uv__ipc_socket_info_ex* socket_info_ex,
+    int tcp_connection);
+
+int uv_tcp_duplicate_socket(uv_tcp_t* handle, int pid,
+    LPWSAPROTOCOL_INFOW protocol_info);
+
+
+/*
+ * UDP
+ */
+void uv_process_udp_recv_req(uv_loop_t* loop, uv_udp_t* handle, uv_req_t* req);
+void uv_process_udp_send_req(uv_loop_t* loop, uv_udp_t* handle,
+    uv_udp_send_t* req);
+
+void uv_udp_close(uv_loop_t* loop, uv_udp_t* handle);
+void uv_udp_endgame(uv_loop_t* loop, uv_udp_t* handle);
+
+
+/*
+ * Pipes
+ */
+int uv_stdio_pipe_server(uv_loop_t* loop, uv_pipe_t* handle, DWORD access,
+    char* name, size_t nameSize);
+
+int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb);
+int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client);
+int uv_pipe_read_start(uv_pipe_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb);
+int uv_pipe_write(uv_loop_t* loop, uv_write_t* req, uv_pipe_t* handle,
+    const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb);
+int uv_pipe_write2(uv_loop_t* loop, uv_write_t* req, uv_pipe_t* handle,
+    const uv_buf_t bufs[], unsigned int nbufs, uv_stream_t* send_handle,
+    uv_write_cb cb);
+void uv__pipe_pause_read(uv_pipe_t* handle);
+void uv__pipe_unpause_read(uv_pipe_t* handle);
+void uv__pipe_stop_read(uv_pipe_t* handle);
+
+void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_req_t* req);
+void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_write_t* req);
+void uv_process_pipe_accept_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_req_t* raw_req);
+void uv_process_pipe_connect_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_connect_t* req);
+void uv_process_pipe_shutdown_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_shutdown_t* req);
+
+void uv_pipe_close(uv_loop_t* loop, uv_pipe_t* handle);
+void uv_pipe_cleanup(uv_loop_t* loop, uv_pipe_t* handle);
+void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle);
+
+
+/*
+ * TTY
+ */
+void uv_console_init();
+
+int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb);
+int uv_tty_read_stop(uv_tty_t* handle);
+int uv_tty_write(uv_loop_t* loop, uv_write_t* req, uv_tty_t* handle,
+    const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb);
+int uv__tty_try_write(uv_tty_t* handle, const uv_buf_t bufs[],
+    unsigned int nbufs);
+void uv_tty_close(uv_tty_t* handle);
+
+void uv_process_tty_read_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* req);
+void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_write_t* req);
+/* TODO: remove me */
+void uv_process_tty_accept_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* raw_req);
+/* TODO: remove me */
+void uv_process_tty_connect_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_connect_t* req);
+
+void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle);
+
+
+/*
+ * Poll watchers
+ */
+void uv_process_poll_req(uv_loop_t* loop, uv_poll_t* handle,
+    uv_req_t* req);
+
+int uv_poll_close(uv_loop_t* loop, uv_poll_t* handle);
+void uv_poll_endgame(uv_loop_t* loop, uv_poll_t* handle);
+
+
+/*
+ * Timers
+ */
+void uv_timer_endgame(uv_loop_t* loop, uv_timer_t* handle);
+
+DWORD uv__next_timeout(const uv_loop_t* loop);
+void uv_process_timers(uv_loop_t* loop);
+
+
+/*
+ * Loop watchers
+ */
+void uv_loop_watcher_endgame(uv_loop_t* loop, uv_handle_t* handle);
+
+void uv_prepare_invoke(uv_loop_t* loop);
+void uv_check_invoke(uv_loop_t* loop);
+void uv_idle_invoke(uv_loop_t* loop);
+
+void uv__once_init();
+
+
+/*
+ * Async watcher
+ */
+void uv_async_close(uv_loop_t* loop, uv_async_t* handle);
+void uv_async_endgame(uv_loop_t* loop, uv_async_t* handle);
+
+void uv_process_async_wakeup_req(uv_loop_t* loop, uv_async_t* handle,
+    uv_req_t* req);
+
+
+/*
+ * Signal watcher
+ */
+void uv_signals_init();
+int uv__signal_dispatch(int signum);
+
+void uv_signal_close(uv_loop_t* loop, uv_signal_t* handle);
+void uv_signal_endgame(uv_loop_t* loop, uv_signal_t* handle);
+
+void uv_process_signal_req(uv_loop_t* loop, uv_signal_t* handle,
+    uv_req_t* req);
+
+
+/*
+ * Spawn
+ */
+void uv_process_proc_exit(uv_loop_t* loop, uv_process_t* handle);
+void uv_process_close(uv_loop_t* loop, uv_process_t* handle);
+void uv_process_endgame(uv_loop_t* loop, uv_process_t* handle);
+
+
+/*
+ * Error
+ */
+int uv_translate_sys_error(int sys_errno);
+
+
+/*
+ * FS
+ */
+void uv_fs_init();
+
+
+/*
+ * FS Event
+ */
+void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req,
+    uv_fs_event_t* handle);
+void uv_fs_event_close(uv_loop_t* loop, uv_fs_event_t* handle);
+void uv_fs_event_endgame(uv_loop_t* loop, uv_fs_event_t* handle);
+
+
+/*
+ * Stat poller.
+ */
+void uv__fs_poll_endgame(uv_loop_t* loop, uv_fs_poll_t* handle);
+
+
+/*
+ * Utilities.
+ */
+void uv__util_init();
+
+uint64_t uv__hrtime(double scale);
+int uv_parent_pid();
+int uv_current_pid();
+__declspec(noreturn) void uv_fatal_error(const int errorno, const char* syscall);
+int uv__getpwuid_r(uv_passwd_t* pwd);
+int uv__convert_utf16_to_utf8(const WCHAR* utf16, int utf16len, char** utf8);
+
+
+/*
+ * Process stdio handles.
+ */
+int uv__stdio_create(uv_loop_t* loop,
+                     const uv_process_options_t* options,
+                     BYTE** buffer_ptr);
+void uv__stdio_destroy(BYTE* buffer);
+void uv__stdio_noinherit(BYTE* buffer);
+int uv__stdio_verify(BYTE* buffer, WORD size);
+WORD uv__stdio_size(BYTE* buffer);
+HANDLE uv__stdio_handle(BYTE* buffer, int fd);
+
+
+/*
+ * Winapi and ntapi utility functions
+ */
+void uv_winapi_init();
+
+
+/*
+ * Winsock utility functions
+ */
+void uv_winsock_init();
+
+int uv_ntstatus_to_winsock_error(NTSTATUS status);
+
+BOOL uv_get_acceptex_function(SOCKET socket, LPFN_ACCEPTEX* target);
+BOOL uv_get_connectex_function(SOCKET socket, LPFN_CONNECTEX* target);
+
+int WSAAPI uv_wsarecv_workaround(SOCKET socket, WSABUF* buffers,
+    DWORD buffer_count, DWORD* bytes, DWORD* flags, WSAOVERLAPPED *overlapped,
+    LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
+int WSAAPI uv_wsarecvfrom_workaround(SOCKET socket, WSABUF* buffers,
+    DWORD buffer_count, DWORD* bytes, DWORD* flags, struct sockaddr* addr,
+    int* addr_len, WSAOVERLAPPED *overlapped,
+    LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
+
+int WSAAPI uv_msafd_poll(SOCKET socket, AFD_POLL_INFO* info_in,
+    AFD_POLL_INFO* info_out, OVERLAPPED* overlapped);
+
+/* Whether there are any non-IFS LSPs stacked on TCP */
+extern int uv_tcp_non_ifs_lsp_ipv4;
+extern int uv_tcp_non_ifs_lsp_ipv6;
+
+/* Ip address used to bind to any port at any interface */
+extern struct sockaddr_in uv_addr_ip4_any_;
+extern struct sockaddr_in6 uv_addr_ip6_any_;
+
+/*
+ * Wake all loops with fake message
+ */
+void uv__wake_all_loops();
+
+/*
+ * Init system wake-up detection
+ */
+void uv__init_detect_system_wakeup();
+
+#endif /* UV_WIN_INTERNAL_H_ */
diff --git a/Utilities/cmlibuv/src/win/loop-watcher.c b/Utilities/cmlibuv/src/win/loop-watcher.c
new file mode 100644
index 0000000..20e4509
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/loop-watcher.c
@@ -0,0 +1,122 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+
+
+void uv_loop_watcher_endgame(uv_loop_t* loop, uv_handle_t* handle) {
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+    handle->flags |= UV_HANDLE_CLOSED;
+    uv__handle_close(handle);
+  }
+}
+
+
+#define UV_LOOP_WATCHER_DEFINE(name, NAME)                                    \
+  int uv_##name##_init(uv_loop_t* loop, uv_##name##_t* handle) {              \
+    uv__handle_init(loop, (uv_handle_t*) handle, UV_##NAME);                  \
+                                                                              \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+                                                                              \
+  int uv_##name##_start(uv_##name##_t* handle, uv_##name##_cb cb) {           \
+    uv_loop_t* loop = handle->loop;                                           \
+    uv_##name##_t* old_head;                                                  \
+                                                                              \
+    assert(handle->type == UV_##NAME);                                        \
+                                                                              \
+    if (uv__is_active(handle))                                                \
+      return 0;                                                               \
+                                                                              \
+    if (cb == NULL)                                                           \
+      return UV_EINVAL;                                                       \
+                                                                              \
+    old_head = loop->name##_handles;                                          \
+                                                                              \
+    handle->name##_next = old_head;                                           \
+    handle->name##_prev = NULL;                                               \
+                                                                              \
+    if (old_head) {                                                           \
+      old_head->name##_prev = handle;                                         \
+    }                                                                         \
+                                                                              \
+    loop->name##_handles = handle;                                            \
+                                                                              \
+    handle->name##_cb = cb;                                                   \
+    uv__handle_start(handle);                                                 \
+                                                                              \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+                                                                              \
+  int uv_##name##_stop(uv_##name##_t* handle) {                               \
+    uv_loop_t* loop = handle->loop;                                           \
+                                                                              \
+    assert(handle->type == UV_##NAME);                                        \
+                                                                              \
+    if (!uv__is_active(handle))                                               \
+      return 0;                                                               \
+                                                                              \
+    /* Update loop head if needed */                                          \
+    if (loop->name##_handles == handle) {                                     \
+      loop->name##_handles = handle->name##_next;                             \
+    }                                                                         \
+                                                                              \
+    /* Update the iterator-next pointer of needed */                          \
+    if (loop->next_##name##_handle == handle) {                               \
+      loop->next_##name##_handle = handle->name##_next;                       \
+    }                                                                         \
+                                                                              \
+    if (handle->name##_prev) {                                                \
+      handle->name##_prev->name##_next = handle->name##_next;                 \
+    }                                                                         \
+    if (handle->name##_next) {                                                \
+      handle->name##_next->name##_prev = handle->name##_prev;                 \
+    }                                                                         \
+                                                                              \
+    uv__handle_stop(handle);                                                  \
+                                                                              \
+    return 0;                                                                 \
+  }                                                                           \
+                                                                              \
+                                                                              \
+  void uv_##name##_invoke(uv_loop_t* loop) {                                  \
+    uv_##name##_t* handle;                                                    \
+                                                                              \
+    (loop)->next_##name##_handle = (loop)->name##_handles;                    \
+                                                                              \
+    while ((loop)->next_##name##_handle != NULL) {                            \
+      handle = (loop)->next_##name##_handle;                                  \
+      (loop)->next_##name##_handle = handle->name##_next;                     \
+                                                                              \
+      handle->name##_cb(handle);                                              \
+    }                                                                         \
+  }
+
+UV_LOOP_WATCHER_DEFINE(prepare, PREPARE)
+UV_LOOP_WATCHER_DEFINE(check, CHECK)
+UV_LOOP_WATCHER_DEFINE(idle, IDLE)
diff --git a/Utilities/cmlibuv/src/win/pipe.c b/Utilities/cmlibuv/src/win/pipe.c
new file mode 100644
index 0000000..2442be7
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/pipe.c
@@ -0,0 +1,2130 @@
+/* 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 <assert.h>
+#include <io.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "stream-inl.h"
+#include "req-inl.h"
+
+typedef struct uv__ipc_queue_item_s uv__ipc_queue_item_t;
+
+struct uv__ipc_queue_item_s {
+  /*
+   * NOTE: It is important for socket_info_ex to be the first field,
+   * because we will we assigning it to the pending_ipc_info.socket_info
+   */
+  uv__ipc_socket_info_ex socket_info_ex;
+  QUEUE member;
+  int tcp_connection;
+};
+
+/* A zero-size buffer for use by uv_pipe_read */
+static char uv_zero_[] = "";
+
+/* Null uv_buf_t */
+static const uv_buf_t uv_null_buf_ = { 0, NULL };
+
+/* The timeout that the pipe will wait for the remote end to write data */
+/* when the local ends wants to shut it down. */
+static const int64_t eof_timeout = 50; /* ms */
+
+static const int default_pending_pipe_instances = 4;
+
+/* Pipe prefix */
+static char pipe_prefix[] = "\\\\?\\pipe";
+static const int pipe_prefix_len = sizeof(pipe_prefix) - 1;
+
+/* IPC protocol flags. */
+#define UV_IPC_RAW_DATA       0x0001
+#define UV_IPC_TCP_SERVER     0x0002
+#define UV_IPC_TCP_CONNECTION 0x0004
+
+/* IPC frame header. */
+typedef struct {
+  int flags;
+  uint64_t raw_data_length;
+} uv_ipc_frame_header_t;
+
+/* IPC frame, which contains an imported TCP socket stream. */
+typedef struct {
+  uv_ipc_frame_header_t header;
+  uv__ipc_socket_info_ex socket_info_ex;
+} uv_ipc_frame_uv_stream;
+
+static void eof_timer_init(uv_pipe_t* pipe);
+static void eof_timer_start(uv_pipe_t* pipe);
+static void eof_timer_stop(uv_pipe_t* pipe);
+static void eof_timer_cb(uv_timer_t* timer);
+static void eof_timer_destroy(uv_pipe_t* pipe);
+static void eof_timer_close_cb(uv_handle_t* handle);
+
+
+static void uv_unique_pipe_name(char* ptr, char* name, size_t size) {
+  snprintf(name, size, "\\\\?\\pipe\\uv\\%p-%lu", ptr, GetCurrentProcessId());
+}
+
+
+int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) {
+  uv_stream_init(loop, (uv_stream_t*)handle, UV_NAMED_PIPE);
+
+  handle->reqs_pending = 0;
+  handle->handle = INVALID_HANDLE_VALUE;
+  handle->name = NULL;
+  handle->pipe.conn.ipc_pid = 0;
+  handle->pipe.conn.remaining_ipc_rawdata_bytes = 0;
+  QUEUE_INIT(&handle->pipe.conn.pending_ipc_info.queue);
+  handle->pipe.conn.pending_ipc_info.queue_len = 0;
+  handle->ipc = ipc;
+  handle->pipe.conn.non_overlapped_writes_tail = NULL;
+  handle->pipe.conn.readfile_thread = NULL;
+
+  uv_req_init(loop, (uv_req_t*) &handle->pipe.conn.ipc_header_write_req);
+
+  return 0;
+}
+
+
+static void uv_pipe_connection_init(uv_pipe_t* handle) {
+  uv_connection_init((uv_stream_t*) handle);
+  handle->read_req.data = handle;
+  handle->pipe.conn.eof_timer = NULL;
+  assert(!(handle->flags & UV_HANDLE_PIPESERVER));
+  if (pCancelSynchronousIo &&
+      handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) {
+      uv_mutex_init(&handle->pipe.conn.readfile_mutex);
+      handle->flags |= UV_HANDLE_PIPE_READ_CANCELABLE;
+  }
+}
+
+
+static HANDLE open_named_pipe(const WCHAR* name, DWORD* duplex_flags) {
+  HANDLE pipeHandle;
+
+  /*
+   * Assume that we have a duplex pipe first, so attempt to
+   * connect with GENERIC_READ | GENERIC_WRITE.
+   */
+  pipeHandle = CreateFileW(name,
+                           GENERIC_READ | GENERIC_WRITE,
+                           0,
+                           NULL,
+                           OPEN_EXISTING,
+                           FILE_FLAG_OVERLAPPED,
+                           NULL);
+  if (pipeHandle != INVALID_HANDLE_VALUE) {
+    *duplex_flags = UV_HANDLE_READABLE | UV_HANDLE_WRITABLE;
+    return pipeHandle;
+  }
+
+  /*
+   * If the pipe is not duplex CreateFileW fails with
+   * ERROR_ACCESS_DENIED.  In that case try to connect
+   * as a read-only or write-only.
+   */
+  if (GetLastError() == ERROR_ACCESS_DENIED) {
+    pipeHandle = CreateFileW(name,
+                             GENERIC_READ | FILE_WRITE_ATTRIBUTES,
+                             0,
+                             NULL,
+                             OPEN_EXISTING,
+                             FILE_FLAG_OVERLAPPED,
+                             NULL);
+
+    if (pipeHandle != INVALID_HANDLE_VALUE) {
+      *duplex_flags = UV_HANDLE_READABLE;
+      return pipeHandle;
+    }
+  }
+
+  if (GetLastError() == ERROR_ACCESS_DENIED) {
+    pipeHandle = CreateFileW(name,
+                             GENERIC_WRITE | FILE_READ_ATTRIBUTES,
+                             0,
+                             NULL,
+                             OPEN_EXISTING,
+                             FILE_FLAG_OVERLAPPED,
+                             NULL);
+
+    if (pipeHandle != INVALID_HANDLE_VALUE) {
+      *duplex_flags = UV_HANDLE_WRITABLE;
+      return pipeHandle;
+    }
+  }
+
+  return INVALID_HANDLE_VALUE;
+}
+
+
+static void close_pipe(uv_pipe_t* pipe) {
+  assert(pipe->u.fd == -1 || pipe->u.fd > 2);
+  if (pipe->u.fd == -1)
+    CloseHandle(pipe->handle);
+  else
+    close(pipe->u.fd);
+
+  pipe->u.fd = -1;
+  pipe->handle = INVALID_HANDLE_VALUE;
+}
+
+
+int uv_stdio_pipe_server(uv_loop_t* loop, uv_pipe_t* handle, DWORD access,
+    char* name, size_t nameSize) {
+  HANDLE pipeHandle;
+  int err;
+  char* ptr = (char*)handle;
+
+  for (;;) {
+    uv_unique_pipe_name(ptr, name, nameSize);
+
+    pipeHandle = CreateNamedPipeA(name,
+      access | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
+      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 65536, 65536, 0,
+      NULL);
+
+    if (pipeHandle != INVALID_HANDLE_VALUE) {
+      /* No name collisions.  We're done. */
+      break;
+    }
+
+    err = GetLastError();
+    if (err != ERROR_PIPE_BUSY && err != ERROR_ACCESS_DENIED) {
+      goto error;
+    }
+
+    /* Pipe name collision.  Increment the pointer and try again. */
+    ptr++;
+  }
+
+  if (CreateIoCompletionPort(pipeHandle,
+                             loop->iocp,
+                             (ULONG_PTR)handle,
+                             0) == NULL) {
+    err = GetLastError();
+    goto error;
+  }
+
+  uv_pipe_connection_init(handle);
+  handle->handle = pipeHandle;
+
+  return 0;
+
+ error:
+  if (pipeHandle != INVALID_HANDLE_VALUE) {
+    CloseHandle(pipeHandle);
+  }
+
+  return err;
+}
+
+
+static int uv_set_pipe_handle(uv_loop_t* loop,
+                              uv_pipe_t* handle,
+                              HANDLE pipeHandle,
+                              int fd,
+                              DWORD duplex_flags) {
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+  FILE_MODE_INFORMATION mode_info;
+  DWORD mode = PIPE_READMODE_BYTE | PIPE_WAIT;
+  DWORD current_mode = 0;
+  DWORD err = 0;
+
+  if (!(handle->flags & UV_HANDLE_PIPESERVER) &&
+      handle->handle != INVALID_HANDLE_VALUE)
+    return UV_EBUSY;
+
+  if (!SetNamedPipeHandleState(pipeHandle, &mode, NULL, NULL)) {
+    err = GetLastError();
+    if (err == ERROR_ACCESS_DENIED) {
+      /*
+       * SetNamedPipeHandleState can fail if the handle doesn't have either
+       * GENERIC_WRITE  or FILE_WRITE_ATTRIBUTES.
+       * But if the handle already has the desired wait and blocking modes
+       * we can continue.
+       */
+      if (!GetNamedPipeHandleState(pipeHandle, &current_mode, NULL, NULL,
+                                   NULL, NULL, 0)) {
+        return -1;
+      } else if (current_mode & PIPE_NOWAIT) {
+        SetLastError(ERROR_ACCESS_DENIED);
+        return -1;
+      }
+    } else {
+      /* If this returns ERROR_INVALID_PARAMETER we probably opened
+       * something that is not a pipe. */
+      if (err == ERROR_INVALID_PARAMETER) {
+        SetLastError(WSAENOTSOCK);
+      }
+      return -1;
+    }
+  }
+
+  /* Check if the pipe was created with FILE_FLAG_OVERLAPPED. */
+  nt_status = pNtQueryInformationFile(pipeHandle,
+                                      &io_status,
+                                      &mode_info,
+                                      sizeof(mode_info),
+                                      FileModeInformation);
+  if (nt_status != STATUS_SUCCESS) {
+    return -1;
+  }
+
+  if (mode_info.Mode & FILE_SYNCHRONOUS_IO_ALERT ||
+      mode_info.Mode & FILE_SYNCHRONOUS_IO_NONALERT) {
+    /* Non-overlapped pipe. */
+    handle->flags |= UV_HANDLE_NON_OVERLAPPED_PIPE;
+  } else {
+    /* Overlapped pipe.  Try to associate with IOCP. */
+    if (CreateIoCompletionPort(pipeHandle,
+                               loop->iocp,
+                               (ULONG_PTR)handle,
+                               0) == NULL) {
+      handle->flags |= UV_HANDLE_EMULATE_IOCP;
+    }
+  }
+
+  handle->handle = pipeHandle;
+  handle->u.fd = fd;
+  handle->flags |= duplex_flags;
+
+  return 0;
+}
+
+
+static DWORD WINAPI pipe_shutdown_thread_proc(void* parameter) {
+  uv_loop_t* loop;
+  uv_pipe_t* handle;
+  uv_shutdown_t* req;
+
+  req = (uv_shutdown_t*) parameter;
+  assert(req);
+  handle = (uv_pipe_t*) req->handle;
+  assert(handle);
+  loop = handle->loop;
+  assert(loop);
+
+  FlushFileBuffers(handle->handle);
+
+  /* Post completed */
+  POST_COMPLETION_FOR_REQ(loop, req);
+
+  return 0;
+}
+
+
+void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) {
+  int err;
+  DWORD result;
+  uv_shutdown_t* req;
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+  FILE_PIPE_LOCAL_INFORMATION pipe_info;
+  uv__ipc_queue_item_t* item;
+
+  if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) {
+    handle->flags &= ~UV_HANDLE_PIPE_READ_CANCELABLE;
+    uv_mutex_destroy(&handle->pipe.conn.readfile_mutex);
+  }
+
+  if ((handle->flags & UV_HANDLE_CONNECTION) &&
+      handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+    req = handle->stream.conn.shutdown_req;
+
+    /* Clear the shutdown_req field so we don't go here again. */
+    handle->stream.conn.shutdown_req = NULL;
+
+    if (handle->flags & UV__HANDLE_CLOSING) {
+      UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+      /* Already closing. Cancel the shutdown. */
+      if (req->cb) {
+        req->cb(req, UV_ECANCELED);
+      }
+
+      DECREASE_PENDING_REQ_COUNT(handle);
+      return;
+    }
+
+    /* Try to avoid flushing the pipe buffer in the thread pool. */
+    nt_status = pNtQueryInformationFile(handle->handle,
+                                        &io_status,
+                                        &pipe_info,
+                                        sizeof pipe_info,
+                                        FilePipeLocalInformation);
+
+    if (nt_status != STATUS_SUCCESS) {
+      /* Failure */
+      UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+      handle->flags |= UV_HANDLE_WRITABLE; /* Questionable */
+      if (req->cb) {
+        err = pRtlNtStatusToDosError(nt_status);
+        req->cb(req, uv_translate_sys_error(err));
+      }
+
+      DECREASE_PENDING_REQ_COUNT(handle);
+      return;
+    }
+
+    if (pipe_info.OutboundQuota == pipe_info.WriteQuotaAvailable) {
+      /* Short-circuit, no need to call FlushFileBuffers. */
+      uv_insert_pending_req(loop, (uv_req_t*) req);
+      return;
+    }
+
+    /* Run FlushFileBuffers in the thread pool. */
+    result = QueueUserWorkItem(pipe_shutdown_thread_proc,
+                               req,
+                               WT_EXECUTELONGFUNCTION);
+    if (result) {
+      return;
+
+    } else {
+      /* Failure. */
+      UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+      handle->flags |= UV_HANDLE_WRITABLE; /* Questionable */
+      if (req->cb) {
+        err = GetLastError();
+        req->cb(req, uv_translate_sys_error(err));
+      }
+
+      DECREASE_PENDING_REQ_COUNT(handle);
+      return;
+    }
+  }
+
+  if (handle->flags & UV__HANDLE_CLOSING &&
+      handle->reqs_pending == 0) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+    if (handle->flags & UV_HANDLE_CONNECTION) {
+      /* Free pending sockets */
+      while (!QUEUE_EMPTY(&handle->pipe.conn.pending_ipc_info.queue)) {
+        QUEUE* q;
+        SOCKET socket;
+
+        q = QUEUE_HEAD(&handle->pipe.conn.pending_ipc_info.queue);
+        QUEUE_REMOVE(q);
+        item = QUEUE_DATA(q, uv__ipc_queue_item_t, member);
+
+        /* Materialize socket and close it */
+        socket = WSASocketW(FROM_PROTOCOL_INFO,
+                            FROM_PROTOCOL_INFO,
+                            FROM_PROTOCOL_INFO,
+                            &item->socket_info_ex.socket_info,
+                            0,
+                            WSA_FLAG_OVERLAPPED);
+        uv__free(item);
+
+        if (socket != INVALID_SOCKET)
+          closesocket(socket);
+      }
+      handle->pipe.conn.pending_ipc_info.queue_len = 0;
+
+      if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+        if (handle->read_req.wait_handle != INVALID_HANDLE_VALUE) {
+          UnregisterWait(handle->read_req.wait_handle);
+          handle->read_req.wait_handle = INVALID_HANDLE_VALUE;
+        }
+        if (handle->read_req.event_handle) {
+          CloseHandle(handle->read_req.event_handle);
+          handle->read_req.event_handle = NULL;
+        }
+      }
+    }
+
+    if (handle->flags & UV_HANDLE_PIPESERVER) {
+      assert(handle->pipe.serv.accept_reqs);
+      uv__free(handle->pipe.serv.accept_reqs);
+      handle->pipe.serv.accept_reqs = NULL;
+    }
+
+    uv__handle_close(handle);
+  }
+}
+
+
+void uv_pipe_pending_instances(uv_pipe_t* handle, int count) {
+  if (handle->flags & UV_HANDLE_BOUND)
+    return;
+  handle->pipe.serv.pending_instances = count;
+  handle->flags |= UV_HANDLE_PIPESERVER;
+}
+
+
+/* Creates a pipe server. */
+int uv_pipe_bind(uv_pipe_t* handle, const char* name) {
+  uv_loop_t* loop = handle->loop;
+  int i, err, nameSize;
+  uv_pipe_accept_t* req;
+
+  if (handle->flags & UV_HANDLE_BOUND) {
+    return UV_EINVAL;
+  }
+
+  if (!name) {
+    return UV_EINVAL;
+  }
+
+  if (!(handle->flags & UV_HANDLE_PIPESERVER)) {
+    handle->pipe.serv.pending_instances = default_pending_pipe_instances;
+  }
+
+  handle->pipe.serv.accept_reqs = (uv_pipe_accept_t*)
+    uv__malloc(sizeof(uv_pipe_accept_t) * handle->pipe.serv.pending_instances);
+  if (!handle->pipe.serv.accept_reqs) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  for (i = 0; i < handle->pipe.serv.pending_instances; i++) {
+    req = &handle->pipe.serv.accept_reqs[i];
+    uv_req_init(loop, (uv_req_t*) req);
+    req->type = UV_ACCEPT;
+    req->data = handle;
+    req->pipeHandle = INVALID_HANDLE_VALUE;
+    req->next_pending = NULL;
+  }
+
+  /* Convert name to UTF16. */
+  nameSize = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0) * sizeof(WCHAR);
+  handle->name = (WCHAR*)uv__malloc(nameSize);
+  if (!handle->name) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  if (!MultiByteToWideChar(CP_UTF8,
+                           0,
+                           name,
+                           -1,
+                           handle->name,
+                           nameSize / sizeof(WCHAR))) {
+    err = GetLastError();
+    goto error;
+  }
+
+  /*
+   * Attempt to create the first pipe with FILE_FLAG_FIRST_PIPE_INSTANCE.
+   * If this fails then there's already a pipe server for the given pipe name.
+   */
+  handle->pipe.serv.accept_reqs[0].pipeHandle = CreateNamedPipeW(handle->name,
+      PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
+      FILE_FLAG_FIRST_PIPE_INSTANCE,
+      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+      PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL);
+
+  if (handle->pipe.serv.accept_reqs[0].pipeHandle == INVALID_HANDLE_VALUE) {
+    err = GetLastError();
+    if (err == ERROR_ACCESS_DENIED) {
+      err = WSAEADDRINUSE;  /* Translates to UV_EADDRINUSE. */
+    } else if (err == ERROR_PATH_NOT_FOUND || err == ERROR_INVALID_NAME) {
+      err = WSAEACCES;  /* Translates to UV_EACCES. */
+    }
+    goto error;
+  }
+
+  if (uv_set_pipe_handle(loop,
+                         handle,
+                         handle->pipe.serv.accept_reqs[0].pipeHandle,
+                         -1,
+                         0)) {
+    err = GetLastError();
+    goto error;
+  }
+
+  handle->pipe.serv.pending_accepts = NULL;
+  handle->flags |= UV_HANDLE_PIPESERVER;
+  handle->flags |= UV_HANDLE_BOUND;
+
+  return 0;
+
+error:
+  if (handle->name) {
+    uv__free(handle->name);
+    handle->name = NULL;
+  }
+
+  if (handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE) {
+    CloseHandle(handle->pipe.serv.accept_reqs[0].pipeHandle);
+    handle->pipe.serv.accept_reqs[0].pipeHandle = INVALID_HANDLE_VALUE;
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+static DWORD WINAPI pipe_connect_thread_proc(void* parameter) {
+  uv_loop_t* loop;
+  uv_pipe_t* handle;
+  uv_connect_t* req;
+  HANDLE pipeHandle = INVALID_HANDLE_VALUE;
+  DWORD duplex_flags;
+
+  req = (uv_connect_t*) parameter;
+  assert(req);
+  handle = (uv_pipe_t*) req->handle;
+  assert(handle);
+  loop = handle->loop;
+  assert(loop);
+
+  /* We're here because CreateFile on a pipe returned ERROR_PIPE_BUSY. */
+  /* We wait for the pipe to become available with WaitNamedPipe. */
+  while (WaitNamedPipeW(handle->name, 30000)) {
+    /* The pipe is now available, try to connect. */
+    pipeHandle = open_named_pipe(handle->name, &duplex_flags);
+    if (pipeHandle != INVALID_HANDLE_VALUE) {
+      break;
+    }
+
+    SwitchToThread();
+  }
+
+  if (pipeHandle != INVALID_HANDLE_VALUE &&
+      !uv_set_pipe_handle(loop, handle, pipeHandle, -1, duplex_flags)) {
+    SET_REQ_SUCCESS(req);
+  } else {
+    SET_REQ_ERROR(req, GetLastError());
+  }
+
+  /* Post completed */
+  POST_COMPLETION_FOR_REQ(loop, req);
+
+  return 0;
+}
+
+
+void uv_pipe_connect(uv_connect_t* req, uv_pipe_t* handle,
+    const char* name, uv_connect_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  int err, nameSize;
+  HANDLE pipeHandle = INVALID_HANDLE_VALUE;
+  DWORD duplex_flags;
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_CONNECT;
+  req->handle = (uv_stream_t*) handle;
+  req->cb = cb;
+
+  /* Convert name to UTF16. */
+  nameSize = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0) * sizeof(WCHAR);
+  handle->name = (WCHAR*)uv__malloc(nameSize);
+  if (!handle->name) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  if (!MultiByteToWideChar(CP_UTF8,
+                           0,
+                           name,
+                           -1,
+                           handle->name,
+                           nameSize / sizeof(WCHAR))) {
+    err = GetLastError();
+    goto error;
+  }
+
+  pipeHandle = open_named_pipe(handle->name, &duplex_flags);
+  if (pipeHandle == INVALID_HANDLE_VALUE) {
+    if (GetLastError() == ERROR_PIPE_BUSY) {
+      /* Wait for the server to make a pipe instance available. */
+      if (!QueueUserWorkItem(&pipe_connect_thread_proc,
+                             req,
+                             WT_EXECUTELONGFUNCTION)) {
+        err = GetLastError();
+        goto error;
+      }
+
+      REGISTER_HANDLE_REQ(loop, handle, req);
+      handle->reqs_pending++;
+
+      return;
+    }
+
+    err = GetLastError();
+    goto error;
+  }
+
+  assert(pipeHandle != INVALID_HANDLE_VALUE);
+
+  if (uv_set_pipe_handle(loop,
+                         (uv_pipe_t*) req->handle,
+                         pipeHandle,
+                         -1,
+                         duplex_flags)) {
+    err = GetLastError();
+    goto error;
+  }
+
+  SET_REQ_SUCCESS(req);
+  uv_insert_pending_req(loop, (uv_req_t*) req);
+  handle->reqs_pending++;
+  REGISTER_HANDLE_REQ(loop, handle, req);
+  return;
+
+error:
+  if (handle->name) {
+    uv__free(handle->name);
+    handle->name = NULL;
+  }
+
+  if (pipeHandle != INVALID_HANDLE_VALUE) {
+    CloseHandle(pipeHandle);
+  }
+
+  /* Make this req pending reporting an error. */
+  SET_REQ_ERROR(req, err);
+  uv_insert_pending_req(loop, (uv_req_t*) req);
+  handle->reqs_pending++;
+  REGISTER_HANDLE_REQ(loop, handle, req);
+  return;
+}
+
+
+void uv__pipe_pause_read(uv_pipe_t* handle) {
+  if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) {
+      /* Pause the ReadFile task briefly, to work
+         around the Windows kernel bug that causes
+         any access to a NamedPipe to deadlock if
+         any process has called ReadFile */
+      HANDLE h;
+      uv_mutex_lock(&handle->pipe.conn.readfile_mutex);
+      h = handle->pipe.conn.readfile_thread;
+      while (h) {
+        /* spinlock: we expect this to finish quickly,
+           or we are probably about to deadlock anyways
+           (in the kernel), so it doesn't matter */
+        pCancelSynchronousIo(h);
+        SwitchToThread(); /* yield thread control briefly */
+        h = handle->pipe.conn.readfile_thread;
+      }
+  }
+}
+
+
+void uv__pipe_unpause_read(uv_pipe_t* handle) {
+  if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) {
+    uv_mutex_unlock(&handle->pipe.conn.readfile_mutex);
+  }
+}
+
+
+void uv__pipe_stop_read(uv_pipe_t* handle) {
+  handle->flags &= ~UV_HANDLE_READING;
+  uv__pipe_pause_read((uv_pipe_t*)handle);
+  uv__pipe_unpause_read((uv_pipe_t*)handle);
+}
+
+
+/* Cleans up uv_pipe_t (server or connection) and all resources associated */
+/* with it. */
+void uv_pipe_cleanup(uv_loop_t* loop, uv_pipe_t* handle) {
+  int i;
+  HANDLE pipeHandle;
+
+  uv__pipe_stop_read(handle);
+
+  if (handle->name) {
+    uv__free(handle->name);
+    handle->name = NULL;
+  }
+
+  if (handle->flags & UV_HANDLE_PIPESERVER) {
+    for (i = 0; i < handle->pipe.serv.pending_instances; i++) {
+      pipeHandle = handle->pipe.serv.accept_reqs[i].pipeHandle;
+      if (pipeHandle != INVALID_HANDLE_VALUE) {
+        CloseHandle(pipeHandle);
+        handle->pipe.serv.accept_reqs[i].pipeHandle = INVALID_HANDLE_VALUE;
+      }
+    }
+    handle->handle = INVALID_HANDLE_VALUE;
+  }
+
+  if (handle->flags & UV_HANDLE_CONNECTION) {
+    handle->flags &= ~UV_HANDLE_WRITABLE;
+    eof_timer_destroy(handle);
+  }
+
+  if ((handle->flags & UV_HANDLE_CONNECTION)
+      && handle->handle != INVALID_HANDLE_VALUE)
+    close_pipe(handle);
+}
+
+
+void uv_pipe_close(uv_loop_t* loop, uv_pipe_t* handle) {
+  if (handle->flags & UV_HANDLE_READING) {
+    handle->flags &= ~UV_HANDLE_READING;
+    DECREASE_ACTIVE_COUNT(loop, handle);
+  }
+
+  if (handle->flags & UV_HANDLE_LISTENING) {
+    handle->flags &= ~UV_HANDLE_LISTENING;
+    DECREASE_ACTIVE_COUNT(loop, handle);
+  }
+
+  uv_pipe_cleanup(loop, handle);
+
+  if (handle->reqs_pending == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+
+  handle->flags &= ~(UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
+  uv__handle_closing(handle);
+}
+
+
+static void uv_pipe_queue_accept(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_pipe_accept_t* req, BOOL firstInstance) {
+  assert(handle->flags & UV_HANDLE_LISTENING);
+
+  if (!firstInstance) {
+    assert(req->pipeHandle == INVALID_HANDLE_VALUE);
+
+    req->pipeHandle = CreateNamedPipeW(handle->name,
+        PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
+        PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+        PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL);
+
+    if (req->pipeHandle == INVALID_HANDLE_VALUE) {
+      SET_REQ_ERROR(req, GetLastError());
+      uv_insert_pending_req(loop, (uv_req_t*) req);
+      handle->reqs_pending++;
+      return;
+    }
+
+    if (uv_set_pipe_handle(loop, handle, req->pipeHandle, -1, 0)) {
+      CloseHandle(req->pipeHandle);
+      req->pipeHandle = INVALID_HANDLE_VALUE;
+      SET_REQ_ERROR(req, GetLastError());
+      uv_insert_pending_req(loop, (uv_req_t*) req);
+      handle->reqs_pending++;
+      return;
+    }
+  }
+
+  assert(req->pipeHandle != INVALID_HANDLE_VALUE);
+
+  /* Prepare the overlapped structure. */
+  memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped));
+
+  if (!ConnectNamedPipe(req->pipeHandle, &req->u.io.overlapped) &&
+      GetLastError() != ERROR_IO_PENDING) {
+    if (GetLastError() == ERROR_PIPE_CONNECTED) {
+      SET_REQ_SUCCESS(req);
+    } else {
+      CloseHandle(req->pipeHandle);
+      req->pipeHandle = INVALID_HANDLE_VALUE;
+      /* Make this req pending reporting an error. */
+      SET_REQ_ERROR(req, GetLastError());
+    }
+    uv_insert_pending_req(loop, (uv_req_t*) req);
+    handle->reqs_pending++;
+    return;
+  }
+
+  handle->reqs_pending++;
+}
+
+
+int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) {
+  uv_loop_t* loop = server->loop;
+  uv_pipe_t* pipe_client;
+  uv_pipe_accept_t* req;
+  QUEUE* q;
+  uv__ipc_queue_item_t* item;
+  int err;
+
+  if (server->ipc) {
+    if (QUEUE_EMPTY(&server->pipe.conn.pending_ipc_info.queue)) {
+      /* No valid pending sockets. */
+      return WSAEWOULDBLOCK;
+    }
+
+    q = QUEUE_HEAD(&server->pipe.conn.pending_ipc_info.queue);
+    QUEUE_REMOVE(q);
+    server->pipe.conn.pending_ipc_info.queue_len--;
+    item = QUEUE_DATA(q, uv__ipc_queue_item_t, member);
+
+    err = uv_tcp_import((uv_tcp_t*)client,
+                        &item->socket_info_ex,
+                        item->tcp_connection);
+    if (err != 0)
+      return err;
+
+    uv__free(item);
+
+  } else {
+    pipe_client = (uv_pipe_t*)client;
+
+    /* Find a connection instance that has been connected, but not yet */
+    /* accepted. */
+    req = server->pipe.serv.pending_accepts;
+
+    if (!req) {
+      /* No valid connections found, so we error out. */
+      return WSAEWOULDBLOCK;
+    }
+
+    /* Initialize the client handle and copy the pipeHandle to the client */
+    uv_pipe_connection_init(pipe_client);
+    pipe_client->handle = req->pipeHandle;
+    pipe_client->flags |= UV_HANDLE_READABLE | UV_HANDLE_WRITABLE;
+
+    /* Prepare the req to pick up a new connection */
+    server->pipe.serv.pending_accepts = req->next_pending;
+    req->next_pending = NULL;
+    req->pipeHandle = INVALID_HANDLE_VALUE;
+
+    if (!(server->flags & UV__HANDLE_CLOSING)) {
+      uv_pipe_queue_accept(loop, server, req, FALSE);
+    }
+  }
+
+  return 0;
+}
+
+
+/* Starts listening for connections for the given pipe. */
+int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  int i;
+
+  if (handle->flags & UV_HANDLE_LISTENING) {
+    handle->stream.serv.connection_cb = cb;
+  }
+
+  if (!(handle->flags & UV_HANDLE_BOUND)) {
+    return WSAEINVAL;
+  }
+
+  if (handle->flags & UV_HANDLE_READING) {
+    return WSAEISCONN;
+  }
+
+  if (!(handle->flags & UV_HANDLE_PIPESERVER)) {
+    return ERROR_NOT_SUPPORTED;
+  }
+
+  handle->flags |= UV_HANDLE_LISTENING;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+  handle->stream.serv.connection_cb = cb;
+
+  /* First pipe handle should have already been created in uv_pipe_bind */
+  assert(handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE);
+
+  for (i = 0; i < handle->pipe.serv.pending_instances; i++) {
+    uv_pipe_queue_accept(loop, handle, &handle->pipe.serv.accept_reqs[i], i == 0);
+  }
+
+  return 0;
+}
+
+
+static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) {
+  int result;
+  DWORD bytes;
+  uv_read_t* req = (uv_read_t*) parameter;
+  uv_pipe_t* handle = (uv_pipe_t*) req->data;
+  uv_loop_t* loop = handle->loop;
+  HANDLE hThread = NULL;
+  DWORD err;
+  uv_mutex_t *m = &handle->pipe.conn.readfile_mutex;
+
+  assert(req != NULL);
+  assert(req->type == UV_READ);
+  assert(handle->type == UV_NAMED_PIPE);
+
+  if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) {
+    uv_mutex_lock(m); /* mutex controls *setting* of readfile_thread */
+    if (DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
+                        GetCurrentProcess(), &hThread,
+                        0, TRUE, DUPLICATE_SAME_ACCESS)) {
+      handle->pipe.conn.readfile_thread = hThread;
+    } else {
+      hThread = NULL;
+    }
+    uv_mutex_unlock(m);
+  }
+restart_readfile:
+  result = ReadFile(handle->handle,
+                    &uv_zero_,
+                    0,
+                    &bytes,
+                    NULL);
+  if (!result) {
+    err = GetLastError();
+    if (err == ERROR_OPERATION_ABORTED &&
+        handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) {
+      if (handle->flags & UV_HANDLE_READING) {
+        /* just a brief break to do something else */
+        handle->pipe.conn.readfile_thread = NULL;
+        /* resume after it is finished */
+        uv_mutex_lock(m);
+        handle->pipe.conn.readfile_thread = hThread;
+        uv_mutex_unlock(m);
+        goto restart_readfile;
+      } else {
+        result = 1; /* successfully stopped reading */
+      }
+    }
+  }
+  if (hThread) {
+    assert(hThread == handle->pipe.conn.readfile_thread);
+    /* mutex does not control clearing readfile_thread */
+    handle->pipe.conn.readfile_thread = NULL;
+    uv_mutex_lock(m);
+    /* only when we hold the mutex lock is it safe to
+       open or close the handle */
+    CloseHandle(hThread);
+    uv_mutex_unlock(m);
+  }
+
+  if (!result) {
+    SET_REQ_ERROR(req, err);
+  }
+
+  POST_COMPLETION_FOR_REQ(loop, req);
+  return 0;
+}
+
+
+static DWORD WINAPI uv_pipe_writefile_thread_proc(void* parameter) {
+  int result;
+  DWORD bytes;
+  uv_write_t* req = (uv_write_t*) parameter;
+  uv_pipe_t* handle = (uv_pipe_t*) req->handle;
+  uv_loop_t* loop = handle->loop;
+
+  assert(req != NULL);
+  assert(req->type == UV_WRITE);
+  assert(handle->type == UV_NAMED_PIPE);
+  assert(req->write_buffer.base);
+
+  result = WriteFile(handle->handle,
+                     req->write_buffer.base,
+                     req->write_buffer.len,
+                     &bytes,
+                     NULL);
+
+  if (!result) {
+    SET_REQ_ERROR(req, GetLastError());
+  }
+
+  POST_COMPLETION_FOR_REQ(loop, req);
+  return 0;
+}
+
+
+static void CALLBACK post_completion_read_wait(void* context, BOOLEAN timed_out) {
+  uv_read_t* req;
+  uv_tcp_t* handle;
+
+  req = (uv_read_t*) context;
+  assert(req != NULL);
+  handle = (uv_tcp_t*)req->data;
+  assert(handle != NULL);
+  assert(!timed_out);
+
+  if (!PostQueuedCompletionStatus(handle->loop->iocp,
+                                  req->u.io.overlapped.InternalHigh,
+                                  0,
+                                  &req->u.io.overlapped)) {
+    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");
+  }
+}
+
+
+static void CALLBACK post_completion_write_wait(void* context, BOOLEAN timed_out) {
+  uv_write_t* req;
+  uv_tcp_t* handle;
+
+  req = (uv_write_t*) context;
+  assert(req != NULL);
+  handle = (uv_tcp_t*)req->handle;
+  assert(handle != NULL);
+  assert(!timed_out);
+
+  if (!PostQueuedCompletionStatus(handle->loop->iocp,
+                                  req->u.io.overlapped.InternalHigh,
+                                  0,
+                                  &req->u.io.overlapped)) {
+    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");
+  }
+}
+
+
+static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) {
+  uv_read_t* req;
+  int result;
+
+  assert(handle->flags & UV_HANDLE_READING);
+  assert(!(handle->flags & UV_HANDLE_READ_PENDING));
+
+  assert(handle->handle != INVALID_HANDLE_VALUE);
+
+  req = &handle->read_req;
+
+  if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) {
+    if (!QueueUserWorkItem(&uv_pipe_zero_readfile_thread_proc,
+                           req,
+                           WT_EXECUTELONGFUNCTION)) {
+      /* Make this req pending reporting an error. */
+      SET_REQ_ERROR(req, GetLastError());
+      goto error;
+    }
+  } else {
+    memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+      req->u.io.overlapped.hEvent = (HANDLE) ((uintptr_t) req->event_handle | 1);
+    }
+
+    /* Do 0-read */
+    result = ReadFile(handle->handle,
+                      &uv_zero_,
+                      0,
+                      NULL,
+                      &req->u.io.overlapped);
+
+    if (!result && GetLastError() != ERROR_IO_PENDING) {
+      /* Make this req pending reporting an error. */
+      SET_REQ_ERROR(req, GetLastError());
+      goto error;
+    }
+
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+      if (!req->event_handle) {
+        req->event_handle = CreateEvent(NULL, 0, 0, NULL);
+        if (!req->event_handle) {
+          uv_fatal_error(GetLastError(), "CreateEvent");
+        }
+      }
+      if (req->wait_handle == INVALID_HANDLE_VALUE) {
+        if (!RegisterWaitForSingleObject(&req->wait_handle,
+            req->u.io.overlapped.hEvent, post_completion_read_wait, (void*) req,
+            INFINITE, WT_EXECUTEINWAITTHREAD)) {
+          SET_REQ_ERROR(req, GetLastError());
+          goto error;
+        }
+      }
+    }
+  }
+
+  /* Start the eof timer if there is one */
+  eof_timer_start(handle);
+  handle->flags |= UV_HANDLE_READ_PENDING;
+  handle->reqs_pending++;
+  return;
+
+error:
+  uv_insert_pending_req(loop, (uv_req_t*)req);
+  handle->flags |= UV_HANDLE_READ_PENDING;
+  handle->reqs_pending++;
+}
+
+
+int uv_pipe_read_start(uv_pipe_t* handle,
+                       uv_alloc_cb alloc_cb,
+                       uv_read_cb read_cb) {
+  uv_loop_t* loop = handle->loop;
+
+  handle->flags |= UV_HANDLE_READING;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+  handle->read_cb = read_cb;
+  handle->alloc_cb = alloc_cb;
+
+  /* If reading was stopped and then started again, there could still be a */
+  /* read request pending. */
+  if (!(handle->flags & UV_HANDLE_READ_PENDING))
+    uv_pipe_queue_read(loop, handle);
+
+  return 0;
+}
+
+
+static void uv_insert_non_overlapped_write_req(uv_pipe_t* handle,
+    uv_write_t* req) {
+  req->next_req = NULL;
+  if (handle->pipe.conn.non_overlapped_writes_tail) {
+    req->next_req =
+      handle->pipe.conn.non_overlapped_writes_tail->next_req;
+    handle->pipe.conn.non_overlapped_writes_tail->next_req = (uv_req_t*)req;
+    handle->pipe.conn.non_overlapped_writes_tail = req;
+  } else {
+    req->next_req = (uv_req_t*)req;
+    handle->pipe.conn.non_overlapped_writes_tail = req;
+  }
+}
+
+
+static uv_write_t* uv_remove_non_overlapped_write_req(uv_pipe_t* handle) {
+  uv_write_t* req;
+
+  if (handle->pipe.conn.non_overlapped_writes_tail) {
+    req = (uv_write_t*)handle->pipe.conn.non_overlapped_writes_tail->next_req;
+
+    if (req == handle->pipe.conn.non_overlapped_writes_tail) {
+      handle->pipe.conn.non_overlapped_writes_tail = NULL;
+    } else {
+      handle->pipe.conn.non_overlapped_writes_tail->next_req =
+        req->next_req;
+    }
+
+    return req;
+  } else {
+    /* queue empty */
+    return NULL;
+  }
+}
+
+
+static void uv_queue_non_overlapped_write(uv_pipe_t* handle) {
+  uv_write_t* req = uv_remove_non_overlapped_write_req(handle);
+  if (req) {
+    if (!QueueUserWorkItem(&uv_pipe_writefile_thread_proc,
+                           req,
+                           WT_EXECUTELONGFUNCTION)) {
+      uv_fatal_error(GetLastError(), "QueueUserWorkItem");
+    }
+  }
+}
+
+
+static int uv_pipe_write_impl(uv_loop_t* loop,
+                              uv_write_t* req,
+                              uv_pipe_t* handle,
+                              const uv_buf_t bufs[],
+                              unsigned int nbufs,
+                              uv_stream_t* send_handle,
+                              uv_write_cb cb) {
+  int err;
+  int result;
+  uv_tcp_t* tcp_send_handle;
+  uv_write_t* ipc_header_req = NULL;
+  uv_ipc_frame_uv_stream ipc_frame;
+
+  if (nbufs != 1 && (nbufs != 0 || !send_handle)) {
+    return ERROR_NOT_SUPPORTED;
+  }
+
+  /* Only TCP handles are supported for sharing. */
+  if (send_handle && ((send_handle->type != UV_TCP) ||
+      (!(send_handle->flags & UV_HANDLE_BOUND) &&
+       !(send_handle->flags & UV_HANDLE_CONNECTION)))) {
+    return ERROR_NOT_SUPPORTED;
+  }
+
+  assert(handle->handle != INVALID_HANDLE_VALUE);
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_WRITE;
+  req->handle = (uv_stream_t*) handle;
+  req->cb = cb;
+  req->ipc_header = 0;
+  req->event_handle = NULL;
+  req->wait_handle = INVALID_HANDLE_VALUE;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  if (handle->ipc) {
+    assert(!(handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE));
+    ipc_frame.header.flags = 0;
+
+    /* Use the IPC framing protocol. */
+    if (send_handle) {
+      tcp_send_handle = (uv_tcp_t*)send_handle;
+
+      if (handle->pipe.conn.ipc_pid == 0) {
+          handle->pipe.conn.ipc_pid = uv_current_pid();
+      }
+
+      err = uv_tcp_duplicate_socket(tcp_send_handle, handle->pipe.conn.ipc_pid,
+          &ipc_frame.socket_info_ex.socket_info);
+      if (err) {
+        return err;
+      }
+
+      ipc_frame.socket_info_ex.delayed_error = tcp_send_handle->delayed_error;
+
+      ipc_frame.header.flags |= UV_IPC_TCP_SERVER;
+
+      if (tcp_send_handle->flags & UV_HANDLE_CONNECTION) {
+        ipc_frame.header.flags |= UV_IPC_TCP_CONNECTION;
+      }
+    }
+
+    if (nbufs == 1) {
+      ipc_frame.header.flags |= UV_IPC_RAW_DATA;
+      ipc_frame.header.raw_data_length = bufs[0].len;
+    }
+
+    /*
+     * Use the provided req if we're only doing a single write.
+     * If we're doing multiple writes, use ipc_header_write_req to do
+     * the first write, and then use the provided req for the second write.
+     */
+    if (!(ipc_frame.header.flags & UV_IPC_RAW_DATA)) {
+      ipc_header_req = req;
+    } else {
+      /*
+       * Try to use the preallocated write req if it's available.
+       * Otherwise allocate a new one.
+       */
+      if (handle->pipe.conn.ipc_header_write_req.type != UV_WRITE) {
+        ipc_header_req = (uv_write_t*)&handle->pipe.conn.ipc_header_write_req;
+      } else {
+        ipc_header_req = (uv_write_t*)uv__malloc(sizeof(uv_write_t));
+        if (!ipc_header_req) {
+          uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+        }
+      }
+
+      uv_req_init(loop, (uv_req_t*) ipc_header_req);
+      ipc_header_req->type = UV_WRITE;
+      ipc_header_req->handle = (uv_stream_t*) handle;
+      ipc_header_req->cb = NULL;
+      ipc_header_req->ipc_header = 1;
+    }
+
+    /* Write the header or the whole frame. */
+    memset(&ipc_header_req->u.io.overlapped, 0,
+           sizeof(ipc_header_req->u.io.overlapped));
+
+    /* Using overlapped IO, but wait for completion before returning.
+       This write is blocking because ipc_frame is on stack. */
+    ipc_header_req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL);
+    if (!ipc_header_req->u.io.overlapped.hEvent) {
+      uv_fatal_error(GetLastError(), "CreateEvent");
+    }
+
+    result = WriteFile(handle->handle,
+                        &ipc_frame,
+                        ipc_frame.header.flags & UV_IPC_TCP_SERVER ?
+                          sizeof(ipc_frame) : sizeof(ipc_frame.header),
+                        NULL,
+                        &ipc_header_req->u.io.overlapped);
+    if (!result && GetLastError() != ERROR_IO_PENDING) {
+      err = GetLastError();
+      CloseHandle(ipc_header_req->u.io.overlapped.hEvent);
+      return err;
+    }
+
+    if (!result) {
+      /* Request not completed immediately. Wait for it.*/
+      if (WaitForSingleObject(ipc_header_req->u.io.overlapped.hEvent, INFINITE) !=
+          WAIT_OBJECT_0) {
+        err = GetLastError();
+        CloseHandle(ipc_header_req->u.io.overlapped.hEvent);
+        return err;
+      }
+    }
+    ipc_header_req->u.io.queued_bytes = 0;
+    CloseHandle(ipc_header_req->u.io.overlapped.hEvent);
+    ipc_header_req->u.io.overlapped.hEvent = NULL;
+
+    REGISTER_HANDLE_REQ(loop, handle, ipc_header_req);
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+
+    /* If we don't have any raw data to write - we're done. */
+    if (!(ipc_frame.header.flags & UV_IPC_RAW_DATA)) {
+      return 0;
+    }
+  }
+
+  if ((handle->flags &
+      (UV_HANDLE_BLOCKING_WRITES | UV_HANDLE_NON_OVERLAPPED_PIPE)) ==
+      (UV_HANDLE_BLOCKING_WRITES | UV_HANDLE_NON_OVERLAPPED_PIPE)) {
+    DWORD bytes;
+    result = WriteFile(handle->handle,
+                       bufs[0].base,
+                       bufs[0].len,
+                       &bytes,
+                       NULL);
+
+    if (!result) {
+      err = GetLastError();
+      return err;
+    } else {
+      /* Request completed immediately. */
+      req->u.io.queued_bytes = 0;
+    }
+
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+    POST_COMPLETION_FOR_REQ(loop, req);
+    return 0;
+  } else if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) {
+    req->write_buffer = bufs[0];
+    uv_insert_non_overlapped_write_req(handle, req);
+    if (handle->stream.conn.write_reqs_pending == 0) {
+      uv_queue_non_overlapped_write(handle);
+    }
+
+    /* Request queued by the kernel. */
+    req->u.io.queued_bytes = bufs[0].len;
+    handle->write_queue_size += req->u.io.queued_bytes;
+  } else if (handle->flags & UV_HANDLE_BLOCKING_WRITES) {
+    /* Using overlapped IO, but wait for completion before returning */
+    req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL);
+    if (!req->u.io.overlapped.hEvent) {
+      uv_fatal_error(GetLastError(), "CreateEvent");
+    }
+
+    result = WriteFile(handle->handle,
+                       bufs[0].base,
+                       bufs[0].len,
+                       NULL,
+                       &req->u.io.overlapped);
+
+    if (!result && GetLastError() != ERROR_IO_PENDING) {
+      err = GetLastError();
+      CloseHandle(req->u.io.overlapped.hEvent);
+      return err;
+    }
+
+    if (result) {
+      /* Request completed immediately. */
+      req->u.io.queued_bytes = 0;
+    } else {
+      /* Request queued by the kernel. */
+      req->u.io.queued_bytes = bufs[0].len;
+      handle->write_queue_size += req->u.io.queued_bytes;
+      if (WaitForSingleObject(req->u.io.overlapped.hEvent, INFINITE) !=
+          WAIT_OBJECT_0) {
+        err = GetLastError();
+        CloseHandle(req->u.io.overlapped.hEvent);
+        return uv_translate_sys_error(err);
+      }
+    }
+    CloseHandle(req->u.io.overlapped.hEvent);
+
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+    return 0;
+  } else {
+    result = WriteFile(handle->handle,
+                       bufs[0].base,
+                       bufs[0].len,
+                       NULL,
+                       &req->u.io.overlapped);
+
+    if (!result && GetLastError() != ERROR_IO_PENDING) {
+      return GetLastError();
+    }
+
+    if (result) {
+      /* Request completed immediately. */
+      req->u.io.queued_bytes = 0;
+    } else {
+      /* Request queued by the kernel. */
+      req->u.io.queued_bytes = bufs[0].len;
+      handle->write_queue_size += req->u.io.queued_bytes;
+    }
+
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+      req->event_handle = CreateEvent(NULL, 0, 0, NULL);
+      if (!req->event_handle) {
+        uv_fatal_error(GetLastError(), "CreateEvent");
+      }
+      if (!RegisterWaitForSingleObject(&req->wait_handle,
+          req->u.io.overlapped.hEvent, post_completion_write_wait, (void*) req,
+          INFINITE, WT_EXECUTEINWAITTHREAD)) {
+        return GetLastError();
+      }
+    }
+  }
+
+  REGISTER_HANDLE_REQ(loop, handle, req);
+  handle->reqs_pending++;
+  handle->stream.conn.write_reqs_pending++;
+
+  return 0;
+}
+
+
+int uv_pipe_write(uv_loop_t* loop,
+                  uv_write_t* req,
+                  uv_pipe_t* handle,
+                  const uv_buf_t bufs[],
+                  unsigned int nbufs,
+                  uv_write_cb cb) {
+  return uv_pipe_write_impl(loop, req, handle, bufs, nbufs, NULL, cb);
+}
+
+
+int uv_pipe_write2(uv_loop_t* loop,
+                   uv_write_t* req,
+                   uv_pipe_t* handle,
+                   const uv_buf_t bufs[],
+                   unsigned int nbufs,
+                   uv_stream_t* send_handle,
+                   uv_write_cb cb) {
+  if (!handle->ipc) {
+    return WSAEINVAL;
+  }
+
+  return uv_pipe_write_impl(loop, req, handle, bufs, nbufs, send_handle, cb);
+}
+
+
+static void uv_pipe_read_eof(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_buf_t buf) {
+  /* If there is an eof timer running, we don't need it any more, */
+  /* so discard it. */
+  eof_timer_destroy(handle);
+
+  handle->flags &= ~UV_HANDLE_READABLE;
+  uv_read_stop((uv_stream_t*) handle);
+
+  handle->read_cb((uv_stream_t*) handle, UV_EOF, &buf);
+}
+
+
+static void uv_pipe_read_error(uv_loop_t* loop, uv_pipe_t* handle, int error,
+    uv_buf_t buf) {
+  /* If there is an eof timer running, we don't need it any more, */
+  /* so discard it. */
+  eof_timer_destroy(handle);
+
+  uv_read_stop((uv_stream_t*) handle);
+
+  handle->read_cb((uv_stream_t*)handle, uv_translate_sys_error(error), &buf);
+}
+
+
+static void uv_pipe_read_error_or_eof(uv_loop_t* loop, uv_pipe_t* handle,
+    int error, uv_buf_t buf) {
+  if (error == ERROR_BROKEN_PIPE) {
+    uv_pipe_read_eof(loop, handle, buf);
+  } else {
+    uv_pipe_read_error(loop, handle, error, buf);
+  }
+}
+
+
+void uv__pipe_insert_pending_socket(uv_pipe_t* handle,
+                                    uv__ipc_socket_info_ex* info,
+                                    int tcp_connection) {
+  uv__ipc_queue_item_t* item;
+
+  item = (uv__ipc_queue_item_t*) uv__malloc(sizeof(*item));
+  if (item == NULL)
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+
+  memcpy(&item->socket_info_ex, info, sizeof(item->socket_info_ex));
+  item->tcp_connection = tcp_connection;
+  QUEUE_INSERT_TAIL(&handle->pipe.conn.pending_ipc_info.queue, &item->member);
+  handle->pipe.conn.pending_ipc_info.queue_len++;
+}
+
+
+void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_req_t* req) {
+  DWORD bytes, avail;
+  uv_buf_t buf;
+  uv_ipc_frame_uv_stream ipc_frame;
+
+  assert(handle->type == UV_NAMED_PIPE);
+
+  handle->flags &= ~UV_HANDLE_READ_PENDING;
+  eof_timer_stop(handle);
+
+  if (!REQ_SUCCESS(req)) {
+    /* An error occurred doing the 0-read. */
+    if (handle->flags & UV_HANDLE_READING) {
+      uv_pipe_read_error_or_eof(loop,
+                                handle,
+                                GET_REQ_ERROR(req),
+                                uv_null_buf_);
+    }
+  } else {
+    /* Do non-blocking reads until the buffer is empty */
+    while (handle->flags & UV_HANDLE_READING) {
+      if (!PeekNamedPipe(handle->handle,
+                          NULL,
+                          0,
+                          NULL,
+                          &avail,
+                          NULL)) {
+        uv_pipe_read_error_or_eof(loop, handle, GetLastError(), uv_null_buf_);
+        break;
+      }
+
+      if (avail == 0) {
+        /* There is nothing to read after all. */
+        break;
+      }
+
+      if (handle->ipc) {
+        /* Use the IPC framing protocol to read the incoming data. */
+        if (handle->pipe.conn.remaining_ipc_rawdata_bytes == 0) {
+          /* We're reading a new frame.  First, read the header. */
+          assert(avail >= sizeof(ipc_frame.header));
+
+          if (!ReadFile(handle->handle,
+                        &ipc_frame.header,
+                        sizeof(ipc_frame.header),
+                        &bytes,
+                        NULL)) {
+            uv_pipe_read_error_or_eof(loop, handle, GetLastError(),
+              uv_null_buf_);
+            break;
+          }
+
+          assert(bytes == sizeof(ipc_frame.header));
+          assert(ipc_frame.header.flags <= (UV_IPC_TCP_SERVER | UV_IPC_RAW_DATA |
+            UV_IPC_TCP_CONNECTION));
+
+          if (ipc_frame.header.flags & UV_IPC_TCP_SERVER) {
+            assert(avail - sizeof(ipc_frame.header) >=
+              sizeof(ipc_frame.socket_info_ex));
+
+            /* Read the TCP socket info. */
+            if (!ReadFile(handle->handle,
+                          &ipc_frame.socket_info_ex,
+                          sizeof(ipc_frame) - sizeof(ipc_frame.header),
+                          &bytes,
+                          NULL)) {
+              uv_pipe_read_error_or_eof(loop, handle, GetLastError(),
+                uv_null_buf_);
+              break;
+            }
+
+            assert(bytes == sizeof(ipc_frame) - sizeof(ipc_frame.header));
+
+            /* Store the pending socket info. */
+            uv__pipe_insert_pending_socket(
+                handle,
+                &ipc_frame.socket_info_ex,
+                ipc_frame.header.flags & UV_IPC_TCP_CONNECTION);
+          }
+
+          if (ipc_frame.header.flags & UV_IPC_RAW_DATA) {
+            handle->pipe.conn.remaining_ipc_rawdata_bytes =
+              ipc_frame.header.raw_data_length;
+            continue;
+          }
+        } else {
+          avail = min(avail, (DWORD)handle->pipe.conn.remaining_ipc_rawdata_bytes);
+        }
+      }
+
+      buf = uv_buf_init(NULL, 0);
+      handle->alloc_cb((uv_handle_t*) handle, avail, &buf);
+      if (buf.base == NULL || buf.len == 0) {
+        handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &buf);
+        break;
+      }
+      assert(buf.base != NULL);
+
+      if (ReadFile(handle->handle,
+                   buf.base,
+                   min(buf.len, avail),
+                   &bytes,
+                   NULL)) {
+        /* Successful read */
+        if (handle->ipc) {
+          assert(handle->pipe.conn.remaining_ipc_rawdata_bytes >= bytes);
+          handle->pipe.conn.remaining_ipc_rawdata_bytes =
+            handle->pipe.conn.remaining_ipc_rawdata_bytes - bytes;
+        }
+        handle->read_cb((uv_stream_t*)handle, bytes, &buf);
+
+        /* Read again only if bytes == buf.len */
+        if (bytes <= buf.len) {
+          break;
+        }
+      } else {
+        uv_pipe_read_error_or_eof(loop, handle, GetLastError(), buf);
+        break;
+      }
+    }
+
+    /* Post another 0-read if still reading and not closing. */
+    if ((handle->flags & UV_HANDLE_READING) &&
+        !(handle->flags & UV_HANDLE_READ_PENDING)) {
+      uv_pipe_queue_read(loop, handle);
+    }
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_write_t* req) {
+  int err;
+
+  assert(handle->type == UV_NAMED_PIPE);
+
+  assert(handle->write_queue_size >= req->u.io.queued_bytes);
+  handle->write_queue_size -= req->u.io.queued_bytes;
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+    if (req->wait_handle != INVALID_HANDLE_VALUE) {
+      UnregisterWait(req->wait_handle);
+      req->wait_handle = INVALID_HANDLE_VALUE;
+    }
+    if (req->event_handle) {
+      CloseHandle(req->event_handle);
+      req->event_handle = NULL;
+    }
+  }
+
+  if (req->ipc_header) {
+    if (req == &handle->pipe.conn.ipc_header_write_req) {
+      req->type = UV_UNKNOWN_REQ;
+    } else {
+      uv__free(req);
+    }
+  } else {
+    if (req->cb) {
+      err = GET_REQ_ERROR(req);
+      req->cb(req, uv_translate_sys_error(err));
+    }
+  }
+
+  handle->stream.conn.write_reqs_pending--;
+
+  if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE &&
+      handle->pipe.conn.non_overlapped_writes_tail) {
+    assert(handle->stream.conn.write_reqs_pending > 0);
+    uv_queue_non_overlapped_write(handle);
+  }
+
+  if (handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_pipe_accept_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_req_t* raw_req) {
+  uv_pipe_accept_t* req = (uv_pipe_accept_t*) raw_req;
+
+  assert(handle->type == UV_NAMED_PIPE);
+
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    /* The req->pipeHandle should be freed already in uv_pipe_cleanup(). */
+    assert(req->pipeHandle == INVALID_HANDLE_VALUE);
+    DECREASE_PENDING_REQ_COUNT(handle);
+    return;
+  }
+
+  if (REQ_SUCCESS(req)) {
+    assert(req->pipeHandle != INVALID_HANDLE_VALUE);
+    req->next_pending = handle->pipe.serv.pending_accepts;
+    handle->pipe.serv.pending_accepts = req;
+
+    if (handle->stream.serv.connection_cb) {
+      handle->stream.serv.connection_cb((uv_stream_t*)handle, 0);
+    }
+  } else {
+    if (req->pipeHandle != INVALID_HANDLE_VALUE) {
+      CloseHandle(req->pipeHandle);
+      req->pipeHandle = INVALID_HANDLE_VALUE;
+    }
+    if (!(handle->flags & UV__HANDLE_CLOSING)) {
+      uv_pipe_queue_accept(loop, handle, req, FALSE);
+    }
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_pipe_connect_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_connect_t* req) {
+  int err;
+
+  assert(handle->type == UV_NAMED_PIPE);
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (req->cb) {
+    err = 0;
+    if (REQ_SUCCESS(req)) {
+      uv_pipe_connection_init(handle);
+    } else {
+      err = GET_REQ_ERROR(req);
+    }
+    req->cb(req, uv_translate_sys_error(err));
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_pipe_shutdown_req(uv_loop_t* loop, uv_pipe_t* handle,
+    uv_shutdown_t* req) {
+  assert(handle->type == UV_NAMED_PIPE);
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (handle->flags & UV_HANDLE_READABLE) {
+    /* Initialize and optionally start the eof timer. Only do this if the */
+    /* pipe is readable and we haven't seen EOF come in ourselves. */
+    eof_timer_init(handle);
+
+    /* If reading start the timer right now. */
+    /* Otherwise uv_pipe_queue_read will start it. */
+    if (handle->flags & UV_HANDLE_READ_PENDING) {
+      eof_timer_start(handle);
+    }
+
+  } else {
+    /* This pipe is not readable. We can just close it to let the other end */
+    /* know that we're done writing. */
+    close_pipe(handle);
+  }
+
+  if (req->cb) {
+    req->cb(req, 0);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+static void eof_timer_init(uv_pipe_t* pipe) {
+  int r;
+
+  assert(pipe->pipe.conn.eof_timer == NULL);
+  assert(pipe->flags & UV_HANDLE_CONNECTION);
+
+  pipe->pipe.conn.eof_timer = (uv_timer_t*) uv__malloc(sizeof *pipe->pipe.conn.eof_timer);
+
+  r = uv_timer_init(pipe->loop, pipe->pipe.conn.eof_timer);
+  assert(r == 0); /* timers can't fail */
+  pipe->pipe.conn.eof_timer->data = pipe;
+  uv_unref((uv_handle_t*) pipe->pipe.conn.eof_timer);
+}
+
+
+static void eof_timer_start(uv_pipe_t* pipe) {
+  assert(pipe->flags & UV_HANDLE_CONNECTION);
+
+  if (pipe->pipe.conn.eof_timer != NULL) {
+    uv_timer_start(pipe->pipe.conn.eof_timer, eof_timer_cb, eof_timeout, 0);
+  }
+}
+
+
+static void eof_timer_stop(uv_pipe_t* pipe) {
+  assert(pipe->flags & UV_HANDLE_CONNECTION);
+
+  if (pipe->pipe.conn.eof_timer != NULL) {
+    uv_timer_stop(pipe->pipe.conn.eof_timer);
+  }
+}
+
+
+static void eof_timer_cb(uv_timer_t* timer) {
+  uv_pipe_t* pipe = (uv_pipe_t*) timer->data;
+  uv_loop_t* loop = timer->loop;
+
+  assert(pipe->type == UV_NAMED_PIPE);
+
+  /* This should always be true, since we start the timer only */
+  /* in uv_pipe_queue_read after successfully calling ReadFile, */
+  /* or in uv_process_pipe_shutdown_req if a read is pending, */
+  /* and we always immediately stop the timer in */
+  /* uv_process_pipe_read_req. */
+  assert(pipe->flags & UV_HANDLE_READ_PENDING);
+
+  /* If there are many packets coming off the iocp then the timer callback */
+  /* may be called before the read request is coming off the queue. */
+  /* Therefore we check here if the read request has completed but will */
+  /* be processed later. */
+  if ((pipe->flags & UV_HANDLE_READ_PENDING) &&
+      HasOverlappedIoCompleted(&pipe->read_req.u.io.overlapped)) {
+    return;
+  }
+
+  /* Force both ends off the pipe. */
+  close_pipe(pipe);
+
+  /* Stop reading, so the pending read that is going to fail will */
+  /* not be reported to the user. */
+  uv_read_stop((uv_stream_t*) pipe);
+
+  /* Report the eof and update flags. This will get reported even if the */
+  /* user stopped reading in the meantime. TODO: is that okay? */
+  uv_pipe_read_eof(loop, pipe, uv_null_buf_);
+}
+
+
+static void eof_timer_destroy(uv_pipe_t* pipe) {
+  assert(pipe->flags & UV_HANDLE_CONNECTION);
+
+  if (pipe->pipe.conn.eof_timer) {
+    uv_close((uv_handle_t*) pipe->pipe.conn.eof_timer, eof_timer_close_cb);
+    pipe->pipe.conn.eof_timer = NULL;
+  }
+}
+
+
+static void eof_timer_close_cb(uv_handle_t* handle) {
+  assert(handle->type == UV_TIMER);
+  uv__free(handle);
+}
+
+
+int uv_pipe_open(uv_pipe_t* pipe, uv_file file) {
+  HANDLE os_handle = uv__get_osfhandle(file);
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+  FILE_ACCESS_INFORMATION access;
+  DWORD duplex_flags = 0;
+
+  if (os_handle == INVALID_HANDLE_VALUE)
+    return UV_EBADF;
+
+  /* In order to avoid closing a stdio file descriptor 0-2, duplicate the
+   * underlying OS handle and forget about the original fd.
+   * We could also opt to use the original OS handle and just never close it,
+   * but then there would be no reliable way to cancel pending read operations
+   * upon close.
+   */
+  if (file <= 2) {
+    if (!DuplicateHandle(INVALID_HANDLE_VALUE,
+                         os_handle,
+                         INVALID_HANDLE_VALUE,
+                         &os_handle,
+                         0,
+                         FALSE,
+                         DUPLICATE_SAME_ACCESS))
+      return uv_translate_sys_error(GetLastError());
+    file = -1;
+  }
+
+  /* Determine what kind of permissions we have on this handle.
+   * Cygwin opens the pipe in message mode, but we can support it,
+   * just query the access flags and set the stream flags accordingly.
+   */
+  nt_status = pNtQueryInformationFile(os_handle,
+                                      &io_status,
+                                      &access,
+                                      sizeof(access),
+                                      FileAccessInformation);
+  if (nt_status != STATUS_SUCCESS)
+    return UV_EINVAL;
+
+  if (pipe->ipc) {
+    if (!(access.AccessFlags & FILE_WRITE_DATA) ||
+        !(access.AccessFlags & FILE_READ_DATA)) {
+      return UV_EINVAL;
+    }
+  }
+
+  if (access.AccessFlags & FILE_WRITE_DATA)
+    duplex_flags |= UV_HANDLE_WRITABLE;
+  if (access.AccessFlags & FILE_READ_DATA)
+    duplex_flags |= UV_HANDLE_READABLE;
+
+  if (os_handle == INVALID_HANDLE_VALUE ||
+      uv_set_pipe_handle(pipe->loop,
+                         pipe,
+                         os_handle,
+                         file,
+                         duplex_flags) == -1) {
+    return UV_EINVAL;
+  }
+
+  uv_pipe_connection_init(pipe);
+
+  if (pipe->ipc) {
+    assert(!(pipe->flags & UV_HANDLE_NON_OVERLAPPED_PIPE));
+    pipe->pipe.conn.ipc_pid = uv_parent_pid();
+    assert(pipe->pipe.conn.ipc_pid != -1);
+  }
+  return 0;
+}
+
+
+static int uv__pipe_getname(const uv_pipe_t* handle, char* buffer, size_t* size) {
+  NTSTATUS nt_status;
+  IO_STATUS_BLOCK io_status;
+  FILE_NAME_INFORMATION tmp_name_info;
+  FILE_NAME_INFORMATION* name_info;
+  WCHAR* name_buf;
+  unsigned int addrlen;
+  unsigned int name_size;
+  unsigned int name_len;
+  int err;
+
+  name_info = NULL;
+
+  if (handle->handle == INVALID_HANDLE_VALUE) {
+    *size = 0;
+    return UV_EINVAL;
+  }
+
+  uv__pipe_pause_read((uv_pipe_t*)handle); /* cast away const warning */
+
+  nt_status = pNtQueryInformationFile(handle->handle,
+                                      &io_status,
+                                      &tmp_name_info,
+                                      sizeof tmp_name_info,
+                                      FileNameInformation);
+  if (nt_status == STATUS_BUFFER_OVERFLOW) {
+    name_size = sizeof(*name_info) + tmp_name_info.FileNameLength;
+    name_info = uv__malloc(name_size);
+    if (!name_info) {
+      *size = 0;
+      err = UV_ENOMEM;
+      goto cleanup;
+    }
+
+    nt_status = pNtQueryInformationFile(handle->handle,
+                                        &io_status,
+                                        name_info,
+                                        name_size,
+                                        FileNameInformation);
+  }
+
+  if (nt_status != STATUS_SUCCESS) {
+    *size = 0;
+    err = uv_translate_sys_error(pRtlNtStatusToDosError(nt_status));
+    goto error;
+  }
+
+  if (!name_info) {
+    /* the struct on stack was used */
+    name_buf = tmp_name_info.FileName;
+    name_len = tmp_name_info.FileNameLength;
+  } else {
+    name_buf = name_info->FileName;
+    name_len = name_info->FileNameLength;
+  }
+
+  if (name_len == 0) {
+    *size = 0;
+    err = 0;
+    goto error;
+  }
+
+  name_len /= sizeof(WCHAR);
+
+  /* check how much space we need */
+  addrlen = WideCharToMultiByte(CP_UTF8,
+                                0,
+                                name_buf,
+                                name_len,
+                                NULL,
+                                0,
+                                NULL,
+                                NULL);
+  if (!addrlen) {
+    *size = 0;
+    err = uv_translate_sys_error(GetLastError());
+    goto error;
+  } else if (pipe_prefix_len + addrlen >= *size) {
+    /* "\\\\.\\pipe" + name */
+    *size = pipe_prefix_len + addrlen + 1;
+    err = UV_ENOBUFS;
+    goto error;
+  }
+
+  memcpy(buffer, pipe_prefix, pipe_prefix_len);
+  addrlen = WideCharToMultiByte(CP_UTF8,
+                                0,
+                                name_buf,
+                                name_len,
+                                buffer+pipe_prefix_len,
+                                *size-pipe_prefix_len,
+                                NULL,
+                                NULL);
+  if (!addrlen) {
+    *size = 0;
+    err = uv_translate_sys_error(GetLastError());
+    goto error;
+  }
+
+  addrlen += pipe_prefix_len;
+  *size = addrlen;
+  buffer[addrlen] = '\0';
+
+  err = 0;
+  goto cleanup;
+
+error:
+  uv__free(name_info);
+
+cleanup:
+  uv__pipe_unpause_read((uv_pipe_t*)handle); /* cast away const warning */
+  return err;
+}
+
+
+int uv_pipe_pending_count(uv_pipe_t* handle) {
+  if (!handle->ipc)
+    return 0;
+  return handle->pipe.conn.pending_ipc_info.queue_len;
+}
+
+
+int uv_pipe_getsockname(const uv_pipe_t* handle, char* buffer, size_t* size) {
+  if (handle->flags & UV_HANDLE_BOUND)
+    return uv__pipe_getname(handle, buffer, size);
+
+  if (handle->flags & UV_HANDLE_CONNECTION ||
+      handle->handle != INVALID_HANDLE_VALUE) {
+    *size = 0;
+    return 0;
+  }
+
+  return UV_EBADF;
+}
+
+
+int uv_pipe_getpeername(const uv_pipe_t* handle, char* buffer, size_t* size) {
+  /* emulate unix behaviour */
+  if (handle->flags & UV_HANDLE_BOUND)
+    return UV_ENOTCONN;
+
+  if (handle->handle != INVALID_HANDLE_VALUE)
+    return uv__pipe_getname(handle, buffer, size);
+
+  return UV_EBADF;
+}
+
+
+uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle) {
+  if (!handle->ipc)
+    return UV_UNKNOWN_HANDLE;
+  if (handle->pipe.conn.pending_ipc_info.queue_len == 0)
+    return UV_UNKNOWN_HANDLE;
+  else
+    return UV_TCP;
+}
diff --git a/Utilities/cmlibuv/src/win/poll.c b/Utilities/cmlibuv/src/win/poll.c
new file mode 100644
index 0000000..d479e52
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/poll.c
@@ -0,0 +1,646 @@
+/* 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 <assert.h>
+#include <io.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+static const GUID uv_msafd_provider_ids[UV_MSAFD_PROVIDER_COUNT] = {
+  {0xe70f1aa0, 0xab8b, 0x11cf,
+      {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
+  {0xf9eab0c0, 0x26d4, 0x11d0,
+      {0xbb, 0xbf, 0x00, 0xaa, 0x00, 0x6c, 0x34, 0xe4}},
+  {0x9fc48064, 0x7298, 0x43e4,
+      {0xb7, 0xbd, 0x18, 0x1f, 0x20, 0x89, 0x79, 0x2a}}
+};
+
+typedef struct uv_single_fd_set_s {
+  unsigned int fd_count;
+  SOCKET fd_array[1];
+} uv_single_fd_set_t;
+
+
+static OVERLAPPED overlapped_dummy_;
+static uv_once_t overlapped_dummy_init_guard_ = UV_ONCE_INIT;
+
+static AFD_POLL_INFO afd_poll_info_dummy_;
+
+
+static void uv__init_overlapped_dummy(void) {
+  HANDLE event;
+
+  event = CreateEvent(NULL, TRUE, TRUE, NULL);
+  if (event == NULL)
+    uv_fatal_error(GetLastError(), "CreateEvent");
+
+  memset(&overlapped_dummy_, 0, sizeof overlapped_dummy_);
+  overlapped_dummy_.hEvent = (HANDLE) ((uintptr_t) event | 1);
+}
+
+
+static OVERLAPPED* uv__get_overlapped_dummy() {
+  uv_once(&overlapped_dummy_init_guard_, uv__init_overlapped_dummy);
+  return &overlapped_dummy_;
+}
+
+
+static AFD_POLL_INFO* uv__get_afd_poll_info_dummy() {
+  return &afd_poll_info_dummy_;
+}
+
+
+static void uv__fast_poll_submit_poll_req(uv_loop_t* loop, uv_poll_t* handle) {
+  uv_req_t* req;
+  AFD_POLL_INFO* afd_poll_info;
+  DWORD result;
+
+  /* Find a yet unsubmitted req to submit. */
+  if (handle->submitted_events_1 == 0) {
+    req = &handle->poll_req_1;
+    afd_poll_info = &handle->afd_poll_info_1;
+    handle->submitted_events_1 = handle->events;
+    handle->mask_events_1 = 0;
+    handle->mask_events_2 = handle->events;
+  } else if (handle->submitted_events_2 == 0) {
+    req = &handle->poll_req_2;
+    afd_poll_info = &handle->afd_poll_info_2;
+    handle->submitted_events_2 = handle->events;
+    handle->mask_events_1 = handle->events;
+    handle->mask_events_2 = 0;
+  } else {
+    /* Just wait until there's an unsubmitted req. */
+    /* This will happen almost immediately as one of the 2 outstanding */
+    /* requests is about to return. When this happens, */
+    /* uv__fast_poll_process_poll_req will be called, and the pending */
+    /* events, if needed, will be processed in a subsequent request. */
+    return;
+  }
+
+  /* Setting Exclusive to TRUE makes the other poll request return if there */
+  /* is any. */
+  afd_poll_info->Exclusive = TRUE;
+  afd_poll_info->NumberOfHandles = 1;
+  afd_poll_info->Timeout.QuadPart = INT64_MAX;
+  afd_poll_info->Handles[0].Handle = (HANDLE) handle->socket;
+  afd_poll_info->Handles[0].Status = 0;
+  afd_poll_info->Handles[0].Events = 0;
+
+  if (handle->events & UV_READABLE) {
+    afd_poll_info->Handles[0].Events |= AFD_POLL_RECEIVE |
+        AFD_POLL_DISCONNECT | AFD_POLL_ACCEPT | AFD_POLL_ABORT;
+  } else {
+    if (handle->events & UV_DISCONNECT) {
+      afd_poll_info->Handles[0].Events |= AFD_POLL_DISCONNECT;
+    }
+  }
+  if (handle->events & UV_WRITABLE) {
+    afd_poll_info->Handles[0].Events |= AFD_POLL_SEND | AFD_POLL_CONNECT_FAIL;
+  }
+
+  memset(&req->u.io.overlapped, 0, sizeof req->u.io.overlapped);
+
+  result = uv_msafd_poll((SOCKET) handle->peer_socket,
+                         afd_poll_info,
+                         afd_poll_info,
+                         &req->u.io.overlapped);
+  if (result != 0 && WSAGetLastError() != WSA_IO_PENDING) {
+    /* Queue this req, reporting an error. */
+    SET_REQ_ERROR(req, WSAGetLastError());
+    uv_insert_pending_req(loop, req);
+  }
+}
+
+
+static int uv__fast_poll_cancel_poll_req(uv_loop_t* loop, uv_poll_t* handle) {
+  AFD_POLL_INFO afd_poll_info;
+  DWORD result;
+
+  afd_poll_info.Exclusive = TRUE;
+  afd_poll_info.NumberOfHandles = 1;
+  afd_poll_info.Timeout.QuadPart = INT64_MAX;
+  afd_poll_info.Handles[0].Handle = (HANDLE) handle->socket;
+  afd_poll_info.Handles[0].Status = 0;
+  afd_poll_info.Handles[0].Events = AFD_POLL_ALL;
+
+  result = uv_msafd_poll(handle->socket,
+                         &afd_poll_info,
+                         uv__get_afd_poll_info_dummy(),
+                         uv__get_overlapped_dummy());
+
+  if (result == SOCKET_ERROR) {
+    DWORD error = WSAGetLastError();
+    if (error != WSA_IO_PENDING)
+      return error;
+  }
+
+  return 0;
+}
+
+
+static void uv__fast_poll_process_poll_req(uv_loop_t* loop, uv_poll_t* handle,
+    uv_req_t* req) {
+  unsigned char mask_events;
+  AFD_POLL_INFO* afd_poll_info;
+
+  if (req == &handle->poll_req_1) {
+    afd_poll_info = &handle->afd_poll_info_1;
+    handle->submitted_events_1 = 0;
+    mask_events = handle->mask_events_1;
+  } else if (req == &handle->poll_req_2) {
+    afd_poll_info = &handle->afd_poll_info_2;
+    handle->submitted_events_2 = 0;
+    mask_events = handle->mask_events_2;
+  } else {
+    assert(0);
+    return;
+  }
+
+  /* Report an error unless the select was just interrupted. */
+  if (!REQ_SUCCESS(req)) {
+    DWORD error = GET_REQ_SOCK_ERROR(req);
+    if (error != WSAEINTR && handle->events != 0) {
+      handle->events = 0; /* Stop the watcher */
+      handle->poll_cb(handle, uv_translate_sys_error(error), 0);
+    }
+
+  } else if (afd_poll_info->NumberOfHandles >= 1) {
+    unsigned char events = 0;
+
+    if ((afd_poll_info->Handles[0].Events & (AFD_POLL_RECEIVE |
+        AFD_POLL_DISCONNECT | AFD_POLL_ACCEPT | AFD_POLL_ABORT)) != 0) {
+      events |= UV_READABLE;
+      if ((afd_poll_info->Handles[0].Events & AFD_POLL_DISCONNECT) != 0) {
+        events |= UV_DISCONNECT;
+      }
+    }
+    if ((afd_poll_info->Handles[0].Events & (AFD_POLL_SEND |
+        AFD_POLL_CONNECT_FAIL)) != 0) {
+      events |= UV_WRITABLE;
+    }
+
+    events &= handle->events & ~mask_events;
+
+    if (afd_poll_info->Handles[0].Events & AFD_POLL_LOCAL_CLOSE) {
+      /* Stop polling. */
+      handle->events = 0;
+      if (uv__is_active(handle))
+        uv__handle_stop(handle);
+    }
+
+    if (events != 0) {
+      handle->poll_cb(handle, 0, events);
+    }
+  }
+
+  if ((handle->events & ~(handle->submitted_events_1 |
+      handle->submitted_events_2)) != 0) {
+    uv__fast_poll_submit_poll_req(loop, handle);
+  } else if ((handle->flags & UV__HANDLE_CLOSING) &&
+             handle->submitted_events_1 == 0 &&
+             handle->submitted_events_2 == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+}
+
+
+static int uv__fast_poll_set(uv_loop_t* loop, uv_poll_t* handle, int events) {
+  assert(handle->type == UV_POLL);
+  assert(!(handle->flags & UV__HANDLE_CLOSING));
+  assert((events & ~(UV_READABLE | UV_WRITABLE | UV_DISCONNECT)) == 0);
+
+  handle->events = events;
+
+  if (handle->events != 0) {
+    uv__handle_start(handle);
+  } else {
+    uv__handle_stop(handle);
+  }
+
+  if ((handle->events & ~(handle->submitted_events_1 |
+      handle->submitted_events_2)) != 0) {
+    uv__fast_poll_submit_poll_req(handle->loop, handle);
+  }
+
+  return 0;
+}
+
+
+static int uv__fast_poll_close(uv_loop_t* loop, uv_poll_t* handle) {
+  handle->events = 0;
+  uv__handle_closing(handle);
+
+  if (handle->submitted_events_1 == 0 &&
+      handle->submitted_events_2 == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+    return 0;
+  } else {
+    /* Cancel outstanding poll requests by executing another, unique poll */
+    /* request that forces the outstanding ones to return. */
+    return uv__fast_poll_cancel_poll_req(loop, handle);
+  }
+}
+
+
+static SOCKET uv__fast_poll_create_peer_socket(HANDLE iocp,
+    WSAPROTOCOL_INFOW* protocol_info) {
+  SOCKET sock = 0;
+
+  sock = WSASocketW(protocol_info->iAddressFamily,
+                    protocol_info->iSocketType,
+                    protocol_info->iProtocol,
+                    protocol_info,
+                    0,
+                    WSA_FLAG_OVERLAPPED);
+  if (sock == INVALID_SOCKET) {
+    return INVALID_SOCKET;
+  }
+
+  if (!SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0)) {
+    goto error;
+  };
+
+  if (CreateIoCompletionPort((HANDLE) sock,
+                             iocp,
+                             (ULONG_PTR) sock,
+                             0) == NULL) {
+    goto error;
+  }
+
+  return sock;
+
+ error:
+  closesocket(sock);
+  return INVALID_SOCKET;
+}
+
+
+static SOCKET uv__fast_poll_get_peer_socket(uv_loop_t* loop,
+    WSAPROTOCOL_INFOW* protocol_info) {
+  int index, i;
+  SOCKET peer_socket;
+
+  index = -1;
+  for (i = 0; (size_t) i < ARRAY_SIZE(uv_msafd_provider_ids); i++) {
+    if (memcmp((void*) &protocol_info->ProviderId,
+               (void*) &uv_msafd_provider_ids[i],
+               sizeof protocol_info->ProviderId) == 0) {
+      index = i;
+    }
+  }
+
+  /* Check if the protocol uses an msafd socket. */
+  if (index < 0) {
+    return INVALID_SOCKET;
+  }
+
+  /* If we didn't (try) to create a peer socket yet, try to make one. Don't */
+  /* try again if the peer socket creation failed earlier for the same */
+  /* protocol. */
+  peer_socket = loop->poll_peer_sockets[index];
+  if (peer_socket == 0) {
+    peer_socket = uv__fast_poll_create_peer_socket(loop->iocp, protocol_info);
+    loop->poll_peer_sockets[index] = peer_socket;
+  }
+
+  return peer_socket;
+}
+
+
+static DWORD WINAPI uv__slow_poll_thread_proc(void* arg) {
+  uv_req_t* req = (uv_req_t*) arg;
+  uv_poll_t* handle = (uv_poll_t*) req->data;
+  unsigned char reported_events;
+  int r;
+  uv_single_fd_set_t rfds, wfds, efds;
+  struct timeval timeout;
+
+  assert(handle->type == UV_POLL);
+  assert(req->type == UV_POLL_REQ);
+
+  if (handle->events & UV_READABLE) {
+    rfds.fd_count = 1;
+    rfds.fd_array[0] = handle->socket;
+  } else {
+    rfds.fd_count = 0;
+  }
+
+  if (handle->events & UV_WRITABLE) {
+    wfds.fd_count = 1;
+    wfds.fd_array[0] = handle->socket;
+    efds.fd_count = 1;
+    efds.fd_array[0] = handle->socket;
+  } else {
+    wfds.fd_count = 0;
+    efds.fd_count = 0;
+  }
+
+  /* Make the select() time out after 3 minutes. If select() hangs because */
+  /* the user closed the socket, we will at least not hang indefinitely. */
+  timeout.tv_sec = 3 * 60;
+  timeout.tv_usec = 0;
+
+  r = select(1, (fd_set*) &rfds, (fd_set*) &wfds, (fd_set*) &efds, &timeout);
+  if (r == SOCKET_ERROR) {
+    /* Queue this req, reporting an error. */
+    SET_REQ_ERROR(&handle->poll_req_1, WSAGetLastError());
+    POST_COMPLETION_FOR_REQ(handle->loop, req);
+    return 0;
+  }
+
+  reported_events = 0;
+
+  if (r > 0) {
+    if (rfds.fd_count > 0) {
+      assert(rfds.fd_count == 1);
+      assert(rfds.fd_array[0] == handle->socket);
+      reported_events |= UV_READABLE;
+    }
+
+    if (wfds.fd_count > 0) {
+      assert(wfds.fd_count == 1);
+      assert(wfds.fd_array[0] == handle->socket);
+      reported_events |= UV_WRITABLE;
+    } else if (efds.fd_count > 0) {
+      assert(efds.fd_count == 1);
+      assert(efds.fd_array[0] == handle->socket);
+      reported_events |= UV_WRITABLE;
+    }
+  }
+
+  SET_REQ_SUCCESS(req);
+  req->u.io.overlapped.InternalHigh = (DWORD) reported_events;
+  POST_COMPLETION_FOR_REQ(handle->loop, req);
+
+  return 0;
+}
+
+
+static void uv__slow_poll_submit_poll_req(uv_loop_t* loop, uv_poll_t* handle) {
+  uv_req_t* req;
+
+  /* Find a yet unsubmitted req to submit. */
+  if (handle->submitted_events_1 == 0) {
+    req = &handle->poll_req_1;
+    handle->submitted_events_1 = handle->events;
+    handle->mask_events_1 = 0;
+    handle->mask_events_2 = handle->events;
+  } else if (handle->submitted_events_2 == 0) {
+    req = &handle->poll_req_2;
+    handle->submitted_events_2 = handle->events;
+    handle->mask_events_1 = handle->events;
+    handle->mask_events_2 = 0;
+  } else {
+    assert(0);
+    return;
+  }
+
+  if (!QueueUserWorkItem(uv__slow_poll_thread_proc,
+                         (void*) req,
+                         WT_EXECUTELONGFUNCTION)) {
+    /* Make this req pending, reporting an error. */
+    SET_REQ_ERROR(req, GetLastError());
+    uv_insert_pending_req(loop, req);
+  }
+}
+
+
+
+static void uv__slow_poll_process_poll_req(uv_loop_t* loop, uv_poll_t* handle,
+    uv_req_t* req) {
+  unsigned char mask_events;
+  int err;
+
+  if (req == &handle->poll_req_1) {
+    handle->submitted_events_1 = 0;
+    mask_events = handle->mask_events_1;
+  } else if (req == &handle->poll_req_2) {
+    handle->submitted_events_2 = 0;
+    mask_events = handle->mask_events_2;
+  } else {
+    assert(0);
+    return;
+  }
+
+  if (!REQ_SUCCESS(req)) {
+    /* Error. */
+    if (handle->events != 0) {
+      err = GET_REQ_ERROR(req);
+      handle->events = 0; /* Stop the watcher */
+      handle->poll_cb(handle, uv_translate_sys_error(err), 0);
+    }
+  } else {
+    /* Got some events. */
+    int events = req->u.io.overlapped.InternalHigh & handle->events & ~mask_events;
+    if (events != 0) {
+      handle->poll_cb(handle, 0, events);
+    }
+  }
+
+  if ((handle->events & ~(handle->submitted_events_1 |
+      handle->submitted_events_2)) != 0) {
+    uv__slow_poll_submit_poll_req(loop, handle);
+  } else if ((handle->flags & UV__HANDLE_CLOSING) &&
+             handle->submitted_events_1 == 0 &&
+             handle->submitted_events_2 == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+}
+
+
+static int uv__slow_poll_set(uv_loop_t* loop, uv_poll_t* handle, int events) {
+  assert(handle->type == UV_POLL);
+  assert(!(handle->flags & UV__HANDLE_CLOSING));
+  assert((events & ~(UV_READABLE | UV_WRITABLE)) == 0);
+
+  handle->events = events;
+
+  if (handle->events != 0) {
+    uv__handle_start(handle);
+  } else {
+    uv__handle_stop(handle);
+  }
+
+  if ((handle->events &
+      ~(handle->submitted_events_1 | handle->submitted_events_2)) != 0) {
+    uv__slow_poll_submit_poll_req(handle->loop, handle);
+  }
+
+  return 0;
+}
+
+
+static int uv__slow_poll_close(uv_loop_t* loop, uv_poll_t* handle) {
+  handle->events = 0;
+  uv__handle_closing(handle);
+
+  if (handle->submitted_events_1 == 0 &&
+      handle->submitted_events_2 == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+
+  return 0;
+}
+
+
+int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd) {
+  return uv_poll_init_socket(loop, handle, (SOCKET) uv__get_osfhandle(fd));
+}
+
+
+int uv_poll_init_socket(uv_loop_t* loop, uv_poll_t* handle,
+    uv_os_sock_t socket) {
+  WSAPROTOCOL_INFOW protocol_info;
+  int len;
+  SOCKET peer_socket, base_socket;
+  DWORD bytes;
+  DWORD yes = 1;
+
+  /* Set the socket to nonblocking mode */
+  if (ioctlsocket(socket, FIONBIO, &yes) == SOCKET_ERROR)
+    return uv_translate_sys_error(WSAGetLastError());
+
+  /* Try to obtain a base handle for the socket. This increases this chances */
+  /* that we find an AFD handle and are able to use the fast poll mechanism. */
+  /* This will always fail on windows XP/2k3, since they don't support the */
+  /* SIO_BASE_HANDLE ioctl. */
+#ifndef NDEBUG
+  base_socket = INVALID_SOCKET;
+#endif
+
+  if (WSAIoctl(socket,
+               SIO_BASE_HANDLE,
+               NULL,
+               0,
+               &base_socket,
+               sizeof base_socket,
+               &bytes,
+               NULL,
+               NULL) == 0) {
+    assert(base_socket != 0 && base_socket != INVALID_SOCKET);
+    socket = base_socket;
+  }
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_POLL);
+  handle->socket = socket;
+  handle->events = 0;
+
+  /* Obtain protocol information about the socket. */
+  len = sizeof protocol_info;
+  if (getsockopt(socket,
+                 SOL_SOCKET,
+                 SO_PROTOCOL_INFOW,
+                 (char*) &protocol_info,
+                 &len) != 0) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  /* Get the peer socket that is needed to enable fast poll. If the returned */
+  /* value is NULL, the protocol is not implemented by MSAFD and we'll have */
+  /* to use slow mode. */
+  peer_socket = uv__fast_poll_get_peer_socket(loop, &protocol_info);
+
+  if (peer_socket != INVALID_SOCKET) {
+    /* Initialize fast poll specific fields. */
+    handle->peer_socket = peer_socket;
+  } else {
+    /* Initialize slow poll specific fields. */
+    handle->flags |= UV_HANDLE_POLL_SLOW;
+  }
+
+  /* Initialize 2 poll reqs. */
+  handle->submitted_events_1 = 0;
+  uv_req_init(loop, (uv_req_t*) &(handle->poll_req_1));
+  handle->poll_req_1.type = UV_POLL_REQ;
+  handle->poll_req_1.data = handle;
+
+  handle->submitted_events_2 = 0;
+  uv_req_init(loop, (uv_req_t*) &(handle->poll_req_2));
+  handle->poll_req_2.type = UV_POLL_REQ;
+  handle->poll_req_2.data = handle;
+
+  return 0;
+}
+
+
+int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb) {
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_POLL_SLOW)) {
+    err = uv__fast_poll_set(handle->loop, handle, events);
+  } else {
+    err = uv__slow_poll_set(handle->loop, handle, events);
+  }
+
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  handle->poll_cb = cb;
+
+  return 0;
+}
+
+
+int uv_poll_stop(uv_poll_t* handle) {
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_POLL_SLOW)) {
+    err = uv__fast_poll_set(handle->loop, handle, 0);
+  } else {
+    err = uv__slow_poll_set(handle->loop, handle, 0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+void uv_process_poll_req(uv_loop_t* loop, uv_poll_t* handle, uv_req_t* req) {
+  if (!(handle->flags & UV_HANDLE_POLL_SLOW)) {
+    uv__fast_poll_process_poll_req(loop, handle, req);
+  } else {
+    uv__slow_poll_process_poll_req(loop, handle, req);
+  }
+}
+
+
+int uv_poll_close(uv_loop_t* loop, uv_poll_t* handle) {
+  if (!(handle->flags & UV_HANDLE_POLL_SLOW)) {
+    return uv__fast_poll_close(loop, handle);
+  } else {
+    return uv__slow_poll_close(loop, handle);
+  }
+}
+
+
+void uv_poll_endgame(uv_loop_t* loop, uv_poll_t* handle) {
+  assert(handle->flags & UV__HANDLE_CLOSING);
+  assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+  assert(handle->submitted_events_1 == 0);
+  assert(handle->submitted_events_2 == 0);
+
+  uv__handle_close(handle);
+}
diff --git a/Utilities/cmlibuv/src/win/process-stdio.c b/Utilities/cmlibuv/src/win/process-stdio.c
new file mode 100644
index 0000000..e3c06f5
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/process-stdio.c
@@ -0,0 +1,510 @@
+/* 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 <assert.h>
+#include <io.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+
+
+/*
+ * The `child_stdio_buffer` buffer has the following layout:
+ *   int number_of_fds
+ *   unsigned char crt_flags[number_of_fds]
+ *   HANDLE os_handle[number_of_fds]
+ */
+#define CHILD_STDIO_SIZE(count)                     \
+    (sizeof(int) +                                  \
+     sizeof(unsigned char) * (count) +              \
+     sizeof(uintptr_t) * (count))
+
+#define CHILD_STDIO_COUNT(buffer)                   \
+    *((unsigned int*) (buffer))
+
+#define CHILD_STDIO_CRT_FLAGS(buffer, fd)           \
+    *((unsigned char*) (buffer) + sizeof(int) + fd)
+
+#define CHILD_STDIO_HANDLE(buffer, fd)              \
+    *((HANDLE*) ((unsigned char*) (buffer) +        \
+                 sizeof(int) +                      \
+                 sizeof(unsigned char) *            \
+                 CHILD_STDIO_COUNT((buffer)) +      \
+                 sizeof(HANDLE) * (fd)))
+
+
+/* CRT file descriptor mode flags */
+#define FOPEN       0x01
+#define FEOFLAG     0x02
+#define FCRLF       0x04
+#define FPIPE       0x08
+#define FNOINHERIT  0x10
+#define FAPPEND     0x20
+#define FDEV        0x40
+#define FTEXT       0x80
+
+
+/*
+ * Clear the HANDLE_FLAG_INHERIT flag from all HANDLEs that were inherited
+ * the parent process. Don't check for errors - the stdio handles may not be
+ * valid, or may be closed already. There is no guarantee that this function
+ * does a perfect job.
+ */
+void uv_disable_stdio_inheritance(void) {
+  HANDLE handle;
+  STARTUPINFOW si;
+
+  /* Make the windows stdio handles non-inheritable. */
+  handle = GetStdHandle(STD_INPUT_HANDLE);
+  if (handle != NULL && handle != INVALID_HANDLE_VALUE)
+    SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
+
+  handle = GetStdHandle(STD_OUTPUT_HANDLE);
+  if (handle != NULL && handle != INVALID_HANDLE_VALUE)
+    SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
+
+  handle = GetStdHandle(STD_ERROR_HANDLE);
+  if (handle != NULL && handle != INVALID_HANDLE_VALUE)
+    SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
+
+  /* Make inherited CRT FDs non-inheritable. */
+  GetStartupInfoW(&si);
+  if (uv__stdio_verify(si.lpReserved2, si.cbReserved2))
+    uv__stdio_noinherit(si.lpReserved2);
+}
+
+
+static int uv__create_stdio_pipe_pair(uv_loop_t* loop,
+    uv_pipe_t* server_pipe, HANDLE* child_pipe_ptr, unsigned int flags) {
+  char pipe_name[64];
+  SECURITY_ATTRIBUTES sa;
+  DWORD server_access = 0;
+  DWORD client_access = 0;
+  HANDLE child_pipe = INVALID_HANDLE_VALUE;
+  int err;
+
+  if (flags & UV_READABLE_PIPE) {
+    /* The server needs inbound access too, otherwise CreateNamedPipe() */
+    /* won't give us the FILE_READ_ATTRIBUTES permission. We need that to */
+    /* probe the state of the write buffer when we're trying to shutdown */
+    /* the pipe. */
+    server_access |= PIPE_ACCESS_OUTBOUND | PIPE_ACCESS_INBOUND;
+    client_access |= GENERIC_READ | FILE_WRITE_ATTRIBUTES;
+  }
+  if (flags & UV_WRITABLE_PIPE) {
+    server_access |= PIPE_ACCESS_INBOUND;
+    client_access |= GENERIC_WRITE | FILE_READ_ATTRIBUTES;
+  }
+
+  /* Create server pipe handle. */
+  err = uv_stdio_pipe_server(loop,
+                             server_pipe,
+                             server_access,
+                             pipe_name,
+                             sizeof(pipe_name));
+  if (err)
+    goto error;
+
+  /* Create child pipe handle. */
+  sa.nLength = sizeof sa;
+  sa.lpSecurityDescriptor = NULL;
+  sa.bInheritHandle = TRUE;
+
+  child_pipe = CreateFileA(pipe_name,
+                           client_access,
+                           0,
+                           &sa,
+                           OPEN_EXISTING,
+                           server_pipe->ipc ? FILE_FLAG_OVERLAPPED : 0,
+                           NULL);
+  if (child_pipe == INVALID_HANDLE_VALUE) {
+    err = GetLastError();
+    goto error;
+  }
+
+#ifndef NDEBUG
+  /* Validate that the pipe was opened in the right mode. */
+  {
+    DWORD mode;
+    BOOL r = GetNamedPipeHandleState(child_pipe,
+                                     &mode,
+                                     NULL,
+                                     NULL,
+                                     NULL,
+                                     NULL,
+                                     0);
+    assert(r == TRUE);
+    assert(mode == (PIPE_READMODE_BYTE | PIPE_WAIT));
+  }
+#endif
+
+  /* Do a blocking ConnectNamedPipe.  This should not block because we have */
+  /* both ends of the pipe created. */
+  if (!ConnectNamedPipe(server_pipe->handle, NULL)) {
+    if (GetLastError() != ERROR_PIPE_CONNECTED) {
+      err = GetLastError();
+      goto error;
+    }
+  }
+
+  /* The server end is now readable and/or writable. */
+  if (flags & UV_READABLE_PIPE)
+    server_pipe->flags |= UV_HANDLE_WRITABLE;
+  if (flags & UV_WRITABLE_PIPE)
+    server_pipe->flags |= UV_HANDLE_READABLE;
+
+  *child_pipe_ptr = child_pipe;
+  return 0;
+
+ error:
+  if (server_pipe->handle != INVALID_HANDLE_VALUE) {
+    uv_pipe_cleanup(loop, server_pipe);
+  }
+
+  if (child_pipe != INVALID_HANDLE_VALUE) {
+    CloseHandle(child_pipe);
+  }
+
+  return err;
+}
+
+
+static int uv__duplicate_handle(uv_loop_t* loop, HANDLE handle, HANDLE* dup) {
+  HANDLE current_process;
+
+
+  /* _get_osfhandle will sometimes return -2 in case of an error. This seems */
+  /* to happen when fd <= 2 and the process' corresponding stdio handle is */
+  /* set to NULL. Unfortunately DuplicateHandle will happily duplicate */
+  /* (HANDLE) -2, so this situation goes unnoticed until someone tries to */
+  /* use the duplicate. Therefore we filter out known-invalid handles here. */
+  if (handle == INVALID_HANDLE_VALUE ||
+      handle == NULL ||
+      handle == (HANDLE) -2) {
+    *dup = INVALID_HANDLE_VALUE;
+    return ERROR_INVALID_HANDLE;
+  }
+
+  current_process = GetCurrentProcess();
+
+  if (!DuplicateHandle(current_process,
+                       handle,
+                       current_process,
+                       dup,
+                       0,
+                       TRUE,
+                       DUPLICATE_SAME_ACCESS)) {
+    *dup = INVALID_HANDLE_VALUE;
+    return GetLastError();
+  }
+
+  return 0;
+}
+
+
+static int uv__duplicate_fd(uv_loop_t* loop, int fd, HANDLE* dup) {
+  HANDLE handle;
+
+  if (fd == -1) {
+    *dup = INVALID_HANDLE_VALUE;
+    return ERROR_INVALID_HANDLE;
+  }
+
+  handle = uv__get_osfhandle(fd);
+  return uv__duplicate_handle(loop, handle, dup);
+}
+
+
+int uv__create_nul_handle(HANDLE* handle_ptr,
+    DWORD access) {
+  HANDLE handle;
+  SECURITY_ATTRIBUTES sa;
+
+  sa.nLength = sizeof sa;
+  sa.lpSecurityDescriptor = NULL;
+  sa.bInheritHandle = TRUE;
+
+  handle = CreateFileW(L"NUL",
+                       access,
+                       FILE_SHARE_READ | FILE_SHARE_WRITE,
+                       &sa,
+                       OPEN_EXISTING,
+                       0,
+                       NULL);
+  if (handle == INVALID_HANDLE_VALUE) {
+    return GetLastError();
+  }
+
+  *handle_ptr = handle;
+  return 0;
+}
+
+
+int uv__stdio_create(uv_loop_t* loop,
+                     const uv_process_options_t* options,
+                     BYTE** buffer_ptr) {
+  BYTE* buffer;
+  int count, i;
+  int err;
+
+  count = options->stdio_count;
+
+  if (count < 0 || count > 255) {
+    /* Only support FDs 0-255 */
+    return ERROR_NOT_SUPPORTED;
+  } else if (count < 3) {
+    /* There should always be at least 3 stdio handles. */
+    count = 3;
+  }
+
+  /* Allocate the child stdio buffer */
+  buffer = (BYTE*) uv__malloc(CHILD_STDIO_SIZE(count));
+  if (buffer == NULL) {
+    return ERROR_OUTOFMEMORY;
+  }
+
+  /* Prepopulate the buffer with INVALID_HANDLE_VALUE handles so we can */
+  /* clean up on failure. */
+  CHILD_STDIO_COUNT(buffer) = count;
+  for (i = 0; i < count; i++) {
+    CHILD_STDIO_CRT_FLAGS(buffer, i) = 0;
+    CHILD_STDIO_HANDLE(buffer, i) = INVALID_HANDLE_VALUE;
+  }
+
+  for (i = 0; i < count; i++) {
+    uv_stdio_container_t fdopt;
+    if (i < options->stdio_count) {
+      fdopt = options->stdio[i];
+    } else {
+      fdopt.flags = UV_IGNORE;
+    }
+
+    switch (fdopt.flags & (UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD |
+            UV_INHERIT_STREAM)) {
+      case UV_IGNORE:
+        /* Starting a process with no stdin/stout/stderr can confuse it. */
+        /* So no matter what the user specified, we make sure the first */
+        /* three FDs are always open in their typical modes, e.g. stdin */
+        /* be readable and stdout/err should be writable. For FDs > 2, don't */
+        /* do anything - all handles in the stdio buffer are initialized with */
+        /* INVALID_HANDLE_VALUE, which should be okay. */
+        if (i <= 2) {
+          DWORD access = (i == 0) ? FILE_GENERIC_READ :
+                                    FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES;
+
+          err = uv__create_nul_handle(&CHILD_STDIO_HANDLE(buffer, i),
+                                      access);
+          if (err)
+            goto error;
+
+          CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
+        }
+        break;
+
+      case UV_CREATE_PIPE: {
+        /* Create a pair of two connected pipe ends; one end is turned into */
+        /* an uv_pipe_t for use by the parent. The other one is given to */
+        /* the child. */
+        uv_pipe_t* parent_pipe = (uv_pipe_t*) fdopt.data.stream;
+        HANDLE child_pipe = INVALID_HANDLE_VALUE;
+
+        /* Create a new, connected pipe pair. stdio[i].stream should point */
+        /* to an uninitialized, but not connected pipe handle. */
+        assert(fdopt.data.stream->type == UV_NAMED_PIPE);
+        assert(!(fdopt.data.stream->flags & UV_HANDLE_CONNECTION));
+        assert(!(fdopt.data.stream->flags & UV_HANDLE_PIPESERVER));
+
+        err = uv__create_stdio_pipe_pair(loop,
+                                         parent_pipe,
+                                         &child_pipe,
+                                         fdopt.flags);
+        if (err)
+          goto error;
+
+        CHILD_STDIO_HANDLE(buffer, i) = child_pipe;
+        CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FPIPE;
+        break;
+      }
+
+      case UV_INHERIT_FD: {
+        /* Inherit a raw FD. */
+        HANDLE child_handle;
+
+        /* Make an inheritable duplicate of the handle. */
+        err = uv__duplicate_fd(loop, fdopt.data.fd, &child_handle);
+        if (err) {
+          /* If fdopt.data.fd is not valid and fd fd <= 2, then ignore the */
+          /* error. */
+          if (fdopt.data.fd <= 2 && err == ERROR_INVALID_HANDLE) {
+            CHILD_STDIO_CRT_FLAGS(buffer, i) = 0;
+            CHILD_STDIO_HANDLE(buffer, i) = INVALID_HANDLE_VALUE;
+            break;
+          }
+          goto error;
+        }
+
+        /* Figure out what the type is. */
+        switch (GetFileType(child_handle)) {
+          case FILE_TYPE_DISK:
+            CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN;
+            break;
+
+          case FILE_TYPE_PIPE:
+            CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FPIPE;
+
+          case FILE_TYPE_CHAR:
+          case FILE_TYPE_REMOTE:
+            CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
+            break;
+
+          case FILE_TYPE_UNKNOWN:
+            if (GetLastError() != 0) {
+              err = GetLastError();
+              CloseHandle(child_handle);
+              goto error;
+            }
+            CHILD_STDIO_CRT_FLAGS(buffer, i) = FOPEN | FDEV;
+            break;
+
+          default:
+            assert(0);
+            return -1;
+        }
+
+        CHILD_STDIO_HANDLE(buffer, i) = child_handle;
+        break;
+      }
+
+      case UV_INHERIT_STREAM: {
+        /* Use an existing stream as the stdio handle for the child. */
+        HANDLE stream_handle, child_handle;
+        unsigned char crt_flags;
+        uv_stream_t* stream = fdopt.data.stream;
+
+        /* Leech the handle out of the stream. */
+        if (stream->type == UV_TTY) {
+          stream_handle = ((uv_tty_t*) stream)->handle;
+          crt_flags = FOPEN | FDEV;
+        } else if (stream->type == UV_NAMED_PIPE &&
+                   stream->flags & UV_HANDLE_CONNECTION) {
+          stream_handle = ((uv_pipe_t*) stream)->handle;
+          crt_flags = FOPEN | FPIPE;
+        } else {
+          stream_handle = INVALID_HANDLE_VALUE;
+          crt_flags = 0;
+        }
+
+        if (stream_handle == NULL ||
+            stream_handle == INVALID_HANDLE_VALUE) {
+          /* The handle is already closed, or not yet created, or the */
+          /* stream type is not supported. */
+          err = ERROR_NOT_SUPPORTED;
+          goto error;
+        }
+
+        /* Make an inheritable copy of the handle. */
+        err = uv__duplicate_handle(loop, stream_handle, &child_handle);
+        if (err)
+          goto error;
+
+        CHILD_STDIO_HANDLE(buffer, i) = child_handle;
+        CHILD_STDIO_CRT_FLAGS(buffer, i) = crt_flags;
+        break;
+      }
+
+      default:
+        assert(0);
+        return -1;
+    }
+  }
+
+  *buffer_ptr  = buffer;
+  return 0;
+
+ error:
+  uv__stdio_destroy(buffer);
+  return err;
+}
+
+
+void uv__stdio_destroy(BYTE* buffer) {
+  int i, count;
+
+  count = CHILD_STDIO_COUNT(buffer);
+  for (i = 0; i < count; i++) {
+    HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
+    if (handle != INVALID_HANDLE_VALUE) {
+      CloseHandle(handle);
+    }
+  }
+
+  uv__free(buffer);
+}
+
+
+void uv__stdio_noinherit(BYTE* buffer) {
+  int i, count;
+
+  count = CHILD_STDIO_COUNT(buffer);
+  for (i = 0; i < count; i++) {
+    HANDLE handle = CHILD_STDIO_HANDLE(buffer, i);
+    if (handle != INVALID_HANDLE_VALUE) {
+      SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
+    }
+  }
+}
+
+
+int uv__stdio_verify(BYTE* buffer, WORD size) {
+  unsigned int count;
+
+  /* Check the buffer pointer. */
+  if (buffer == NULL)
+    return 0;
+
+  /* Verify that the buffer is at least big enough to hold the count. */
+  if (size < CHILD_STDIO_SIZE(0))
+    return 0;
+
+  /* Verify if the count is within range. */
+  count = CHILD_STDIO_COUNT(buffer);
+  if (count > 256)
+    return 0;
+
+  /* Verify that the buffer size is big enough to hold info for N FDs. */
+  if (size < CHILD_STDIO_SIZE(count))
+    return 0;
+
+  return 1;
+}
+
+
+WORD uv__stdio_size(BYTE* buffer) {
+  return (WORD) CHILD_STDIO_SIZE(CHILD_STDIO_COUNT((buffer)));
+}
+
+
+HANDLE uv__stdio_handle(BYTE* buffer, int fd) {
+  return CHILD_STDIO_HANDLE(buffer, fd);
+}
diff --git a/Utilities/cmlibuv/src/win/process.c b/Utilities/cmlibuv/src/win/process.c
new file mode 100644
index 0000000..855c374
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/process.c
@@ -0,0 +1,1247 @@
+/* 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 <assert.h>
+#include <io.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <limits.h>
+#include <wchar.h>
+#include <malloc.h>    /* alloca */
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+#define SIGKILL         9
+
+
+typedef struct env_var {
+  const WCHAR* const wide;
+  const WCHAR* const wide_eq;
+  const size_t len; /* including null or '=' */
+} env_var_t;
+
+#define E_V(str) { L##str, L##str L"=", sizeof(str) }
+
+static const env_var_t required_vars[] = { /* keep me sorted */
+  E_V("HOMEDRIVE"),
+  E_V("HOMEPATH"),
+  E_V("LOGONSERVER"),
+  E_V("PATH"),
+  E_V("SYSTEMDRIVE"),
+  E_V("SYSTEMROOT"),
+  E_V("TEMP"),
+  E_V("USERDOMAIN"),
+  E_V("USERNAME"),
+  E_V("USERPROFILE"),
+  E_V("WINDIR"),
+};
+static size_t n_required_vars = ARRAY_SIZE(required_vars);
+
+
+static HANDLE uv_global_job_handle_;
+static uv_once_t uv_global_job_handle_init_guard_ = UV_ONCE_INIT;
+
+
+static void uv__init_global_job_handle(void) {
+  /* Create a job object and set it up to kill all contained processes when
+   * it's closed. Since this handle is made non-inheritable and we're not
+   * giving it to anyone, we're the only process holding a reference to it.
+   * That means that if this process exits it is closed and all the processes
+   * it contains are killed. All processes created with uv_spawn that are not
+   * spawned with the UV_PROCESS_DETACHED flag are assigned to this job.
+   *
+   * We're setting the JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag so only the
+   * processes that we explicitly add are affected, and *their* subprocesses
+   * are not. This ensures that our child processes are not limited in their
+   * ability to use job control on Windows versions that don't deal with
+   * nested jobs (prior to Windows 8 / Server 2012). It also lets our child
+   * processes created detached processes without explicitly breaking away
+   * from job control (which uv_spawn doesn't, either).
+   */
+  SECURITY_ATTRIBUTES attr;
+  JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
+
+  memset(&attr, 0, sizeof attr);
+  attr.bInheritHandle = FALSE;
+
+  memset(&info, 0, sizeof info);
+  info.BasicLimitInformation.LimitFlags =
+      JOB_OBJECT_LIMIT_BREAKAWAY_OK |
+      JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK |
+      JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION |
+      JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+
+  uv_global_job_handle_ = CreateJobObjectW(&attr, NULL);
+  if (uv_global_job_handle_ == NULL)
+    uv_fatal_error(GetLastError(), "CreateJobObjectW");
+
+  if (!SetInformationJobObject(uv_global_job_handle_,
+                               JobObjectExtendedLimitInformation,
+                               &info,
+                               sizeof info))
+    uv_fatal_error(GetLastError(), "SetInformationJobObject");
+}
+
+
+static int uv_utf8_to_utf16_alloc(const char* s, WCHAR** ws_ptr) {
+  int ws_len, r;
+  WCHAR* ws;
+
+  ws_len = MultiByteToWideChar(CP_UTF8,
+                               0,
+                               s,
+                               -1,
+                               NULL,
+                               0);
+  if (ws_len <= 0) {
+    return GetLastError();
+  }
+
+  ws = (WCHAR*) uv__malloc(ws_len * sizeof(WCHAR));
+  if (ws == NULL) {
+    return ERROR_OUTOFMEMORY;
+  }
+
+  r = MultiByteToWideChar(CP_UTF8,
+                          0,
+                          s,
+                          -1,
+                          ws,
+                          ws_len);
+  assert(r == ws_len);
+
+  *ws_ptr = ws;
+  return 0;
+}
+
+
+static void uv_process_init(uv_loop_t* loop, uv_process_t* handle) {
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_PROCESS);
+  handle->exit_cb = NULL;
+  handle->pid = 0;
+  handle->exit_signal = 0;
+  handle->wait_handle = INVALID_HANDLE_VALUE;
+  handle->process_handle = INVALID_HANDLE_VALUE;
+  handle->child_stdio_buffer = NULL;
+  handle->exit_cb_pending = 0;
+
+  uv_req_init(loop, (uv_req_t*)&handle->exit_req);
+  handle->exit_req.type = UV_PROCESS_EXIT;
+  handle->exit_req.data = handle;
+}
+
+
+/*
+ * Path search functions
+ */
+
+/*
+ * Helper function for search_path
+ */
+static WCHAR* search_path_join_test(const WCHAR* dir,
+                                    size_t dir_len,
+                                    const WCHAR* name,
+                                    size_t name_len,
+                                    const WCHAR* ext,
+                                    size_t ext_len,
+                                    const WCHAR* cwd,
+                                    size_t cwd_len) {
+  WCHAR *result, *result_pos;
+  DWORD attrs;
+  if (dir_len > 2 && dir[0] == L'\\' && dir[1] == L'\\') {
+    /* It's a UNC path so ignore cwd */
+    cwd_len = 0;
+  } else if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) {
+    /* It's a full path without drive letter, use cwd's drive letter only */
+    cwd_len = 2;
+  } else if (dir_len >= 2 && dir[1] == L':' &&
+      (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) {
+    /* It's a relative path with drive letter (ext.g. D:../some/file)
+     * Replace drive letter in dir by full cwd if it points to the same drive,
+     * otherwise use the dir only.
+     */
+    if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
+      cwd_len = 0;
+    } else {
+      dir += 2;
+      dir_len -= 2;
+    }
+  } else if (dir_len > 2 && dir[1] == L':') {
+    /* It's an absolute path with drive letter
+     * Don't use the cwd at all
+     */
+    cwd_len = 0;
+  }
+
+  /* Allocate buffer for output */
+  result = result_pos = (WCHAR*)uv__malloc(sizeof(WCHAR) *
+      (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1));
+
+  /* Copy cwd */
+  wcsncpy(result_pos, cwd, cwd_len);
+  result_pos += cwd_len;
+
+  /* Add a path separator if cwd didn't end with one */
+  if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
+    result_pos[0] = L'\\';
+    result_pos++;
+  }
+
+  /* Copy dir */
+  wcsncpy(result_pos, dir, dir_len);
+  result_pos += dir_len;
+
+  /* Add a separator if the dir didn't end with one */
+  if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
+    result_pos[0] = L'\\';
+    result_pos++;
+  }
+
+  /* Copy filename */
+  wcsncpy(result_pos, name, name_len);
+  result_pos += name_len;
+
+  if (ext_len) {
+    /* Add a dot if the filename didn't end with one */
+    if (name_len && result_pos[-1] != '.') {
+      result_pos[0] = L'.';
+      result_pos++;
+    }
+
+    /* Copy extension */
+    wcsncpy(result_pos, ext, ext_len);
+    result_pos += ext_len;
+  }
+
+  /* Null terminator */
+  result_pos[0] = L'\0';
+
+  attrs = GetFileAttributesW(result);
+
+  if (attrs != INVALID_FILE_ATTRIBUTES &&
+      !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
+    return result;
+  }
+
+  uv__free(result);
+  return NULL;
+}
+
+
+/*
+ * Helper function for search_path
+ */
+static WCHAR* path_search_walk_ext(const WCHAR *dir,
+                                   size_t dir_len,
+                                   const WCHAR *name,
+                                   size_t name_len,
+                                   WCHAR *cwd,
+                                   size_t cwd_len,
+                                   int name_has_ext) {
+  WCHAR* result;
+
+  /* If the name itself has a nonempty extension, try this extension first */
+  if (name_has_ext) {
+    result = search_path_join_test(dir, dir_len,
+                                   name, name_len,
+                                   L"", 0,
+                                   cwd, cwd_len);
+    if (result != NULL) {
+      return result;
+    }
+  }
+
+  /* Try .com extension */
+  result = search_path_join_test(dir, dir_len,
+                                 name, name_len,
+                                 L"com", 3,
+                                 cwd, cwd_len);
+  if (result != NULL) {
+    return result;
+  }
+
+  /* Try .exe extension */
+  result = search_path_join_test(dir, dir_len,
+                                 name, name_len,
+                                 L"exe", 3,
+                                 cwd, cwd_len);
+  if (result != NULL) {
+    return result;
+  }
+
+  return NULL;
+}
+
+
+/*
+ * search_path searches the system path for an executable filename -
+ * the windows API doesn't provide this as a standalone function nor as an
+ * option to CreateProcess.
+ *
+ * It tries to return an absolute filename.
+ *
+ * Furthermore, it tries to follow the semantics that cmd.exe, with this
+ * exception that PATHEXT environment variable isn't used. Since CreateProcess
+ * can start only .com and .exe files, only those extensions are tried. This
+ * behavior equals that of msvcrt's spawn functions.
+ *
+ * - Do not search the path if the filename already contains a path (either
+ *   relative or absolute).
+ *
+ * - If there's really only a filename, check the current directory for file,
+ *   then search all path directories.
+ *
+ * - If filename specified has *any* extension, search for the file with the
+ *   specified extension first.
+ *
+ * - If the literal filename is not found in a directory, try *appending*
+ *   (not replacing) .com first and then .exe.
+ *
+ * - The path variable may contain relative paths; relative paths are relative
+ *   to the cwd.
+ *
+ * - Directories in path may or may not end with a trailing backslash.
+ *
+ * - CMD does not trim leading/trailing whitespace from path/pathex entries
+ *   nor from the environment variables as a whole.
+ *
+ * - When cmd.exe cannot read a directory, it will just skip it and go on
+ *   searching. However, unlike posix-y systems, it will happily try to run a
+ *   file that is not readable/executable; if the spawn fails it will not
+ *   continue searching.
+ *
+ * UNC path support: we are dealing with UNC paths in both the path and the
+ * filename. This is a deviation from what cmd.exe does (it does not let you
+ * start a program by specifying an UNC path on the command line) but this is
+ * really a pointless restriction.
+ *
+ */
+static WCHAR* search_path(const WCHAR *file,
+                            WCHAR *cwd,
+                            const WCHAR *path) {
+  int file_has_dir;
+  WCHAR* result = NULL;
+  WCHAR *file_name_start;
+  WCHAR *dot;
+  const WCHAR *dir_start, *dir_end, *dir_path;
+  size_t dir_len;
+  int name_has_ext;
+
+  size_t file_len = wcslen(file);
+  size_t cwd_len = wcslen(cwd);
+
+  /* If the caller supplies an empty filename,
+   * we're not gonna return c:\windows\.exe -- GFY!
+   */
+  if (file_len == 0
+      || (file_len == 1 && file[0] == L'.')) {
+    return NULL;
+  }
+
+  /* Find the start of the filename so we can split the directory from the */
+  /* name. */
+  for (file_name_start = (WCHAR*)file + file_len;
+       file_name_start > file
+           && file_name_start[-1] != L'\\'
+           && file_name_start[-1] != L'/'
+           && file_name_start[-1] != L':';
+       file_name_start--);
+
+  file_has_dir = file_name_start != file;
+
+  /* Check if the filename includes an extension */
+  dot = wcschr(file_name_start, L'.');
+  name_has_ext = (dot != NULL && dot[1] != L'\0');
+
+  if (file_has_dir) {
+    /* The file has a path inside, don't use path */
+    result = path_search_walk_ext(
+        file, file_name_start - file,
+        file_name_start, file_len - (file_name_start - file),
+        cwd, cwd_len,
+        name_has_ext);
+
+  } else {
+    dir_end = path;
+
+    /* The file is really only a name; look in cwd first, then scan path */
+    result = path_search_walk_ext(L"", 0,
+                                  file, file_len,
+                                  cwd, cwd_len,
+                                  name_has_ext);
+
+    while (result == NULL) {
+      if (*dir_end == L'\0') {
+        break;
+      }
+
+      /* Skip the separator that dir_end now points to */
+      if (dir_end != path || *path == L';') {
+        dir_end++;
+      }
+
+      /* Next slice starts just after where the previous one ended */
+      dir_start = dir_end;
+
+      /* Slice until the next ; or \0 is found */
+      dir_end = wcschr(dir_start, L';');
+      if (dir_end == NULL) {
+        dir_end = wcschr(dir_start, L'\0');
+      }
+
+      /* If the slice is zero-length, don't bother */
+      if (dir_end - dir_start == 0) {
+        continue;
+      }
+
+      dir_path = dir_start;
+      dir_len = dir_end - dir_start;
+
+      /* Adjust if the path is quoted. */
+      if (dir_path[0] == '"' || dir_path[0] == '\'') {
+        ++dir_path;
+        --dir_len;
+      }
+
+      if (dir_path[dir_len - 1] == '"' || dir_path[dir_len - 1] == '\'') {
+        --dir_len;
+      }
+
+      result = path_search_walk_ext(dir_path, dir_len,
+                                    file, file_len,
+                                    cwd, cwd_len,
+                                    name_has_ext);
+    }
+  }
+
+  return result;
+}
+
+
+/*
+ * Quotes command line arguments
+ * Returns a pointer to the end (next char to be written) of the buffer
+ */
+WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) {
+  size_t len = wcslen(source);
+  size_t i;
+  int quote_hit;
+  WCHAR* start;
+
+  if (len == 0) {
+    /* Need double quotation for empty argument */
+    *(target++) = L'"';
+    *(target++) = L'"';
+    return target;
+  }
+
+  if (NULL == wcspbrk(source, L" \t\"")) {
+    /* No quotation needed */
+    wcsncpy(target, source, len);
+    target += len;
+    return target;
+  }
+
+  if (NULL == wcspbrk(source, L"\"\\")) {
+    /*
+     * No embedded double quotes or backlashes, so I can just wrap
+     * quote marks around the whole thing.
+     */
+    *(target++) = L'"';
+    wcsncpy(target, source, len);
+    target += len;
+    *(target++) = L'"';
+    return target;
+  }
+
+  /*
+   * Expected input/output:
+   *   input : hello"world
+   *   output: "hello\"world"
+   *   input : hello""world
+   *   output: "hello\"\"world"
+   *   input : hello\world
+   *   output: hello\world
+   *   input : hello\\world
+   *   output: hello\\world
+   *   input : hello\"world
+   *   output: "hello\\\"world"
+   *   input : hello\\"world
+   *   output: "hello\\\\\"world"
+   *   input : hello world\
+   *   output: "hello world\"
+   */
+
+  *(target++) = L'"';
+  start = target;
+  quote_hit = 1;
+
+  for (i = len; i > 0; --i) {
+    *(target++) = source[i - 1];
+
+    if (quote_hit && source[i - 1] == L'\\') {
+      *(target++) = L'\\';
+    } else if(source[i - 1] == L'"') {
+      quote_hit = 1;
+      *(target++) = L'\\';
+    } else {
+      quote_hit = 0;
+    }
+  }
+  target[0] = L'\0';
+  wcsrev(start);
+  *(target++) = L'"';
+  return target;
+}
+
+
+int make_program_args(char** args, int verbatim_arguments, WCHAR** dst_ptr) {
+  char** arg;
+  WCHAR* dst = NULL;
+  WCHAR* temp_buffer = NULL;
+  size_t dst_len = 0;
+  size_t temp_buffer_len = 0;
+  WCHAR* pos;
+  int arg_count = 0;
+  int err = 0;
+
+  /* Count the required size. */
+  for (arg = args; *arg; arg++) {
+    DWORD arg_len;
+
+    arg_len = MultiByteToWideChar(CP_UTF8,
+                                  0,
+                                  *arg,
+                                  -1,
+                                  NULL,
+                                  0);
+    if (arg_len == 0) {
+      return GetLastError();
+    }
+
+    dst_len += arg_len;
+
+    if (arg_len > temp_buffer_len)
+      temp_buffer_len = arg_len;
+
+    arg_count++;
+  }
+
+  /* Adjust for potential quotes. Also assume the worst-case scenario */
+  /* that every character needs escaping, so we need twice as much space. */
+  dst_len = dst_len * 2 + arg_count * 2;
+
+  /* Allocate buffer for the final command line. */
+  dst = (WCHAR*) uv__malloc(dst_len * sizeof(WCHAR));
+  if (dst == NULL) {
+    err = ERROR_OUTOFMEMORY;
+    goto error;
+  }
+
+  /* Allocate temporary working buffer. */
+  temp_buffer = (WCHAR*) uv__malloc(temp_buffer_len * sizeof(WCHAR));
+  if (temp_buffer == NULL) {
+    err = ERROR_OUTOFMEMORY;
+    goto error;
+  }
+
+  pos = dst;
+  for (arg = args; *arg; arg++) {
+    DWORD arg_len;
+
+    /* Convert argument to wide char. */
+    arg_len = MultiByteToWideChar(CP_UTF8,
+                                  0,
+                                  *arg,
+                                  -1,
+                                  temp_buffer,
+                                  (int) (dst + dst_len - pos));
+    if (arg_len == 0) {
+      err = GetLastError();
+      goto error;
+    }
+
+    if (verbatim_arguments) {
+      /* Copy verbatim. */
+      wcscpy(pos, temp_buffer);
+      pos += arg_len - 1;
+    } else {
+      /* Quote/escape, if needed. */
+      pos = quote_cmd_arg(temp_buffer, pos);
+    }
+
+    *pos++ = *(arg + 1) ? L' ' : L'\0';
+  }
+
+  uv__free(temp_buffer);
+
+  *dst_ptr = dst;
+  return 0;
+
+error:
+  uv__free(dst);
+  uv__free(temp_buffer);
+  return err;
+}
+
+
+int env_strncmp(const wchar_t* a, int na, const wchar_t* b) {
+  wchar_t* a_eq;
+  wchar_t* b_eq;
+  wchar_t* A;
+  wchar_t* B;
+  int nb;
+  int r;
+
+  if (na < 0) {
+    a_eq = wcschr(a, L'=');
+    assert(a_eq);
+    na = (int)(long)(a_eq - a);
+  } else {
+    na--;
+  }
+  b_eq = wcschr(b, L'=');
+  assert(b_eq);
+  nb = b_eq - b;
+
+  A = alloca((na+1) * sizeof(wchar_t));
+  B = alloca((nb+1) * sizeof(wchar_t));
+
+  r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na);
+  assert(r==na);
+  A[na] = L'\0';
+  r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb);
+  assert(r==nb);
+  B[nb] = L'\0';
+
+  while (1) {
+    wchar_t AA = *A++;
+    wchar_t BB = *B++;
+    if (AA < BB) {
+      return -1;
+    } else if (AA > BB) {
+      return 1;
+    } else if (!AA && !BB) {
+      return 0;
+    }
+  }
+}
+
+
+static int qsort_wcscmp(const void *a, const void *b) {
+  wchar_t* astr = *(wchar_t* const*)a;
+  wchar_t* bstr = *(wchar_t* const*)b;
+  return env_strncmp(astr, -1, bstr);
+}
+
+
+/*
+ * The way windows takes environment variables is different than what C does;
+ * Windows wants a contiguous block of null-terminated strings, terminated
+ * with an additional null.
+ *
+ * Windows has a few "essential" environment variables. winsock will fail
+ * to initialize if SYSTEMROOT is not defined; some APIs make reference to
+ * TEMP. SYSTEMDRIVE is probably also important. We therefore ensure that
+ * these get defined if the input environment block does not contain any
+ * values for them.
+ *
+ * Also add variables known to Cygwin to be required for correct
+ * subprocess operation in many cases:
+ * https://github.com/Alexpux/Cygwin/blob/b266b04fbbd3a595f02ea149e4306d3ab9b1fe3d/winsup/cygwin/environ.cc#L955
+ *
+ */
+int make_program_env(char* env_block[], WCHAR** dst_ptr) {
+  WCHAR* dst;
+  WCHAR* ptr;
+  char** env;
+  size_t env_len = 0;
+  int len;
+  size_t i;
+  DWORD var_size;
+  size_t env_block_count = 1; /* 1 for null-terminator */
+  WCHAR* dst_copy;
+  WCHAR** ptr_copy;
+  WCHAR** env_copy;
+  DWORD* required_vars_value_len = alloca(n_required_vars * sizeof(DWORD*));
+
+  /* first pass: determine size in UTF-16 */
+  for (env = env_block; *env; env++) {
+    int len;
+    if (strchr(*env, '=')) {
+      len = MultiByteToWideChar(CP_UTF8,
+                                0,
+                                *env,
+                                -1,
+                                NULL,
+                                0);
+      if (len <= 0) {
+        return GetLastError();
+      }
+      env_len += len;
+      env_block_count++;
+    }
+  }
+
+  /* second pass: copy to UTF-16 environment block */
+  dst_copy = (WCHAR*)uv__malloc(env_len * sizeof(WCHAR));
+  if (!dst_copy) {
+    return ERROR_OUTOFMEMORY;
+  }
+  env_copy = alloca(env_block_count * sizeof(WCHAR*));
+
+  ptr = dst_copy;
+  ptr_copy = env_copy;
+  for (env = env_block; *env; env++) {
+    if (strchr(*env, '=')) {
+      len = MultiByteToWideChar(CP_UTF8,
+                                0,
+                                *env,
+                                -1,
+                                ptr,
+                                (int) (env_len - (ptr - dst_copy)));
+      if (len <= 0) {
+        DWORD err = GetLastError();
+        uv__free(dst_copy);
+        return err;
+      }
+      *ptr_copy++ = ptr;
+      ptr += len;
+    }
+  }
+  *ptr_copy = NULL;
+  assert(env_len == ptr - dst_copy);
+
+  /* sort our (UTF-16) copy */
+  qsort(env_copy, env_block_count-1, sizeof(wchar_t*), qsort_wcscmp);
+
+  /* third pass: check for required variables */
+  for (ptr_copy = env_copy, i = 0; i < n_required_vars; ) {
+    int cmp;
+    if (!*ptr_copy) {
+      cmp = -1;
+    } else {
+      cmp = env_strncmp(required_vars[i].wide_eq,
+                       required_vars[i].len,
+                        *ptr_copy);
+    }
+    if (cmp < 0) {
+      /* missing required var */
+      var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0);
+      required_vars_value_len[i] = var_size;
+      if (var_size != 0) {
+        env_len += required_vars[i].len;
+        env_len += var_size;
+      }
+      i++;
+    } else {
+      ptr_copy++;
+      if (cmp == 0)
+        i++;
+    }
+  }
+
+  /* final pass: copy, in sort order, and inserting required variables */
+  dst = uv__malloc((1+env_len) * sizeof(WCHAR));
+  if (!dst) {
+    uv__free(dst_copy);
+    return ERROR_OUTOFMEMORY;
+  }
+
+  for (ptr = dst, ptr_copy = env_copy, i = 0;
+       *ptr_copy || i < n_required_vars;
+       ptr += len) {
+    int cmp;
+    if (i >= n_required_vars) {
+      cmp = 1;
+    } else if (!*ptr_copy) {
+      cmp = -1;
+    } else {
+      cmp = env_strncmp(required_vars[i].wide_eq,
+                        required_vars[i].len,
+                        *ptr_copy);
+    }
+    if (cmp < 0) {
+      /* missing required var */
+      len = required_vars_value_len[i];
+      if (len) {
+        wcscpy(ptr, required_vars[i].wide_eq);
+        ptr += required_vars[i].len;
+        var_size = GetEnvironmentVariableW(required_vars[i].wide,
+                                           ptr,
+                                           (int) (env_len - (ptr - dst)));
+        if (var_size != len-1) { /* race condition? */
+          uv_fatal_error(GetLastError(), "GetEnvironmentVariableW");
+        }
+      }
+      i++;
+    } else {
+      /* copy var from env_block */
+      len = wcslen(*ptr_copy) + 1;
+      wmemcpy(ptr, *ptr_copy, len);
+      ptr_copy++;
+      if (cmp == 0)
+        i++;
+    }
+  }
+
+  /* Terminate with an extra NULL. */
+  assert(env_len == (ptr - dst));
+  *ptr = L'\0';
+
+  uv__free(dst_copy);
+  *dst_ptr = dst;
+  return 0;
+}
+
+/*
+ * Attempt to find the value of the PATH environment variable in the child's
+ * preprocessed environment.
+ *
+ * If found, a pointer into `env` is returned. If not found, NULL is returned.
+ */
+static WCHAR* find_path(WCHAR *env) {
+  for (; env != NULL && *env != 0; env += wcslen(env) + 1) {
+    if (wcsncmp(env, L"PATH=", 5) == 0)
+      return &env[5];
+  }
+
+  return NULL;
+}
+
+/*
+ * Called on Windows thread-pool thread to indicate that
+ * a child process has exited.
+ */
+static void CALLBACK exit_wait_callback(void* data, BOOLEAN didTimeout) {
+  uv_process_t* process = (uv_process_t*) data;
+  uv_loop_t* loop = process->loop;
+
+  assert(didTimeout == FALSE);
+  assert(process);
+  assert(!process->exit_cb_pending);
+
+  process->exit_cb_pending = 1;
+
+  /* Post completed */
+  POST_COMPLETION_FOR_REQ(loop, &process->exit_req);
+}
+
+
+/* Called on main thread after a child process has exited. */
+void uv_process_proc_exit(uv_loop_t* loop, uv_process_t* handle) {
+  int64_t exit_code;
+  DWORD status;
+
+  assert(handle->exit_cb_pending);
+  handle->exit_cb_pending = 0;
+
+  /* If we're closing, don't call the exit callback. Just schedule a close */
+  /* callback now. */
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+    return;
+  }
+
+  /* Unregister from process notification. */
+  if (handle->wait_handle != INVALID_HANDLE_VALUE) {
+    UnregisterWait(handle->wait_handle);
+    handle->wait_handle = INVALID_HANDLE_VALUE;
+  }
+
+  /* Set the handle to inactive: no callbacks will be made after the exit */
+  /* callback.*/
+  uv__handle_stop(handle);
+
+  if (GetExitCodeProcess(handle->process_handle, &status)) {
+    exit_code = status;
+  } else {
+    /* Unable to to obtain the exit code. This should never happen. */
+    exit_code = uv_translate_sys_error(GetLastError());
+  }
+
+  /* Fire the exit callback. */
+  if (handle->exit_cb) {
+    handle->exit_cb(handle, exit_code, handle->exit_signal);
+  }
+}
+
+
+void uv_process_close(uv_loop_t* loop, uv_process_t* handle) {
+  uv__handle_closing(handle);
+
+  if (handle->wait_handle != INVALID_HANDLE_VALUE) {
+    /* This blocks until either the wait was cancelled, or the callback has */
+    /* completed. */
+    BOOL r = UnregisterWaitEx(handle->wait_handle, INVALID_HANDLE_VALUE);
+    if (!r) {
+      /* This should never happen, and if it happens, we can't recover... */
+      uv_fatal_error(GetLastError(), "UnregisterWaitEx");
+    }
+
+    handle->wait_handle = INVALID_HANDLE_VALUE;
+  }
+
+  if (!handle->exit_cb_pending) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+}
+
+
+void uv_process_endgame(uv_loop_t* loop, uv_process_t* handle) {
+  assert(!handle->exit_cb_pending);
+  assert(handle->flags & UV__HANDLE_CLOSING);
+  assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+  /* Clean-up the process handle. */
+  CloseHandle(handle->process_handle);
+
+  uv__handle_close(handle);
+}
+
+
+int uv_spawn(uv_loop_t* loop,
+             uv_process_t* process,
+             const uv_process_options_t* options) {
+  int i;
+  int err = 0;
+  WCHAR* path = NULL, *alloc_path = NULL;
+  BOOL result;
+  WCHAR* application_path = NULL, *application = NULL, *arguments = NULL,
+         *env = NULL, *cwd = NULL;
+  STARTUPINFOW startup;
+  PROCESS_INFORMATION info;
+  DWORD process_flags;
+
+  uv_process_init(loop, process);
+  process->exit_cb = options->exit_cb;
+
+  if (options->flags & (UV_PROCESS_SETGID | UV_PROCESS_SETUID)) {
+    return UV_ENOTSUP;
+  }
+
+  if (options->file == NULL ||
+      options->args == NULL) {
+    return UV_EINVAL;
+  }
+
+  assert(options->file != NULL);
+  assert(!(options->flags & ~(UV_PROCESS_DETACHED |
+                              UV_PROCESS_SETGID |
+                              UV_PROCESS_SETUID |
+                              UV_PROCESS_WINDOWS_HIDE |
+                              UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
+
+  err = uv_utf8_to_utf16_alloc(options->file, &application);
+  if (err)
+    goto done;
+
+  err = make_program_args(
+      options->args,
+      options->flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS,
+      &arguments);
+  if (err)
+    goto done;
+
+  if (options->env) {
+     err = make_program_env(options->env, &env);
+     if (err)
+       goto done;
+  }
+
+  if (options->cwd) {
+    /* Explicit cwd */
+    err = uv_utf8_to_utf16_alloc(options->cwd, &cwd);
+    if (err)
+      goto done;
+
+  } else {
+    /* Inherit cwd */
+    DWORD cwd_len, r;
+
+    cwd_len = GetCurrentDirectoryW(0, NULL);
+    if (!cwd_len) {
+      err = GetLastError();
+      goto done;
+    }
+
+    cwd = (WCHAR*) uv__malloc(cwd_len * sizeof(WCHAR));
+    if (cwd == NULL) {
+      err = ERROR_OUTOFMEMORY;
+      goto done;
+    }
+
+    r = GetCurrentDirectoryW(cwd_len, cwd);
+    if (r == 0 || r >= cwd_len) {
+      err = GetLastError();
+      goto done;
+    }
+  }
+
+  /* Get PATH environment variable. */
+  path = find_path(env);
+  if (path == NULL) {
+    DWORD path_len, r;
+
+    path_len = GetEnvironmentVariableW(L"PATH", NULL, 0);
+    if (path_len == 0) {
+      err = GetLastError();
+      goto done;
+    }
+
+    alloc_path = (WCHAR*) uv__malloc(path_len * sizeof(WCHAR));
+    if (alloc_path == NULL) {
+      err = ERROR_OUTOFMEMORY;
+      goto done;
+    }
+    path = alloc_path;
+
+    r = GetEnvironmentVariableW(L"PATH", path, path_len);
+    if (r == 0 || r >= path_len) {
+      err = GetLastError();
+      goto done;
+    }
+  }
+
+  err = uv__stdio_create(loop, options, &process->child_stdio_buffer);
+  if (err)
+    goto done;
+
+  application_path = search_path(application,
+                                 cwd,
+                                 path);
+  if (application_path == NULL) {
+    /* Not found. */
+    err = ERROR_FILE_NOT_FOUND;
+    goto done;
+  }
+
+  startup.cb = sizeof(startup);
+  startup.lpReserved = NULL;
+  startup.lpDesktop = NULL;
+  startup.lpTitle = NULL;
+  startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
+
+  startup.cbReserved2 = uv__stdio_size(process->child_stdio_buffer);
+  startup.lpReserved2 = (BYTE*) process->child_stdio_buffer;
+
+  startup.hStdInput = uv__stdio_handle(process->child_stdio_buffer, 0);
+  startup.hStdOutput = uv__stdio_handle(process->child_stdio_buffer, 1);
+  startup.hStdError = uv__stdio_handle(process->child_stdio_buffer, 2);
+
+  if (options->flags & UV_PROCESS_WINDOWS_HIDE) {
+    /* Use SW_HIDE to avoid any potential process window. */
+    startup.wShowWindow = SW_HIDE;
+  } else {
+    startup.wShowWindow = SW_SHOWDEFAULT;
+  }
+
+  process_flags = CREATE_UNICODE_ENVIRONMENT;
+
+  if (options->flags & UV_PROCESS_DETACHED) {
+    /* Note that we're not setting the CREATE_BREAKAWAY_FROM_JOB flag. That
+     * means that libuv might not let you create a fully daemonized process
+     * when run under job control. However the type of job control that libuv
+     * itself creates doesn't trickle down to subprocesses so they can still
+     * daemonize.
+     *
+     * A reason to not do this is that CREATE_BREAKAWAY_FROM_JOB makes the
+     * CreateProcess call fail if we're under job control that doesn't allow
+     * breakaway.
+     */
+    process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
+  }
+
+  if (!CreateProcessW(application_path,
+                     arguments,
+                     NULL,
+                     NULL,
+                     1,
+                     process_flags,
+                     env,
+                     cwd,
+                     &startup,
+                     &info)) {
+    /* CreateProcessW failed. */
+    err = GetLastError();
+    goto done;
+  }
+
+  /* Spawn succeeded */
+  /* Beyond this point, failure is reported asynchronously. */
+
+  process->process_handle = info.hProcess;
+  process->pid = info.dwProcessId;
+
+  /* If the process isn't spawned as detached, assign to the global job */
+  /* object so windows will kill it when the parent process dies. */
+  if (!(options->flags & UV_PROCESS_DETACHED)) {
+    uv_once(&uv_global_job_handle_init_guard_, uv__init_global_job_handle);
+
+    if (!AssignProcessToJobObject(uv_global_job_handle_, info.hProcess)) {
+      /* AssignProcessToJobObject might fail if this process is under job
+       * control and the job doesn't have the
+       * JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag set, on a Windows version
+       * that doesn't support nested jobs.
+       *
+       * When that happens we just swallow the error and continue without
+       * establishing a kill-child-on-parent-exit relationship, otherwise
+       * there would be no way for libuv applications run under job control
+       * to spawn processes at all.
+       */
+      DWORD err = GetLastError();
+      if (err != ERROR_ACCESS_DENIED)
+        uv_fatal_error(err, "AssignProcessToJobObject");
+    }
+  }
+
+  /* Set IPC pid to all IPC pipes. */
+  for (i = 0; i < options->stdio_count; i++) {
+    const uv_stdio_container_t* fdopt = &options->stdio[i];
+    if (fdopt->flags & UV_CREATE_PIPE &&
+        fdopt->data.stream->type == UV_NAMED_PIPE &&
+        ((uv_pipe_t*) fdopt->data.stream)->ipc) {
+      ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_pid = info.dwProcessId;
+    }
+  }
+
+  /* Setup notifications for when the child process exits. */
+  result = RegisterWaitForSingleObject(&process->wait_handle,
+      process->process_handle, exit_wait_callback, (void*)process, INFINITE,
+      WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
+  if (!result) {
+    uv_fatal_error(GetLastError(), "RegisterWaitForSingleObject");
+  }
+
+  CloseHandle(info.hThread);
+
+  assert(!err);
+
+  /* Make the handle active. It will remain active until the exit callback */
+  /* is made or the handle is closed, whichever happens first. */
+  uv__handle_start(process);
+
+  /* Cleanup, whether we succeeded or failed. */
+ done:
+  uv__free(application);
+  uv__free(application_path);
+  uv__free(arguments);
+  uv__free(cwd);
+  uv__free(env);
+  uv__free(alloc_path);
+
+  if (process->child_stdio_buffer != NULL) {
+    /* Clean up child stdio handles. */
+    uv__stdio_destroy(process->child_stdio_buffer);
+    process->child_stdio_buffer = NULL;
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+static int uv__kill(HANDLE process_handle, int signum) {
+  switch (signum) {
+    case SIGTERM:
+    case SIGKILL:
+    case SIGINT: {
+      /* Unconditionally terminate the process. On Windows, killed processes */
+      /* normally return 1. */
+      DWORD status;
+      int err;
+
+      if (TerminateProcess(process_handle, 1))
+        return 0;
+
+      /* If the process already exited before TerminateProcess was called, */
+      /* TerminateProcess will fail with ERROR_ACCESS_DENIED. */
+      err = GetLastError();
+      if (err == ERROR_ACCESS_DENIED &&
+          GetExitCodeProcess(process_handle, &status) &&
+          status != STILL_ACTIVE) {
+        return UV_ESRCH;
+      }
+
+      return uv_translate_sys_error(err);
+    }
+
+    case 0: {
+      /* Health check: is the process still alive? */
+      DWORD status;
+
+      if (!GetExitCodeProcess(process_handle, &status))
+        return uv_translate_sys_error(GetLastError());
+
+      if (status != STILL_ACTIVE)
+        return UV_ESRCH;
+
+      return 0;
+    }
+
+    default:
+      /* Unsupported signal. */
+      return UV_ENOSYS;
+  }
+}
+
+
+int uv_process_kill(uv_process_t* process, int signum) {
+  int err;
+
+  if (process->process_handle == INVALID_HANDLE_VALUE) {
+    return UV_EINVAL;
+  }
+
+  err = uv__kill(process->process_handle, signum);
+  if (err) {
+    return err;  /* err is already translated. */
+  }
+
+  process->exit_signal = signum;
+
+  return 0;
+}
+
+
+int uv_kill(int pid, int signum) {
+  int err;
+  HANDLE process_handle = OpenProcess(PROCESS_TERMINATE |
+    PROCESS_QUERY_INFORMATION, FALSE, pid);
+
+  if (process_handle == NULL) {
+    err = GetLastError();
+    if (err == ERROR_INVALID_PARAMETER) {
+      return UV_ESRCH;
+    } else {
+      return uv_translate_sys_error(err);
+    }
+  }
+
+  err = uv__kill(process_handle, signum);
+  CloseHandle(process_handle);
+
+  return err;  /* err is already translated. */
+}
diff --git a/Utilities/cmlibuv/src/win/req-inl.h b/Utilities/cmlibuv/src/win/req-inl.h
new file mode 100644
index 0000000..b5e502e
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/req-inl.h
@@ -0,0 +1,224 @@
+/* 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_WIN_REQ_INL_H_
+#define UV_WIN_REQ_INL_H_
+
+#include <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+#define SET_REQ_STATUS(req, status)                                     \
+   (req)->u.io.overlapped.Internal = (ULONG_PTR) (status)
+
+#define SET_REQ_ERROR(req, error)                                       \
+  SET_REQ_STATUS((req), NTSTATUS_FROM_WIN32((error)))
+
+#define SET_REQ_SUCCESS(req)                                            \
+  SET_REQ_STATUS((req), STATUS_SUCCESS)
+
+#define GET_REQ_STATUS(req)                                             \
+  ((NTSTATUS) (req)->u.io.overlapped.Internal)
+
+#define REQ_SUCCESS(req)                                                \
+  (NT_SUCCESS(GET_REQ_STATUS((req))))
+
+#define GET_REQ_ERROR(req)                                              \
+  (pRtlNtStatusToDosError(GET_REQ_STATUS((req))))
+
+#define GET_REQ_SOCK_ERROR(req)                                         \
+  (uv_ntstatus_to_winsock_error(GET_REQ_STATUS((req))))
+
+
+#define REGISTER_HANDLE_REQ(loop, handle, req)                          \
+  do {                                                                  \
+    INCREASE_ACTIVE_COUNT((loop), (handle));                            \
+    uv__req_register((loop), (req));                                    \
+  } while (0)
+
+#define UNREGISTER_HANDLE_REQ(loop, handle, req)                        \
+  do {                                                                  \
+    DECREASE_ACTIVE_COUNT((loop), (handle));                            \
+    uv__req_unregister((loop), (req));                                  \
+  } while (0)
+
+
+#define UV_SUCCEEDED_WITHOUT_IOCP(result)                               \
+  ((result) && (handle->flags & UV_HANDLE_SYNC_BYPASS_IOCP))
+
+#define UV_SUCCEEDED_WITH_IOCP(result)                                  \
+  ((result) || (GetLastError() == ERROR_IO_PENDING))
+
+
+#define POST_COMPLETION_FOR_REQ(loop, req)                              \
+  if (!PostQueuedCompletionStatus((loop)->iocp,                         \
+                                  0,                                    \
+                                  0,                                    \
+                                  &((req)->u.io.overlapped))) {         \
+    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");       \
+  }
+
+
+INLINE static void uv_req_init(uv_loop_t* loop, uv_req_t* req) {
+  req->type = UV_UNKNOWN_REQ;
+  SET_REQ_SUCCESS(req);
+}
+
+
+INLINE static uv_req_t* uv_overlapped_to_req(OVERLAPPED* overlapped) {
+  return CONTAINING_RECORD(overlapped, uv_req_t, u.io.overlapped);
+}
+
+
+INLINE static void uv_insert_pending_req(uv_loop_t* loop, uv_req_t* req) {
+  req->next_req = NULL;
+  if (loop->pending_reqs_tail) {
+#ifdef _DEBUG
+    /* Ensure the request is not already in the queue, or the queue
+     * will get corrupted.
+     */
+    uv_req_t* current = loop->pending_reqs_tail;
+    do {
+      assert(req != current);
+      current = current->next_req;
+    } while(current != loop->pending_reqs_tail);
+#endif
+
+    req->next_req = loop->pending_reqs_tail->next_req;
+    loop->pending_reqs_tail->next_req = req;
+    loop->pending_reqs_tail = req;
+  } else {
+    req->next_req = req;
+    loop->pending_reqs_tail = req;
+  }
+}
+
+
+#define DELEGATE_STREAM_REQ(loop, req, method, handle_at)                     \
+  do {                                                                        \
+    switch (((uv_handle_t*) (req)->handle_at)->type) {                        \
+      case UV_TCP:                                                            \
+        uv_process_tcp_##method##_req(loop,                                   \
+                                      (uv_tcp_t*) ((req)->handle_at),         \
+                                      req);                                   \
+        break;                                                                \
+                                                                              \
+      case UV_NAMED_PIPE:                                                     \
+        uv_process_pipe_##method##_req(loop,                                  \
+                                       (uv_pipe_t*) ((req)->handle_at),       \
+                                       req);                                  \
+        break;                                                                \
+                                                                              \
+      case UV_TTY:                                                            \
+        uv_process_tty_##method##_req(loop,                                   \
+                                      (uv_tty_t*) ((req)->handle_at),         \
+                                      req);                                   \
+        break;                                                                \
+                                                                              \
+      default:                                                                \
+        assert(0);                                                            \
+    }                                                                         \
+  } while (0)
+
+
+INLINE static int uv_process_reqs(uv_loop_t* loop) {
+  uv_req_t* req;
+  uv_req_t* first;
+  uv_req_t* next;
+
+  if (loop->pending_reqs_tail == NULL)
+    return 0;
+
+  first = loop->pending_reqs_tail->next_req;
+  next = first;
+  loop->pending_reqs_tail = NULL;
+
+  while (next != NULL) {
+    req = next;
+    next = req->next_req != first ? req->next_req : NULL;
+
+    switch (req->type) {
+      case UV_READ:
+        DELEGATE_STREAM_REQ(loop, req, read, data);
+        break;
+
+      case UV_WRITE:
+        DELEGATE_STREAM_REQ(loop, (uv_write_t*) req, write, handle);
+        break;
+
+      case UV_ACCEPT:
+        DELEGATE_STREAM_REQ(loop, req, accept, data);
+        break;
+
+      case UV_CONNECT:
+        DELEGATE_STREAM_REQ(loop, (uv_connect_t*) req, connect, handle);
+        break;
+
+      case UV_SHUTDOWN:
+        /* Tcp shutdown requests don't come here. */
+        assert(((uv_shutdown_t*) req)->handle->type == UV_NAMED_PIPE);
+        uv_process_pipe_shutdown_req(
+            loop,
+            (uv_pipe_t*) ((uv_shutdown_t*) req)->handle,
+            (uv_shutdown_t*) req);
+        break;
+
+      case UV_UDP_RECV:
+        uv_process_udp_recv_req(loop, (uv_udp_t*) req->data, req);
+        break;
+
+      case UV_UDP_SEND:
+        uv_process_udp_send_req(loop,
+                                ((uv_udp_send_t*) req)->handle,
+                                (uv_udp_send_t*) req);
+        break;
+
+      case UV_WAKEUP:
+        uv_process_async_wakeup_req(loop, (uv_async_t*) req->data, req);
+        break;
+
+      case UV_SIGNAL_REQ:
+        uv_process_signal_req(loop, (uv_signal_t*) req->data, req);
+        break;
+
+      case UV_POLL_REQ:
+        uv_process_poll_req(loop, (uv_poll_t*) req->data, req);
+        break;
+
+      case UV_PROCESS_EXIT:
+        uv_process_proc_exit(loop, (uv_process_t*) req->data);
+        break;
+
+      case UV_FS_EVENT_REQ:
+        uv_process_fs_event_req(loop, req, (uv_fs_event_t*) req->data);
+        break;
+
+      default:
+        assert(0);
+    }
+  }
+
+  return 1;
+}
+
+#endif /* UV_WIN_REQ_INL_H_ */
diff --git a/Utilities/cmlibuv/src/win/req.c b/Utilities/cmlibuv/src/win/req.c
new file mode 100644
index 0000000..111cc5e
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/req.c
@@ -0,0 +1,25 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
diff --git a/Utilities/cmlibuv/src/win/signal.c b/Utilities/cmlibuv/src/win/signal.c
new file mode 100644
index 0000000..2c64a55
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/signal.c
@@ -0,0 +1,356 @@
+/* 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 <assert.h>
+#include <signal.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+RB_HEAD(uv_signal_tree_s, uv_signal_s);
+
+static struct uv_signal_tree_s uv__signal_tree = RB_INITIALIZER(uv__signal_tree);
+static ssize_t volatile uv__signal_control_handler_refs = 0;
+static CRITICAL_SECTION uv__signal_lock;
+
+
+void uv_signals_init() {
+  InitializeCriticalSection(&uv__signal_lock);
+}
+
+
+static int uv__signal_compare(uv_signal_t* w1, uv_signal_t* w2) {
+  /* Compare signums first so all watchers with the same signnum end up */
+  /* adjacent. */
+  if (w1->signum < w2->signum) return -1;
+  if (w1->signum > w2->signum) return 1;
+
+  /* Sort by loop pointer, so we can easily look up the first item after */
+  /* { .signum = x, .loop = NULL } */
+  if ((uintptr_t) w1->loop < (uintptr_t) w2->loop) return -1;
+  if ((uintptr_t) w1->loop > (uintptr_t) w2->loop) return 1;
+
+  if ((uintptr_t) w1 < (uintptr_t) w2) return -1;
+  if ((uintptr_t) w1 > (uintptr_t) w2) return 1;
+
+  return 0;
+}
+
+
+RB_GENERATE_STATIC(uv_signal_tree_s, uv_signal_s, tree_entry, uv__signal_compare);
+
+
+/*
+ * Dispatches signal {signum} to all active uv_signal_t watchers in all loops.
+ * Returns 1 if the signal was dispatched to any watcher, or 0 if there were
+ * no active signal watchers observing this signal.
+ */
+int uv__signal_dispatch(int signum) {
+  uv_signal_t lookup;
+  uv_signal_t* handle;
+  int dispatched = 0;
+
+  EnterCriticalSection(&uv__signal_lock);
+
+  lookup.signum = signum;
+  lookup.loop = NULL;
+
+  for (handle = RB_NFIND(uv_signal_tree_s, &uv__signal_tree, &lookup);
+       handle != NULL && handle->signum == signum;
+       handle = RB_NEXT(uv_signal_tree_s, &uv__signal_tree, handle)) {
+    unsigned long previous = InterlockedExchange(
+            (volatile LONG*) &handle->pending_signum, signum);
+
+    if (!previous) {
+      POST_COMPLETION_FOR_REQ(handle->loop, &handle->signal_req);
+    }
+
+    dispatched = 1;
+  }
+
+  LeaveCriticalSection(&uv__signal_lock);
+
+  return dispatched;
+}
+
+
+static BOOL WINAPI uv__signal_control_handler(DWORD type) {
+  switch (type) {
+    case CTRL_C_EVENT:
+      return uv__signal_dispatch(SIGINT);
+
+    case CTRL_BREAK_EVENT:
+      return uv__signal_dispatch(SIGBREAK);
+
+    case CTRL_CLOSE_EVENT:
+      if (uv__signal_dispatch(SIGHUP)) {
+        /* Windows will terminate the process after the control handler */
+        /* returns. After that it will just terminate our process. Therefore */
+        /* block the signal handler so the main loop has some time to pick */
+        /* up the signal and do something for a few seconds. */
+        Sleep(INFINITE);
+        return TRUE;
+      }
+      return FALSE;
+
+    case CTRL_LOGOFF_EVENT:
+    case CTRL_SHUTDOWN_EVENT:
+      /* These signals are only sent to services. Services have their own */
+      /* notification mechanism, so there's no point in handling these. */
+
+    default:
+      /* We don't handle these. */
+      return FALSE;
+  }
+}
+
+
+static int uv__signal_register_control_handler() {
+  /* When this function is called, the uv__signal_lock must be held. */
+
+  /* If the console control handler has already been hooked, just add a */
+  /* reference. */
+  if (uv__signal_control_handler_refs > 0) {
+    uv__signal_control_handler_refs++;
+    return 0;
+  }
+
+  if (!SetConsoleCtrlHandler(uv__signal_control_handler, TRUE))
+    return GetLastError();
+
+  uv__signal_control_handler_refs++;
+
+  return 0;
+}
+
+
+static void uv__signal_unregister_control_handler() {
+  /* When this function is called, the uv__signal_lock must be held. */
+  BOOL r;
+
+  /* Don't unregister if the number of console control handlers exceeds one. */
+  /* Just remove a reference in that case. */
+  if (uv__signal_control_handler_refs > 1) {
+    uv__signal_control_handler_refs--;
+    return;
+  }
+
+  assert(uv__signal_control_handler_refs == 1);
+
+  r = SetConsoleCtrlHandler(uv__signal_control_handler, FALSE);
+  /* This should never fail; if it does it is probably a bug in libuv. */
+  assert(r);
+
+  uv__signal_control_handler_refs--;
+}
+
+
+static int uv__signal_register(int signum) {
+  switch (signum) {
+    case SIGINT:
+    case SIGBREAK:
+    case SIGHUP:
+      return uv__signal_register_control_handler();
+
+    case SIGWINCH:
+      /* SIGWINCH is generated in tty.c. No need to register anything. */
+      return 0;
+
+    case SIGILL:
+    case SIGABRT_COMPAT:
+    case SIGFPE:
+    case SIGSEGV:
+    case SIGTERM:
+    case SIGABRT:
+      /* Signal is never raised. */
+      return 0;
+
+    default:
+      /* Invalid signal. */
+      return ERROR_INVALID_PARAMETER;
+  }
+}
+
+
+static void uv__signal_unregister(int signum) {
+  switch (signum) {
+    case SIGINT:
+    case SIGBREAK:
+    case SIGHUP:
+      uv__signal_unregister_control_handler();
+      return;
+
+    case SIGWINCH:
+      /* SIGWINCH is generated in tty.c. No need to unregister anything. */
+      return;
+
+    case SIGILL:
+    case SIGABRT_COMPAT:
+    case SIGFPE:
+    case SIGSEGV:
+    case SIGTERM:
+    case SIGABRT:
+      /* Nothing is registered for this signal. */
+      return;
+
+    default:
+      /* Libuv bug. */
+      assert(0 && "Invalid signum");
+      return;
+  }
+}
+
+
+int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle) {
+  uv_req_t* req;
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_SIGNAL);
+  handle->pending_signum = 0;
+  handle->signum = 0;
+  handle->signal_cb = NULL;
+
+  req = &handle->signal_req;
+  uv_req_init(loop, req);
+  req->type = UV_SIGNAL_REQ;
+  req->data = handle;
+
+  return 0;
+}
+
+
+int uv_signal_stop(uv_signal_t* handle) {
+  uv_signal_t* removed_handle;
+
+  /* If the watcher wasn't started, this is a no-op. */
+  if (handle->signum == 0)
+    return 0;
+
+  EnterCriticalSection(&uv__signal_lock);
+
+  uv__signal_unregister(handle->signum);
+
+  removed_handle = RB_REMOVE(uv_signal_tree_s, &uv__signal_tree, handle);
+  assert(removed_handle == handle);
+
+  LeaveCriticalSection(&uv__signal_lock);
+
+  handle->signum = 0;
+  uv__handle_stop(handle);
+
+  return 0;
+}
+
+
+int uv_signal_start(uv_signal_t* handle, uv_signal_cb signal_cb, int signum) {
+  int err;
+
+  /* If the user supplies signum == 0, then return an error already. If the */
+  /* signum is otherwise invalid then uv__signal_register will find out */
+  /* eventually. */
+  if (signum == 0) {
+    return UV_EINVAL;
+  }
+
+  /* Short circuit: if the signal watcher is already watching {signum} don't */
+  /* go through the process of deregistering and registering the handler. */
+  /* Additionally, this avoids pending signals getting lost in the (small) */
+  /* time frame that handle->signum == 0. */
+  if (signum == handle->signum) {
+    handle->signal_cb = signal_cb;
+    return 0;
+  }
+
+  /* If the signal handler was already active, stop it first. */
+  if (handle->signum != 0) {
+    int r = uv_signal_stop(handle);
+    /* uv_signal_stop is infallible. */
+    assert(r == 0);
+  }
+
+  EnterCriticalSection(&uv__signal_lock);
+
+  err = uv__signal_register(signum);
+  if (err) {
+    /* Uh-oh, didn't work. */
+    LeaveCriticalSection(&uv__signal_lock);
+    return uv_translate_sys_error(err);
+  }
+
+  handle->signum = signum;
+  RB_INSERT(uv_signal_tree_s, &uv__signal_tree, handle);
+
+  LeaveCriticalSection(&uv__signal_lock);
+
+  handle->signal_cb = signal_cb;
+  uv__handle_start(handle);
+
+  return 0;
+}
+
+
+void uv_process_signal_req(uv_loop_t* loop, uv_signal_t* handle,
+    uv_req_t* req) {
+  long dispatched_signum;
+
+  assert(handle->type == UV_SIGNAL);
+  assert(req->type == UV_SIGNAL_REQ);
+
+  dispatched_signum = InterlockedExchange(
+          (volatile LONG*) &handle->pending_signum, 0);
+  assert(dispatched_signum != 0);
+
+  /* Check if the pending signal equals the signum that we are watching for. */
+  /* These can get out of sync when the handler is stopped and restarted */
+  /* while the signal_req is pending. */
+  if (dispatched_signum == handle->signum)
+    handle->signal_cb(handle, dispatched_signum);
+
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    /* When it is closing, it must be stopped at this point. */
+    assert(handle->signum == 0);
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+}
+
+
+void uv_signal_close(uv_loop_t* loop, uv_signal_t* handle) {
+  uv_signal_stop(handle);
+  uv__handle_closing(handle);
+
+  if (handle->pending_signum == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+}
+
+
+void uv_signal_endgame(uv_loop_t* loop, uv_signal_t* handle) {
+  assert(handle->flags & UV__HANDLE_CLOSING);
+  assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+  assert(handle->signum == 0);
+  assert(handle->pending_signum == 0);
+
+  handle->flags |= UV_HANDLE_CLOSED;
+
+  uv__handle_close(handle);
+}
diff --git a/Utilities/cmlibuv/src/win/snprintf.c b/Utilities/cmlibuv/src/win/snprintf.c
new file mode 100644
index 0000000..776c0e3
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/snprintf.c
@@ -0,0 +1,42 @@
+/* Copyright the 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.
+ */
+
+#if defined(_MSC_VER) && _MSC_VER < 1900
+
+#include <stdio.h>
+#include <stdarg.h>
+
+/* Emulate snprintf() on MSVC<2015, _snprintf() doesn't zero-terminate the buffer
+ * on overflow...
+ */
+int snprintf(char* buf, size_t len, const char* fmt, ...) {
+  int n;
+  va_list ap;
+  va_start(ap, fmt);
+
+  n = _vscprintf(fmt, ap);
+  vsnprintf_s(buf, len, _TRUNCATE, fmt, ap);
+
+  va_end(ap);
+  return n;
+}
+
+#endif
diff --git a/Utilities/cmlibuv/src/win/stream-inl.h b/Utilities/cmlibuv/src/win/stream-inl.h
new file mode 100644
index 0000000..b7a3c11
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/stream-inl.h
@@ -0,0 +1,56 @@
+/* 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_WIN_STREAM_INL_H_
+#define UV_WIN_STREAM_INL_H_
+
+#include <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+INLINE static void uv_stream_init(uv_loop_t* loop,
+                                  uv_stream_t* handle,
+                                  uv_handle_type type) {
+  uv__handle_init(loop, (uv_handle_t*) handle, type);
+  handle->write_queue_size = 0;
+  handle->activecnt = 0;
+}
+
+
+INLINE static void uv_connection_init(uv_stream_t* handle) {
+  handle->flags |= UV_HANDLE_CONNECTION;
+  handle->stream.conn.write_reqs_pending = 0;
+
+  uv_req_init(handle->loop, (uv_req_t*) &(handle->read_req));
+  handle->read_req.event_handle = NULL;
+  handle->read_req.wait_handle = INVALID_HANDLE_VALUE;
+  handle->read_req.type = UV_READ;
+  handle->read_req.data = handle;
+
+  handle->stream.conn.shutdown_req = NULL;
+}
+
+
+#endif /* UV_WIN_STREAM_INL_H_ */
diff --git a/Utilities/cmlibuv/src/win/stream.c b/Utilities/cmlibuv/src/win/stream.c
new file mode 100644
index 0000000..a2466e5
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/stream.c
@@ -0,0 +1,249 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "req-inl.h"
+
+
+int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) {
+  int err;
+
+  err = ERROR_INVALID_PARAMETER;
+  switch (stream->type) {
+    case UV_TCP:
+      err = uv_tcp_listen((uv_tcp_t*)stream, backlog, cb);
+      break;
+    case UV_NAMED_PIPE:
+      err = uv_pipe_listen((uv_pipe_t*)stream, backlog, cb);
+      break;
+    default:
+      assert(0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_accept(uv_stream_t* server, uv_stream_t* client) {
+  int err;
+
+  err = ERROR_INVALID_PARAMETER;
+  switch (server->type) {
+    case UV_TCP:
+      err = uv_tcp_accept((uv_tcp_t*)server, (uv_tcp_t*)client);
+      break;
+    case UV_NAMED_PIPE:
+      err = uv_pipe_accept((uv_pipe_t*)server, client);
+      break;
+    default:
+      assert(0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_read_start(uv_stream_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb) {
+  int err;
+
+  if (handle->flags & UV_HANDLE_READING) {
+    return UV_EALREADY;
+  }
+
+  if (!(handle->flags & UV_HANDLE_READABLE)) {
+    return UV_ENOTCONN;
+  }
+
+  err = ERROR_INVALID_PARAMETER;
+  switch (handle->type) {
+    case UV_TCP:
+      err = uv_tcp_read_start((uv_tcp_t*)handle, alloc_cb, read_cb);
+      break;
+    case UV_NAMED_PIPE:
+      err = uv_pipe_read_start((uv_pipe_t*)handle, alloc_cb, read_cb);
+      break;
+    case UV_TTY:
+      err = uv_tty_read_start((uv_tty_t*) handle, alloc_cb, read_cb);
+      break;
+    default:
+      assert(0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_read_stop(uv_stream_t* handle) {
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_READING))
+    return 0;
+
+  err = 0;
+  if (handle->type == UV_TTY) {
+    err = uv_tty_read_stop((uv_tty_t*) handle);
+  } else {
+    if (handle->type == UV_NAMED_PIPE) {
+      uv__pipe_stop_read((uv_pipe_t*) handle);
+    } else {
+      handle->flags &= ~UV_HANDLE_READING;
+    }
+    DECREASE_ACTIVE_COUNT(handle->loop, handle);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_write(uv_write_t* req,
+             uv_stream_t* handle,
+             const uv_buf_t bufs[],
+             unsigned int nbufs,
+             uv_write_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_WRITABLE)) {
+    return UV_EPIPE;
+  }
+
+  err = ERROR_INVALID_PARAMETER;
+  switch (handle->type) {
+    case UV_TCP:
+      err = uv_tcp_write(loop, req, (uv_tcp_t*) handle, bufs, nbufs, cb);
+      break;
+    case UV_NAMED_PIPE:
+      err = uv_pipe_write(loop, req, (uv_pipe_t*) handle, bufs, nbufs, cb);
+      break;
+    case UV_TTY:
+      err = uv_tty_write(loop, req, (uv_tty_t*) handle, bufs, nbufs, cb);
+      break;
+    default:
+      assert(0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_write2(uv_write_t* req,
+              uv_stream_t* handle,
+              const uv_buf_t bufs[],
+              unsigned int nbufs,
+              uv_stream_t* send_handle,
+              uv_write_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_WRITABLE)) {
+    return UV_EPIPE;
+  }
+
+  err = ERROR_INVALID_PARAMETER;
+  switch (handle->type) {
+    case UV_NAMED_PIPE:
+      err = uv_pipe_write2(loop,
+                           req,
+                           (uv_pipe_t*) handle,
+                           bufs,
+                           nbufs,
+                           send_handle,
+                           cb);
+      break;
+    default:
+      assert(0);
+  }
+
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_try_write(uv_stream_t* stream,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs) {
+  if (stream->flags & UV__HANDLE_CLOSING)
+    return UV_EBADF;
+  if (!(stream->flags & UV_HANDLE_WRITABLE))
+    return UV_EPIPE;
+
+  switch (stream->type) {
+    case UV_TCP:
+      return uv__tcp_try_write((uv_tcp_t*) stream, bufs, nbufs);
+    case UV_TTY:
+      return uv__tty_try_write((uv_tty_t*) stream, bufs, nbufs);
+    case UV_NAMED_PIPE:
+      return UV_EAGAIN;
+    default:
+      assert(0);
+      return UV_ENOSYS;
+  }
+}
+
+
+int uv_shutdown(uv_shutdown_t* req, uv_stream_t* handle, uv_shutdown_cb cb) {
+  uv_loop_t* loop = handle->loop;
+
+  if (!(handle->flags & UV_HANDLE_WRITABLE)) {
+    return UV_EPIPE;
+  }
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_SHUTDOWN;
+  req->handle = handle;
+  req->cb = cb;
+
+  handle->flags &= ~UV_HANDLE_WRITABLE;
+  handle->stream.conn.shutdown_req = req;
+  handle->reqs_pending++;
+  REGISTER_HANDLE_REQ(loop, handle, req);
+
+  uv_want_endgame(loop, (uv_handle_t*)handle);
+
+  return 0;
+}
+
+
+int uv_is_readable(const uv_stream_t* handle) {
+  return !!(handle->flags & UV_HANDLE_READABLE);
+}
+
+
+int uv_is_writable(const uv_stream_t* handle) {
+  return !!(handle->flags & UV_HANDLE_WRITABLE);
+}
+
+
+int uv_stream_set_blocking(uv_stream_t* handle, int blocking) {
+  if (handle->type != UV_NAMED_PIPE)
+    return UV_EINVAL;
+
+  if (blocking != 0)
+    handle->flags |= UV_HANDLE_BLOCKING_WRITES;
+  else
+    handle->flags &= ~UV_HANDLE_BLOCKING_WRITES;
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/win/tcp.c b/Utilities/cmlibuv/src/win/tcp.c
new file mode 100644
index 0000000..0709696
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/tcp.c
@@ -0,0 +1,1510 @@
+/* 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 <assert.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "stream-inl.h"
+#include "req-inl.h"
+
+
+/*
+ * Threshold of active tcp streams for which to preallocate tcp read buffers.
+ * (Due to node slab allocator performing poorly under this pattern,
+ *  the optimization is temporarily disabled (threshold=0).  This will be
+ *  revisited once node allocator is improved.)
+ */
+const unsigned int uv_active_tcp_streams_threshold = 0;
+
+/*
+ * Number of simultaneous pending AcceptEx calls.
+ */
+const unsigned int uv_simultaneous_server_accepts = 32;
+
+/* A zero-size buffer for use by uv_tcp_read */
+static char uv_zero_[] = "";
+
+static int uv__tcp_nodelay(uv_tcp_t* handle, SOCKET socket, int enable) {
+  if (setsockopt(socket,
+                 IPPROTO_TCP,
+                 TCP_NODELAY,
+                 (const char*)&enable,
+                 sizeof enable) == -1) {
+    return WSAGetLastError();
+  }
+  return 0;
+}
+
+
+static int uv__tcp_keepalive(uv_tcp_t* handle, SOCKET socket, int enable, unsigned int delay) {
+  if (setsockopt(socket,
+                 SOL_SOCKET,
+                 SO_KEEPALIVE,
+                 (const char*)&enable,
+                 sizeof enable) == -1) {
+    return WSAGetLastError();
+  }
+
+  if (enable && setsockopt(socket,
+                           IPPROTO_TCP,
+                           TCP_KEEPALIVE,
+                           (const char*)&delay,
+                           sizeof delay) == -1) {
+    return WSAGetLastError();
+  }
+
+  return 0;
+}
+
+
+static int uv_tcp_set_socket(uv_loop_t* loop,
+                             uv_tcp_t* handle,
+                             SOCKET socket,
+                             int family,
+                             int imported) {
+  DWORD yes = 1;
+  int non_ifs_lsp;
+  int err;
+
+  if (handle->socket != INVALID_SOCKET)
+    return UV_EBUSY;
+
+  /* Set the socket to nonblocking mode */
+  if (ioctlsocket(socket, FIONBIO, &yes) == SOCKET_ERROR) {
+    return WSAGetLastError();
+  }
+
+  /* Make the socket non-inheritable */
+  if (!SetHandleInformation((HANDLE) socket, HANDLE_FLAG_INHERIT, 0))
+    return GetLastError();
+
+  /* Associate it with the I/O completion port. */
+  /* Use uv_handle_t pointer as completion key. */
+  if (CreateIoCompletionPort((HANDLE)socket,
+                             loop->iocp,
+                             (ULONG_PTR)socket,
+                             0) == NULL) {
+    if (imported) {
+      handle->flags |= UV_HANDLE_EMULATE_IOCP;
+    } else {
+      return GetLastError();
+    }
+  }
+
+  if (family == AF_INET6) {
+    non_ifs_lsp = uv_tcp_non_ifs_lsp_ipv6;
+  } else {
+    non_ifs_lsp = uv_tcp_non_ifs_lsp_ipv4;
+  }
+
+  if (pSetFileCompletionNotificationModes &&
+      !(handle->flags & UV_HANDLE_EMULATE_IOCP) && !non_ifs_lsp) {
+    if (pSetFileCompletionNotificationModes((HANDLE) socket,
+        FILE_SKIP_SET_EVENT_ON_HANDLE |
+        FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)) {
+      handle->flags |= UV_HANDLE_SYNC_BYPASS_IOCP;
+    } else if (GetLastError() != ERROR_INVALID_FUNCTION) {
+      return GetLastError();
+    }
+  }
+
+  if (handle->flags & UV_HANDLE_TCP_NODELAY) {
+    err = uv__tcp_nodelay(handle, socket, 1);
+    if (err)
+      return err;
+  }
+
+  /* TODO: Use stored delay. */
+  if (handle->flags & UV_HANDLE_TCP_KEEPALIVE) {
+    err = uv__tcp_keepalive(handle, socket, 1, 60);
+    if (err)
+      return err;
+  }
+
+  handle->socket = socket;
+
+  if (family == AF_INET6) {
+    handle->flags |= UV_HANDLE_IPV6;
+  } else {
+    assert(!(handle->flags & UV_HANDLE_IPV6));
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_init_ex(uv_loop_t* loop, uv_tcp_t* handle, unsigned int flags) {
+  int domain;
+
+  /* Use the lower 8 bits for the domain */
+  domain = flags & 0xFF;
+  if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNSPEC)
+    return UV_EINVAL;
+
+  if (flags & ~0xFF)
+    return UV_EINVAL;
+
+  uv_stream_init(loop, (uv_stream_t*) handle, UV_TCP);
+  handle->tcp.serv.accept_reqs = NULL;
+  handle->tcp.serv.pending_accepts = NULL;
+  handle->socket = INVALID_SOCKET;
+  handle->reqs_pending = 0;
+  handle->tcp.serv.func_acceptex = NULL;
+  handle->tcp.conn.func_connectex = NULL;
+  handle->tcp.serv.processed_accepts = 0;
+  handle->delayed_error = 0;
+
+  /* If anything fails beyond this point we need to remove the handle from
+   * the handle queue, since it was added by uv__handle_init in uv_stream_init.
+   */
+
+  if (domain != AF_UNSPEC) {
+    SOCKET sock;
+    DWORD err;
+
+    sock = socket(domain, SOCK_STREAM, 0);
+    if (sock == INVALID_SOCKET) {
+      err = WSAGetLastError();
+      QUEUE_REMOVE(&handle->handle_queue);
+      return uv_translate_sys_error(err);
+    }
+
+    err = uv_tcp_set_socket(handle->loop, handle, sock, domain, 0);
+    if (err) {
+      closesocket(sock);
+      QUEUE_REMOVE(&handle->handle_queue);
+      return uv_translate_sys_error(err);
+    }
+
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_init(uv_loop_t* loop, uv_tcp_t* handle) {
+  return uv_tcp_init_ex(loop, handle, AF_UNSPEC);
+}
+
+
+void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) {
+  int err;
+  unsigned int i;
+  uv_tcp_accept_t* req;
+
+  if (handle->flags & UV_HANDLE_CONNECTION &&
+      handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+
+    UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req);
+
+    err = 0;
+    if (handle->flags & UV__HANDLE_CLOSING) {
+      err = ERROR_OPERATION_ABORTED;
+    } else if (shutdown(handle->socket, SD_SEND) == SOCKET_ERROR) {
+      err = WSAGetLastError();
+    }
+
+    if (handle->stream.conn.shutdown_req->cb) {
+      handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req,
+                               uv_translate_sys_error(err));
+    }
+
+    handle->stream.conn.shutdown_req = NULL;
+    DECREASE_PENDING_REQ_COUNT(handle);
+    return;
+  }
+
+  if (handle->flags & UV__HANDLE_CLOSING &&
+      handle->reqs_pending == 0) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+
+    if (!(handle->flags & UV_HANDLE_TCP_SOCKET_CLOSED)) {
+      closesocket(handle->socket);
+      handle->socket = INVALID_SOCKET;
+      handle->flags |= UV_HANDLE_TCP_SOCKET_CLOSED;
+    }
+
+    if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->tcp.serv.accept_reqs) {
+      if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+        for (i = 0; i < uv_simultaneous_server_accepts; i++) {
+          req = &handle->tcp.serv.accept_reqs[i];
+          if (req->wait_handle != INVALID_HANDLE_VALUE) {
+            UnregisterWait(req->wait_handle);
+            req->wait_handle = INVALID_HANDLE_VALUE;
+          }
+          if (req->event_handle) {
+            CloseHandle(req->event_handle);
+            req->event_handle = NULL;
+          }
+        }
+      }
+
+      uv__free(handle->tcp.serv.accept_reqs);
+      handle->tcp.serv.accept_reqs = NULL;
+    }
+
+    if (handle->flags & UV_HANDLE_CONNECTION &&
+        handle->flags & UV_HANDLE_EMULATE_IOCP) {
+      if (handle->read_req.wait_handle != INVALID_HANDLE_VALUE) {
+        UnregisterWait(handle->read_req.wait_handle);
+        handle->read_req.wait_handle = INVALID_HANDLE_VALUE;
+      }
+      if (handle->read_req.event_handle) {
+        CloseHandle(handle->read_req.event_handle);
+        handle->read_req.event_handle = NULL;
+      }
+    }
+
+    uv__handle_close(handle);
+    loop->active_tcp_streams--;
+  }
+}
+
+
+/* Unlike on Unix, here we don't set SO_REUSEADDR, because it doesn't just
+ * allow binding to addresses that are in use by sockets in TIME_WAIT, it
+ * effectively allows 'stealing' a port which is in use by another application.
+ *
+ * SO_EXCLUSIVEADDRUSE is also not good here because it does check all sockets,
+ * regardless of state, so we'd get an error even if the port is in use by a
+ * socket in TIME_WAIT state.
+ *
+ * See issue #1360.
+ *
+ */
+static int uv_tcp_try_bind(uv_tcp_t* handle,
+                           const struct sockaddr* addr,
+                           unsigned int addrlen,
+                           unsigned int flags) {
+  DWORD err;
+  int r;
+
+  if (handle->socket == INVALID_SOCKET) {
+    SOCKET sock;
+
+    /* Cannot set IPv6-only mode on non-IPv6 socket. */
+    if ((flags & UV_TCP_IPV6ONLY) && addr->sa_family != AF_INET6)
+      return ERROR_INVALID_PARAMETER;
+
+    sock = socket(addr->sa_family, SOCK_STREAM, 0);
+    if (sock == INVALID_SOCKET) {
+      return WSAGetLastError();
+    }
+
+    err = uv_tcp_set_socket(handle->loop, handle, sock, addr->sa_family, 0);
+    if (err) {
+      closesocket(sock);
+      return err;
+    }
+  }
+
+#ifdef IPV6_V6ONLY
+  if (addr->sa_family == AF_INET6) {
+    int on;
+
+    on = (flags & UV_TCP_IPV6ONLY) != 0;
+
+    /* TODO: how to handle errors? This may fail if there is no ipv4 stack */
+    /* available, or when run on XP/2003 which have no support for dualstack */
+    /* sockets. For now we're silently ignoring the error. */
+    setsockopt(handle->socket,
+               IPPROTO_IPV6,
+               IPV6_V6ONLY,
+               (const char*)&on,
+               sizeof on);
+  }
+#endif
+
+  r = bind(handle->socket, addr, addrlen);
+
+  if (r == SOCKET_ERROR) {
+    err = WSAGetLastError();
+    if (err == WSAEADDRINUSE) {
+      /* Some errors are not to be reported until connect() or listen() */
+      handle->delayed_error = err;
+    } else {
+      return err;
+    }
+  }
+
+  handle->flags |= UV_HANDLE_BOUND;
+
+  return 0;
+}
+
+
+static void CALLBACK post_completion(void* context, BOOLEAN timed_out) {
+  uv_req_t* req;
+  uv_tcp_t* handle;
+
+  req = (uv_req_t*) context;
+  assert(req != NULL);
+  handle = (uv_tcp_t*)req->data;
+  assert(handle != NULL);
+  assert(!timed_out);
+
+  if (!PostQueuedCompletionStatus(handle->loop->iocp,
+                                  req->u.io.overlapped.InternalHigh,
+                                  0,
+                                  &req->u.io.overlapped)) {
+    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");
+  }
+}
+
+
+static void CALLBACK post_write_completion(void* context, BOOLEAN timed_out) {
+  uv_write_t* req;
+  uv_tcp_t* handle;
+
+  req = (uv_write_t*) context;
+  assert(req != NULL);
+  handle = (uv_tcp_t*)req->handle;
+  assert(handle != NULL);
+  assert(!timed_out);
+
+  if (!PostQueuedCompletionStatus(handle->loop->iocp,
+                                  req->u.io.overlapped.InternalHigh,
+                                  0,
+                                  &req->u.io.overlapped)) {
+    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");
+  }
+}
+
+
+static void uv_tcp_queue_accept(uv_tcp_t* handle, uv_tcp_accept_t* req) {
+  uv_loop_t* loop = handle->loop;
+  BOOL success;
+  DWORD bytes;
+  SOCKET accept_socket;
+  short family;
+
+  assert(handle->flags & UV_HANDLE_LISTENING);
+  assert(req->accept_socket == INVALID_SOCKET);
+
+  /* choose family and extension function */
+  if (handle->flags & UV_HANDLE_IPV6) {
+    family = AF_INET6;
+  } else {
+    family = AF_INET;
+  }
+
+  /* Open a socket for the accepted connection. */
+  accept_socket = socket(family, SOCK_STREAM, 0);
+  if (accept_socket == INVALID_SOCKET) {
+    SET_REQ_ERROR(req, WSAGetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+    handle->reqs_pending++;
+    return;
+  }
+
+  /* Make the socket non-inheritable */
+  if (!SetHandleInformation((HANDLE) accept_socket, HANDLE_FLAG_INHERIT, 0)) {
+    SET_REQ_ERROR(req, GetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+    handle->reqs_pending++;
+    closesocket(accept_socket);
+    return;
+  }
+
+  /* Prepare the overlapped structure. */
+  memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped));
+  if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+    req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1);
+  }
+
+  success = handle->tcp.serv.func_acceptex(handle->socket,
+                                          accept_socket,
+                                          (void*)req->accept_buffer,
+                                          0,
+                                          sizeof(struct sockaddr_storage),
+                                          sizeof(struct sockaddr_storage),
+                                          &bytes,
+                                          &req->u.io.overlapped);
+
+  if (UV_SUCCEEDED_WITHOUT_IOCP(success)) {
+    /* Process the req without IOCP. */
+    req->accept_socket = accept_socket;
+    handle->reqs_pending++;
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  } else if (UV_SUCCEEDED_WITH_IOCP(success)) {
+    /* The req will be processed with IOCP. */
+    req->accept_socket = accept_socket;
+    handle->reqs_pending++;
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP &&
+        req->wait_handle == INVALID_HANDLE_VALUE &&
+        !RegisterWaitForSingleObject(&req->wait_handle,
+          req->event_handle, post_completion, (void*) req,
+          INFINITE, WT_EXECUTEINWAITTHREAD)) {
+      SET_REQ_ERROR(req, GetLastError());
+      uv_insert_pending_req(loop, (uv_req_t*)req);
+      handle->reqs_pending++;
+      return;
+    }
+  } else {
+    /* Make this req pending reporting an error. */
+    SET_REQ_ERROR(req, WSAGetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+    handle->reqs_pending++;
+    /* Destroy the preallocated client socket. */
+    closesocket(accept_socket);
+    /* Destroy the event handle */
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+      CloseHandle(req->u.io.overlapped.hEvent);
+      req->event_handle = NULL;
+    }
+  }
+}
+
+
+static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) {
+  uv_read_t* req;
+  uv_buf_t buf;
+  int result;
+  DWORD bytes, flags;
+
+  assert(handle->flags & UV_HANDLE_READING);
+  assert(!(handle->flags & UV_HANDLE_READ_PENDING));
+
+  req = &handle->read_req;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  /*
+   * Preallocate a read buffer if the number of active streams is below
+   * the threshold.
+  */
+  if (loop->active_tcp_streams < uv_active_tcp_streams_threshold) {
+    handle->flags &= ~UV_HANDLE_ZERO_READ;
+    handle->tcp.conn.read_buffer = uv_buf_init(NULL, 0);
+    handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->tcp.conn.read_buffer);
+    if (handle->tcp.conn.read_buffer.base == NULL ||
+        handle->tcp.conn.read_buffer.len == 0) {
+      handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &handle->tcp.conn.read_buffer);
+      return;
+    }
+    assert(handle->tcp.conn.read_buffer.base != NULL);
+    buf = handle->tcp.conn.read_buffer;
+  } else {
+    handle->flags |= UV_HANDLE_ZERO_READ;
+    buf.base = (char*) &uv_zero_;
+    buf.len = 0;
+  }
+
+  /* Prepare the overlapped structure. */
+  memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped));
+  if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+    assert(req->event_handle);
+    req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1);
+  }
+
+  flags = 0;
+  result = WSARecv(handle->socket,
+                   (WSABUF*)&buf,
+                   1,
+                   &bytes,
+                   &flags,
+                   &req->u.io.overlapped,
+                   NULL);
+
+  if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
+    /* Process the req without IOCP. */
+    handle->flags |= UV_HANDLE_READ_PENDING;
+    req->u.io.overlapped.InternalHigh = bytes;
+    handle->reqs_pending++;
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
+    /* The req will be processed with IOCP. */
+    handle->flags |= UV_HANDLE_READ_PENDING;
+    handle->reqs_pending++;
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP &&
+        req->wait_handle == INVALID_HANDLE_VALUE &&
+        !RegisterWaitForSingleObject(&req->wait_handle,
+          req->event_handle, post_completion, (void*) req,
+          INFINITE, WT_EXECUTEINWAITTHREAD)) {
+      SET_REQ_ERROR(req, GetLastError());
+      uv_insert_pending_req(loop, (uv_req_t*)req);
+    }
+  } else {
+    /* Make this req pending reporting an error. */
+    SET_REQ_ERROR(req, WSAGetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+    handle->reqs_pending++;
+  }
+}
+
+
+int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  unsigned int i, simultaneous_accepts;
+  uv_tcp_accept_t* req;
+  int err;
+
+  assert(backlog > 0);
+
+  if (handle->flags & UV_HANDLE_LISTENING) {
+    handle->stream.serv.connection_cb = cb;
+  }
+
+  if (handle->flags & UV_HANDLE_READING) {
+    return WSAEISCONN;
+  }
+
+  if (handle->delayed_error) {
+    return handle->delayed_error;
+  }
+
+  if (!(handle->flags & UV_HANDLE_BOUND)) {
+    err = uv_tcp_try_bind(handle,
+                          (const struct sockaddr*) &uv_addr_ip4_any_,
+                          sizeof(uv_addr_ip4_any_),
+                          0);
+    if (err)
+      return err;
+    if (handle->delayed_error)
+      return handle->delayed_error;
+  }
+
+  if (!handle->tcp.serv.func_acceptex) {
+    if (!uv_get_acceptex_function(handle->socket, &handle->tcp.serv.func_acceptex)) {
+      return WSAEAFNOSUPPORT;
+    }
+  }
+
+  if (!(handle->flags & UV_HANDLE_SHARED_TCP_SOCKET) &&
+      listen(handle->socket, backlog) == SOCKET_ERROR) {
+    return WSAGetLastError();
+  }
+
+  handle->flags |= UV_HANDLE_LISTENING;
+  handle->stream.serv.connection_cb = cb;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+
+  simultaneous_accepts = handle->flags & UV_HANDLE_TCP_SINGLE_ACCEPT ? 1
+    : uv_simultaneous_server_accepts;
+
+  if(!handle->tcp.serv.accept_reqs) {
+    handle->tcp.serv.accept_reqs = (uv_tcp_accept_t*)
+      uv__malloc(uv_simultaneous_server_accepts * sizeof(uv_tcp_accept_t));
+    if (!handle->tcp.serv.accept_reqs) {
+      uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+    }
+
+    for (i = 0; i < simultaneous_accepts; i++) {
+      req = &handle->tcp.serv.accept_reqs[i];
+      uv_req_init(loop, (uv_req_t*)req);
+      req->type = UV_ACCEPT;
+      req->accept_socket = INVALID_SOCKET;
+      req->data = handle;
+
+      req->wait_handle = INVALID_HANDLE_VALUE;
+      if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+        req->event_handle = CreateEvent(NULL, 0, 0, NULL);
+        if (!req->event_handle) {
+          uv_fatal_error(GetLastError(), "CreateEvent");
+        }
+      } else {
+        req->event_handle = NULL;
+      }
+
+      uv_tcp_queue_accept(handle, req);
+    }
+
+    /* Initialize other unused requests too, because uv_tcp_endgame */
+    /* doesn't know how how many requests were initialized, so it will */
+    /* try to clean up {uv_simultaneous_server_accepts} requests. */
+    for (i = simultaneous_accepts; i < uv_simultaneous_server_accepts; i++) {
+      req = &handle->tcp.serv.accept_reqs[i];
+      uv_req_init(loop, (uv_req_t*) req);
+      req->type = UV_ACCEPT;
+      req->accept_socket = INVALID_SOCKET;
+      req->data = handle;
+      req->wait_handle = INVALID_HANDLE_VALUE;
+      req->event_handle = NULL;
+    }
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) {
+  uv_loop_t* loop = server->loop;
+  int err = 0;
+  int family;
+
+  uv_tcp_accept_t* req = server->tcp.serv.pending_accepts;
+
+  if (!req) {
+    /* No valid connections found, so we error out. */
+    return WSAEWOULDBLOCK;
+  }
+
+  if (req->accept_socket == INVALID_SOCKET) {
+    return WSAENOTCONN;
+  }
+
+  if (server->flags & UV_HANDLE_IPV6) {
+    family = AF_INET6;
+  } else {
+    family = AF_INET;
+  }
+
+  err = uv_tcp_set_socket(client->loop,
+                          client,
+                          req->accept_socket,
+                          family,
+                          0);
+  if (err) {
+    closesocket(req->accept_socket);
+  } else {
+    uv_connection_init((uv_stream_t*) client);
+    /* AcceptEx() implicitly binds the accepted socket. */
+    client->flags |= UV_HANDLE_BOUND | UV_HANDLE_READABLE | UV_HANDLE_WRITABLE;
+  }
+
+  /* Prepare the req to pick up a new connection */
+  server->tcp.serv.pending_accepts = req->next_pending;
+  req->next_pending = NULL;
+  req->accept_socket = INVALID_SOCKET;
+
+  if (!(server->flags & UV__HANDLE_CLOSING)) {
+    /* Check if we're in a middle of changing the number of pending accepts. */
+    if (!(server->flags & UV_HANDLE_TCP_ACCEPT_STATE_CHANGING)) {
+      uv_tcp_queue_accept(server, req);
+    } else {
+      /* We better be switching to a single pending accept. */
+      assert(server->flags & UV_HANDLE_TCP_SINGLE_ACCEPT);
+
+      server->tcp.serv.processed_accepts++;
+
+      if (server->tcp.serv.processed_accepts >= uv_simultaneous_server_accepts) {
+        server->tcp.serv.processed_accepts = 0;
+        /*
+         * All previously queued accept requests are now processed.
+         * We now switch to queueing just a single accept.
+         */
+        uv_tcp_queue_accept(server, &server->tcp.serv.accept_reqs[0]);
+        server->flags &= ~UV_HANDLE_TCP_ACCEPT_STATE_CHANGING;
+        server->flags |= UV_HANDLE_TCP_SINGLE_ACCEPT;
+      }
+    }
+  }
+
+  loop->active_tcp_streams++;
+
+  return err;
+}
+
+
+int uv_tcp_read_start(uv_tcp_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb) {
+  uv_loop_t* loop = handle->loop;
+
+  handle->flags |= UV_HANDLE_READING;
+  handle->read_cb = read_cb;
+  handle->alloc_cb = alloc_cb;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+
+  /* If reading was stopped and then started again, there could still be a */
+  /* read request pending. */
+  if (!(handle->flags & UV_HANDLE_READ_PENDING)) {
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP &&
+        !handle->read_req.event_handle) {
+      handle->read_req.event_handle = CreateEvent(NULL, 0, 0, NULL);
+      if (!handle->read_req.event_handle) {
+        uv_fatal_error(GetLastError(), "CreateEvent");
+      }
+    }
+    uv_tcp_queue_read(loop, handle);
+  }
+
+  return 0;
+}
+
+
+static int uv_tcp_try_connect(uv_connect_t* req,
+                              uv_tcp_t* handle,
+                              const struct sockaddr* addr,
+                              unsigned int addrlen,
+                              uv_connect_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  const struct sockaddr* bind_addr;
+  BOOL success;
+  DWORD bytes;
+  int err;
+
+  if (handle->delayed_error) {
+    return handle->delayed_error;
+  }
+
+  if (!(handle->flags & UV_HANDLE_BOUND)) {
+    if (addrlen == sizeof(uv_addr_ip4_any_)) {
+      bind_addr = (const struct sockaddr*) &uv_addr_ip4_any_;
+    } else if (addrlen == sizeof(uv_addr_ip6_any_)) {
+      bind_addr = (const struct sockaddr*) &uv_addr_ip6_any_;
+    } else {
+      abort();
+    }
+    err = uv_tcp_try_bind(handle, bind_addr, addrlen, 0);
+    if (err)
+      return err;
+    if (handle->delayed_error)
+      return handle->delayed_error;
+  }
+
+  if (!handle->tcp.conn.func_connectex) {
+    if (!uv_get_connectex_function(handle->socket, &handle->tcp.conn.func_connectex)) {
+      return WSAEAFNOSUPPORT;
+    }
+  }
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_CONNECT;
+  req->handle = (uv_stream_t*) handle;
+  req->cb = cb;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  success = handle->tcp.conn.func_connectex(handle->socket,
+                                           addr,
+                                           addrlen,
+                                           NULL,
+                                           0,
+                                           &bytes,
+                                           &req->u.io.overlapped);
+
+  if (UV_SUCCEEDED_WITHOUT_IOCP(success)) {
+    /* Process the req without IOCP. */
+    handle->reqs_pending++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  } else if (UV_SUCCEEDED_WITH_IOCP(success)) {
+    /* The req will be processed with IOCP. */
+    handle->reqs_pending++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+  } else {
+    return WSAGetLastError();
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_getsockname(const uv_tcp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  int result;
+
+  if (handle->socket == INVALID_SOCKET) {
+    return UV_EINVAL;
+  }
+
+  if (handle->delayed_error) {
+    return uv_translate_sys_error(handle->delayed_error);
+  }
+
+  result = getsockname(handle->socket, name, namelen);
+  if (result != 0) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_getpeername(const uv_tcp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  int result;
+
+  if (handle->socket == INVALID_SOCKET) {
+    return UV_EINVAL;
+  }
+
+  if (handle->delayed_error) {
+    return uv_translate_sys_error(handle->delayed_error);
+  }
+
+  result = getpeername(handle->socket, name, namelen);
+  if (result != 0) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_write(uv_loop_t* loop,
+                 uv_write_t* req,
+                 uv_tcp_t* handle,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs,
+                 uv_write_cb cb) {
+  int result;
+  DWORD bytes;
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_WRITE;
+  req->handle = (uv_stream_t*) handle;
+  req->cb = cb;
+
+  /* Prepare the overlapped structure. */
+  memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped));
+  if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+    req->event_handle = CreateEvent(NULL, 0, 0, NULL);
+    if (!req->event_handle) {
+      uv_fatal_error(GetLastError(), "CreateEvent");
+    }
+    req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1);
+    req->wait_handle = INVALID_HANDLE_VALUE;
+  }
+
+  result = WSASend(handle->socket,
+                   (WSABUF*) bufs,
+                   nbufs,
+                   &bytes,
+                   0,
+                   &req->u.io.overlapped,
+                   NULL);
+
+  if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
+    /* Request completed immediately. */
+    req->u.io.queued_bytes = 0;
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    uv_insert_pending_req(loop, (uv_req_t*) req);
+  } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
+    /* Request queued by the kernel. */
+    req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs);
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    handle->write_queue_size += req->u.io.queued_bytes;
+    if (handle->flags & UV_HANDLE_EMULATE_IOCP &&
+        !RegisterWaitForSingleObject(&req->wait_handle,
+          req->event_handle, post_write_completion, (void*) req,
+          INFINITE, WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE)) {
+      SET_REQ_ERROR(req, GetLastError());
+      uv_insert_pending_req(loop, (uv_req_t*)req);
+    }
+  } else {
+    /* Send failed due to an error, report it later */
+    req->u.io.queued_bytes = 0;
+    handle->reqs_pending++;
+    handle->stream.conn.write_reqs_pending++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    SET_REQ_ERROR(req, WSAGetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*) req);
+  }
+
+  return 0;
+}
+
+
+int uv__tcp_try_write(uv_tcp_t* handle,
+                     const uv_buf_t bufs[],
+                     unsigned int nbufs) {
+  int result;
+  DWORD bytes;
+
+  if (handle->stream.conn.write_reqs_pending > 0)
+    return UV_EAGAIN;
+
+  result = WSASend(handle->socket,
+                   (WSABUF*) bufs,
+                   nbufs,
+                   &bytes,
+                   0,
+                   NULL,
+                   NULL);
+
+  if (result == SOCKET_ERROR)
+    return uv_translate_sys_error(WSAGetLastError());
+  else
+    return bytes;
+}
+
+
+void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_req_t* req) {
+  DWORD bytes, flags, err;
+  uv_buf_t buf;
+
+  assert(handle->type == UV_TCP);
+
+  handle->flags &= ~UV_HANDLE_READ_PENDING;
+
+  if (!REQ_SUCCESS(req)) {
+    /* An error occurred doing the read. */
+    if ((handle->flags & UV_HANDLE_READING) ||
+        !(handle->flags & UV_HANDLE_ZERO_READ)) {
+      handle->flags &= ~UV_HANDLE_READING;
+      DECREASE_ACTIVE_COUNT(loop, handle);
+      buf = (handle->flags & UV_HANDLE_ZERO_READ) ?
+            uv_buf_init(NULL, 0) : handle->tcp.conn.read_buffer;
+
+      err = GET_REQ_SOCK_ERROR(req);
+
+      if (err == WSAECONNABORTED) {
+        /*
+         * Turn WSAECONNABORTED into UV_ECONNRESET to be consistent with Unix.
+         */
+        err = WSAECONNRESET;
+      }
+
+      handle->read_cb((uv_stream_t*)handle,
+                      uv_translate_sys_error(err),
+                      &buf);
+    }
+  } else {
+    if (!(handle->flags & UV_HANDLE_ZERO_READ)) {
+      /* The read was done with a non-zero buffer length. */
+      if (req->u.io.overlapped.InternalHigh > 0) {
+        /* Successful read */
+        handle->read_cb((uv_stream_t*)handle,
+                        req->u.io.overlapped.InternalHigh,
+                        &handle->tcp.conn.read_buffer);
+        /* Read again only if bytes == buf.len */
+        if (req->u.io.overlapped.InternalHigh < handle->tcp.conn.read_buffer.len) {
+          goto done;
+        }
+      } else {
+        /* Connection closed */
+        if (handle->flags & UV_HANDLE_READING) {
+          handle->flags &= ~UV_HANDLE_READING;
+          DECREASE_ACTIVE_COUNT(loop, handle);
+        }
+        handle->flags &= ~UV_HANDLE_READABLE;
+
+        buf.base = 0;
+        buf.len = 0;
+        handle->read_cb((uv_stream_t*)handle, UV_EOF, &handle->tcp.conn.read_buffer);
+        goto done;
+      }
+    }
+
+    /* Do nonblocking reads until the buffer is empty */
+    while (handle->flags & UV_HANDLE_READING) {
+      buf = uv_buf_init(NULL, 0);
+      handle->alloc_cb((uv_handle_t*) handle, 65536, &buf);
+      if (buf.base == NULL || buf.len == 0) {
+        handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &buf);
+        break;
+      }
+      assert(buf.base != NULL);
+
+      flags = 0;
+      if (WSARecv(handle->socket,
+                  (WSABUF*)&buf,
+                  1,
+                  &bytes,
+                  &flags,
+                  NULL,
+                  NULL) != SOCKET_ERROR) {
+        if (bytes > 0) {
+          /* Successful read */
+          handle->read_cb((uv_stream_t*)handle, bytes, &buf);
+          /* Read again only if bytes == buf.len */
+          if (bytes < buf.len) {
+            break;
+          }
+        } else {
+          /* Connection closed */
+          handle->flags &= ~(UV_HANDLE_READING | UV_HANDLE_READABLE);
+          DECREASE_ACTIVE_COUNT(loop, handle);
+
+          handle->read_cb((uv_stream_t*)handle, UV_EOF, &buf);
+          break;
+        }
+      } else {
+        err = WSAGetLastError();
+        if (err == WSAEWOULDBLOCK) {
+          /* Read buffer was completely empty, report a 0-byte read. */
+          handle->read_cb((uv_stream_t*)handle, 0, &buf);
+        } else {
+          /* Ouch! serious error. */
+          handle->flags &= ~UV_HANDLE_READING;
+          DECREASE_ACTIVE_COUNT(loop, handle);
+
+          if (err == WSAECONNABORTED) {
+            /* Turn WSAECONNABORTED into UV_ECONNRESET to be consistent with */
+            /* Unix. */
+            err = WSAECONNRESET;
+          }
+
+          handle->read_cb((uv_stream_t*)handle,
+                          uv_translate_sys_error(err),
+                          &buf);
+        }
+        break;
+      }
+    }
+
+done:
+    /* Post another read if still reading and not closing. */
+    if ((handle->flags & UV_HANDLE_READING) &&
+        !(handle->flags & UV_HANDLE_READ_PENDING)) {
+      uv_tcp_queue_read(loop, handle);
+    }
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_write_t* req) {
+  int err;
+
+  assert(handle->type == UV_TCP);
+
+  assert(handle->write_queue_size >= req->u.io.queued_bytes);
+  handle->write_queue_size -= req->u.io.queued_bytes;
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
+    if (req->wait_handle != INVALID_HANDLE_VALUE) {
+      UnregisterWait(req->wait_handle);
+      req->wait_handle = INVALID_HANDLE_VALUE;
+    }
+    if (req->event_handle) {
+      CloseHandle(req->event_handle);
+      req->event_handle = NULL;
+    }
+  }
+
+  if (req->cb) {
+    err = uv_translate_sys_error(GET_REQ_SOCK_ERROR(req));
+    if (err == UV_ECONNABORTED) {
+      /* use UV_ECANCELED for consistency with Unix */
+      err = UV_ECANCELED;
+    }
+    req->cb(req, err);
+  }
+
+  handle->stream.conn.write_reqs_pending--;
+  if (handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_req_t* raw_req) {
+  uv_tcp_accept_t* req = (uv_tcp_accept_t*) raw_req;
+  int err;
+
+  assert(handle->type == UV_TCP);
+
+  /* If handle->accepted_socket is not a valid socket, then */
+  /* uv_queue_accept must have failed. This is a serious error. We stop */
+  /* accepting connections and report this error to the connection */
+  /* callback. */
+  if (req->accept_socket == INVALID_SOCKET) {
+    if (handle->flags & UV_HANDLE_LISTENING) {
+      handle->flags &= ~UV_HANDLE_LISTENING;
+      DECREASE_ACTIVE_COUNT(loop, handle);
+      if (handle->stream.serv.connection_cb) {
+        err = GET_REQ_SOCK_ERROR(req);
+        handle->stream.serv.connection_cb((uv_stream_t*)handle,
+                                      uv_translate_sys_error(err));
+      }
+    }
+  } else if (REQ_SUCCESS(req) &&
+      setsockopt(req->accept_socket,
+                  SOL_SOCKET,
+                  SO_UPDATE_ACCEPT_CONTEXT,
+                  (char*)&handle->socket,
+                  sizeof(handle->socket)) == 0) {
+    req->next_pending = handle->tcp.serv.pending_accepts;
+    handle->tcp.serv.pending_accepts = req;
+
+    /* Accept and SO_UPDATE_ACCEPT_CONTEXT were successful. */
+    if (handle->stream.serv.connection_cb) {
+      handle->stream.serv.connection_cb((uv_stream_t*)handle, 0);
+    }
+  } else {
+    /* Error related to accepted socket is ignored because the server */
+    /* socket may still be healthy. If the server socket is broken */
+    /* uv_queue_accept will detect it. */
+    closesocket(req->accept_socket);
+    req->accept_socket = INVALID_SOCKET;
+    if (handle->flags & UV_HANDLE_LISTENING) {
+      uv_tcp_queue_accept(handle, req);
+    }
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_tcp_connect_req(uv_loop_t* loop, uv_tcp_t* handle,
+    uv_connect_t* req) {
+  int err;
+
+  assert(handle->type == UV_TCP);
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  err = 0;
+  if (REQ_SUCCESS(req)) {
+    if (setsockopt(handle->socket,
+                    SOL_SOCKET,
+                    SO_UPDATE_CONNECT_CONTEXT,
+                    NULL,
+                    0) == 0) {
+      uv_connection_init((uv_stream_t*)handle);
+      handle->flags |= UV_HANDLE_READABLE | UV_HANDLE_WRITABLE;
+      loop->active_tcp_streams++;
+    } else {
+      err = WSAGetLastError();
+    }
+  } else {
+    err = GET_REQ_SOCK_ERROR(req);
+  }
+  req->cb(req, uv_translate_sys_error(err));
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+int uv_tcp_import(uv_tcp_t* tcp, uv__ipc_socket_info_ex* socket_info_ex,
+    int tcp_connection) {
+  int err;
+  SOCKET socket = WSASocketW(FROM_PROTOCOL_INFO,
+                             FROM_PROTOCOL_INFO,
+                             FROM_PROTOCOL_INFO,
+                             &socket_info_ex->socket_info,
+                             0,
+                             WSA_FLAG_OVERLAPPED);
+
+  if (socket == INVALID_SOCKET) {
+    return WSAGetLastError();
+  }
+
+  err = uv_tcp_set_socket(tcp->loop,
+                          tcp,
+                          socket,
+                          socket_info_ex->socket_info.iAddressFamily,
+                          1);
+  if (err) {
+    closesocket(socket);
+    return err;
+  }
+
+  if (tcp_connection) {
+    uv_connection_init((uv_stream_t*)tcp);
+    tcp->flags |= UV_HANDLE_READABLE | UV_HANDLE_WRITABLE;
+  }
+
+  tcp->flags |= UV_HANDLE_BOUND;
+  tcp->flags |= UV_HANDLE_SHARED_TCP_SOCKET;
+
+  tcp->delayed_error = socket_info_ex->delayed_error;
+
+  tcp->loop->active_tcp_streams++;
+  return 0;
+}
+
+
+int uv_tcp_nodelay(uv_tcp_t* handle, int enable) {
+  int err;
+
+  if (handle->socket != INVALID_SOCKET) {
+    err = uv__tcp_nodelay(handle, handle->socket, enable);
+    if (err)
+      return err;
+  }
+
+  if (enable) {
+    handle->flags |= UV_HANDLE_TCP_NODELAY;
+  } else {
+    handle->flags &= ~UV_HANDLE_TCP_NODELAY;
+  }
+
+  return 0;
+}
+
+
+int uv_tcp_keepalive(uv_tcp_t* handle, int enable, unsigned int delay) {
+  int err;
+
+  if (handle->socket != INVALID_SOCKET) {
+    err = uv__tcp_keepalive(handle, handle->socket, enable, delay);
+    if (err)
+      return err;
+  }
+
+  if (enable) {
+    handle->flags |= UV_HANDLE_TCP_KEEPALIVE;
+  } else {
+    handle->flags &= ~UV_HANDLE_TCP_KEEPALIVE;
+  }
+
+  /* TODO: Store delay if handle->socket isn't created yet. */
+
+  return 0;
+}
+
+
+int uv_tcp_duplicate_socket(uv_tcp_t* handle, int pid,
+    LPWSAPROTOCOL_INFOW protocol_info) {
+  if (!(handle->flags & UV_HANDLE_CONNECTION)) {
+    /*
+     * We're about to share the socket with another process.  Because
+     * this is a listening socket, we assume that the other process will
+     * be accepting connections on it.  So, before sharing the socket
+     * with another process, we call listen here in the parent process.
+     */
+
+    if (!(handle->flags & UV_HANDLE_LISTENING)) {
+      if (!(handle->flags & UV_HANDLE_BOUND)) {
+        return ERROR_INVALID_PARAMETER;
+      }
+
+      if (!(handle->delayed_error)) {
+        if (listen(handle->socket, SOMAXCONN) == SOCKET_ERROR) {
+          handle->delayed_error = WSAGetLastError();
+        }
+      }
+    }
+  }
+
+  if (WSADuplicateSocketW(handle->socket, pid, protocol_info)) {
+    return WSAGetLastError();
+  }
+
+  handle->flags |= UV_HANDLE_SHARED_TCP_SOCKET;
+
+  return 0;
+}
+
+
+int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable) {
+  if (handle->flags & UV_HANDLE_CONNECTION) {
+    return UV_EINVAL;
+  }
+
+  /* Check if we're already in the desired mode. */
+  if ((enable && !(handle->flags & UV_HANDLE_TCP_SINGLE_ACCEPT)) ||
+      (!enable && handle->flags & UV_HANDLE_TCP_SINGLE_ACCEPT)) {
+    return 0;
+  }
+
+  /* Don't allow switching from single pending accept to many. */
+  if (enable) {
+    return UV_ENOTSUP;
+  }
+
+  /* Check if we're in a middle of changing the number of pending accepts. */
+  if (handle->flags & UV_HANDLE_TCP_ACCEPT_STATE_CHANGING) {
+    return 0;
+  }
+
+  handle->flags |= UV_HANDLE_TCP_SINGLE_ACCEPT;
+
+  /* Flip the changing flag if we have already queued multiple accepts. */
+  if (handle->flags & UV_HANDLE_LISTENING) {
+    handle->flags |= UV_HANDLE_TCP_ACCEPT_STATE_CHANGING;
+  }
+
+  return 0;
+}
+
+
+static int uv_tcp_try_cancel_io(uv_tcp_t* tcp) {
+  SOCKET socket = tcp->socket;
+  int non_ifs_lsp;
+
+  /* Check if we have any non-IFS LSPs stacked on top of TCP */
+  non_ifs_lsp = (tcp->flags & UV_HANDLE_IPV6) ? uv_tcp_non_ifs_lsp_ipv6 :
+                                                uv_tcp_non_ifs_lsp_ipv4;
+
+  /* If there are non-ifs LSPs then try to obtain a base handle for the */
+  /* socket. This will always fail on Windows XP/3k. */
+  if (non_ifs_lsp) {
+    DWORD bytes;
+    if (WSAIoctl(socket,
+                 SIO_BASE_HANDLE,
+                 NULL,
+                 0,
+                 &socket,
+                 sizeof socket,
+                 &bytes,
+                 NULL,
+                 NULL) != 0) {
+      /* Failed. We can't do CancelIo. */
+      return -1;
+    }
+  }
+
+  assert(socket != 0 && socket != INVALID_SOCKET);
+
+  if (!CancelIo((HANDLE) socket)) {
+    return GetLastError();
+  }
+
+  /* It worked. */
+  return 0;
+}
+
+
+void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp) {
+  int close_socket = 1;
+
+  if (tcp->flags & UV_HANDLE_READ_PENDING) {
+    /* In order for winsock to do a graceful close there must not be any */
+    /* any pending reads, or the socket must be shut down for writing */
+    if (!(tcp->flags & UV_HANDLE_SHARED_TCP_SOCKET)) {
+      /* Just do shutdown on non-shared sockets, which ensures graceful close. */
+      shutdown(tcp->socket, SD_SEND);
+
+    } else if (uv_tcp_try_cancel_io(tcp) == 0) {
+      /* In case of a shared socket, we try to cancel all outstanding I/O, */
+      /* If that works, don't close the socket yet - wait for the read req to */
+      /* return and close the socket in uv_tcp_endgame. */
+      close_socket = 0;
+
+    } else {
+      /* When cancelling isn't possible - which could happen when an LSP is */
+      /* present on an old Windows version, we will have to close the socket */
+      /* with a read pending. That is not nice because trailing sent bytes */
+      /* may not make it to the other side. */
+    }
+
+  } else if ((tcp->flags & UV_HANDLE_SHARED_TCP_SOCKET) &&
+             tcp->tcp.serv.accept_reqs != NULL) {
+    /* Under normal circumstances closesocket() will ensure that all pending */
+    /* accept reqs are canceled. However, when the socket is shared the */
+    /* presence of another reference to the socket in another process will */
+    /* keep the accept reqs going, so we have to ensure that these are */
+    /* canceled. */
+    if (uv_tcp_try_cancel_io(tcp) != 0) {
+      /* When cancellation is not possible, there is another option: we can */
+      /* close the incoming sockets, which will also cancel the accept */
+      /* operations. However this is not cool because we might inadvertently */
+      /* close a socket that just accepted a new connection, which will */
+      /* cause the connection to be aborted. */
+      unsigned int i;
+      for (i = 0; i < uv_simultaneous_server_accepts; i++) {
+        uv_tcp_accept_t* req = &tcp->tcp.serv.accept_reqs[i];
+        if (req->accept_socket != INVALID_SOCKET &&
+            !HasOverlappedIoCompleted(&req->u.io.overlapped)) {
+          closesocket(req->accept_socket);
+          req->accept_socket = INVALID_SOCKET;
+        }
+      }
+    }
+  }
+
+  if (tcp->flags & UV_HANDLE_READING) {
+    tcp->flags &= ~UV_HANDLE_READING;
+    DECREASE_ACTIVE_COUNT(loop, tcp);
+  }
+
+  if (tcp->flags & UV_HANDLE_LISTENING) {
+    tcp->flags &= ~UV_HANDLE_LISTENING;
+    DECREASE_ACTIVE_COUNT(loop, tcp);
+  }
+
+  if (close_socket) {
+    closesocket(tcp->socket);
+    tcp->socket = INVALID_SOCKET;
+    tcp->flags |= UV_HANDLE_TCP_SOCKET_CLOSED;
+  }
+
+  tcp->flags &= ~(UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
+  uv__handle_closing(tcp);
+
+  if (tcp->reqs_pending == 0) {
+    uv_want_endgame(tcp->loop, (uv_handle_t*)tcp);
+  }
+}
+
+
+int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock) {
+  WSAPROTOCOL_INFOW protocol_info;
+  int opt_len;
+  int err;
+
+  /* Detect the address family of the socket. */
+  opt_len = (int) sizeof protocol_info;
+  if (getsockopt(sock,
+                 SOL_SOCKET,
+                 SO_PROTOCOL_INFOW,
+                 (char*) &protocol_info,
+                 &opt_len) == SOCKET_ERROR) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  err = uv_tcp_set_socket(handle->loop,
+                          handle,
+                          sock,
+                          protocol_info.iAddressFamily,
+                          1);
+  if (err) {
+    return uv_translate_sys_error(err);
+  }
+
+  return 0;
+}
+
+
+/* This function is an egress point, i.e. it returns libuv errors rather than
+ * system errors.
+ */
+int uv__tcp_bind(uv_tcp_t* handle,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 unsigned int flags) {
+  int err;
+
+  err = uv_tcp_try_bind(handle, addr, addrlen, flags);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  return 0;
+}
+
+
+/* This function is an egress point, i.e. it returns libuv errors rather than
+ * system errors.
+ */
+int uv__tcp_connect(uv_connect_t* req,
+                    uv_tcp_t* handle,
+                    const struct sockaddr* addr,
+                    unsigned int addrlen,
+                    uv_connect_cb cb) {
+  int err;
+
+  err = uv_tcp_try_connect(req, handle, addr, addrlen, cb);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  return 0;
+}
diff --git a/Utilities/cmlibuv/src/win/thread.c b/Utilities/cmlibuv/src/win/thread.c
new file mode 100644
index 0000000..91684e9
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/thread.c
@@ -0,0 +1,697 @@
+/* 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 <assert.h>
+#include <limits.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+#define HAVE_CONDVAR_API() (pInitializeConditionVariable != NULL)
+
+static int uv_cond_fallback_init(uv_cond_t* cond);
+static void uv_cond_fallback_destroy(uv_cond_t* cond);
+static void uv_cond_fallback_signal(uv_cond_t* cond);
+static void uv_cond_fallback_broadcast(uv_cond_t* cond);
+static void uv_cond_fallback_wait(uv_cond_t* cond, uv_mutex_t* mutex);
+static int uv_cond_fallback_timedwait(uv_cond_t* cond,
+    uv_mutex_t* mutex, uint64_t timeout);
+
+static int uv_cond_condvar_init(uv_cond_t* cond);
+static void uv_cond_condvar_destroy(uv_cond_t* cond);
+static void uv_cond_condvar_signal(uv_cond_t* cond);
+static void uv_cond_condvar_broadcast(uv_cond_t* cond);
+static void uv_cond_condvar_wait(uv_cond_t* cond, uv_mutex_t* mutex);
+static int uv_cond_condvar_timedwait(uv_cond_t* cond,
+    uv_mutex_t* mutex, uint64_t timeout);
+
+
+static void uv__once_inner(uv_once_t* guard, void (*callback)(void)) {
+  DWORD result;
+  HANDLE existing_event, created_event;
+
+  created_event = CreateEvent(NULL, 1, 0, NULL);
+  if (created_event == 0) {
+    /* Could fail in a low-memory situation? */
+    uv_fatal_error(GetLastError(), "CreateEvent");
+  }
+
+  existing_event = InterlockedCompareExchangePointer(&guard->event,
+                                                     created_event,
+                                                     NULL);
+
+  if (existing_event == NULL) {
+    /* We won the race */
+    callback();
+
+    result = SetEvent(created_event);
+    assert(result);
+    guard->ran = 1;
+
+  } else {
+    /* We lost the race. Destroy the event we created and wait for the */
+    /* existing one to become signaled. */
+    CloseHandle(created_event);
+    result = WaitForSingleObject(existing_event, INFINITE);
+    assert(result == WAIT_OBJECT_0);
+  }
+}
+
+
+void uv_once(uv_once_t* guard, void (*callback)(void)) {
+  /* Fast case - avoid WaitForSingleObject. */
+  if (guard->ran) {
+    return;
+  }
+
+  uv__once_inner(guard, callback);
+}
+
+
+/* Verify that uv_thread_t can be stored in a TLS slot. */
+STATIC_ASSERT(sizeof(uv_thread_t) <= sizeof(void*));
+
+static uv_key_t uv__current_thread_key;
+static uv_once_t uv__current_thread_init_guard = UV_ONCE_INIT;
+
+
+static void uv__init_current_thread_key(void) {
+  if (uv_key_create(&uv__current_thread_key))
+    abort();
+}
+
+
+struct thread_ctx {
+  void (*entry)(void* arg);
+  void* arg;
+  uv_thread_t self;
+};
+
+
+static UINT __stdcall uv__thread_start(void* arg) {
+  struct thread_ctx *ctx_p;
+  struct thread_ctx ctx;
+
+  ctx_p = arg;
+  ctx = *ctx_p;
+  uv__free(ctx_p);
+
+  uv_once(&uv__current_thread_init_guard, uv__init_current_thread_key);
+  uv_key_set(&uv__current_thread_key, (void*) ctx.self);
+
+  ctx.entry(ctx.arg);
+
+  return 0;
+}
+
+
+int uv_thread_create(uv_thread_t *tid, void (*entry)(void *arg), void *arg) {
+  struct thread_ctx* ctx;
+  int err;
+  HANDLE thread;
+
+  ctx = uv__malloc(sizeof(*ctx));
+  if (ctx == NULL)
+    return UV_ENOMEM;
+
+  ctx->entry = entry;
+  ctx->arg = arg;
+
+  /* Create the thread in suspended state so we have a chance to pass
+   * its own creation handle to it */   
+  thread = (HANDLE) _beginthreadex(NULL,
+                                   0,
+                                   uv__thread_start,
+                                   ctx,
+                                   CREATE_SUSPENDED,
+                                   NULL);
+  if (thread == NULL) {
+    err = errno;
+    uv__free(ctx);
+  } else {
+    err = 0;
+    *tid = thread;
+    ctx->self = thread;
+    ResumeThread(thread);
+  }
+
+  switch (err) {
+    case 0:
+      return 0;
+    case EACCES:
+      return UV_EACCES;
+    case EAGAIN:
+      return UV_EAGAIN;
+    case EINVAL:
+      return UV_EINVAL;
+  }
+
+  return UV_EIO;
+}
+
+
+uv_thread_t uv_thread_self(void) {
+  uv_once(&uv__current_thread_init_guard, uv__init_current_thread_key);
+  return (uv_thread_t) uv_key_get(&uv__current_thread_key);
+}
+
+
+int uv_thread_join(uv_thread_t *tid) {
+  if (WaitForSingleObject(*tid, INFINITE))
+    return uv_translate_sys_error(GetLastError());
+  else {
+    CloseHandle(*tid);
+    *tid = 0;
+    return 0;
+  }
+}
+
+
+int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2) {
+  return *t1 == *t2;
+}
+
+
+int uv_mutex_init(uv_mutex_t* mutex) {
+  InitializeCriticalSection(mutex);
+  return 0;
+}
+
+
+void uv_mutex_destroy(uv_mutex_t* mutex) {
+  DeleteCriticalSection(mutex);
+}
+
+
+void uv_mutex_lock(uv_mutex_t* mutex) {
+  EnterCriticalSection(mutex);
+}
+
+
+int uv_mutex_trylock(uv_mutex_t* mutex) {
+  if (TryEnterCriticalSection(mutex))
+    return 0;
+  else
+    return UV_EBUSY;
+}
+
+
+void uv_mutex_unlock(uv_mutex_t* mutex) {
+  LeaveCriticalSection(mutex);
+}
+
+
+int uv_rwlock_init(uv_rwlock_t* rwlock) {
+  /* Initialize the semaphore that acts as the write lock. */
+  HANDLE handle = CreateSemaphoreW(NULL, 1, 1, NULL);
+  if (handle == NULL)
+    return uv_translate_sys_error(GetLastError());
+  rwlock->state_.write_semaphore_ = handle;
+
+  /* Initialize the critical section protecting the reader count. */
+  InitializeCriticalSection(&rwlock->state_.num_readers_lock_);
+
+  /* Initialize the reader count. */
+  rwlock->state_.num_readers_ = 0;
+
+  return 0;
+}
+
+
+void uv_rwlock_destroy(uv_rwlock_t* rwlock) {
+  DeleteCriticalSection(&rwlock->state_.num_readers_lock_);
+  CloseHandle(rwlock->state_.write_semaphore_);
+}
+
+
+void uv_rwlock_rdlock(uv_rwlock_t* rwlock) {
+  /* Acquire the lock that protects the reader count. */
+  EnterCriticalSection(&rwlock->state_.num_readers_lock_);
+
+  /* Increase the reader count, and lock for write if this is the first
+   * reader.
+   */
+  if (++rwlock->state_.num_readers_ == 1) {
+    DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, INFINITE);
+    if (r != WAIT_OBJECT_0)
+      uv_fatal_error(GetLastError(), "WaitForSingleObject");
+  }
+
+  /* Release the lock that protects the reader count. */
+  LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
+}
+
+
+int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock) {
+  int err;
+
+  if (!TryEnterCriticalSection(&rwlock->state_.num_readers_lock_))
+    return UV_EBUSY;
+
+  err = 0;
+
+  if (rwlock->state_.num_readers_ == 0) {
+    /* Currently there are no other readers, which means that the write lock
+     * needs to be acquired.
+     */
+    DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, 0);
+    if (r == WAIT_OBJECT_0)
+      rwlock->state_.num_readers_++;
+    else if (r == WAIT_TIMEOUT)
+      err = UV_EBUSY;
+    else if (r == WAIT_FAILED)
+      uv_fatal_error(GetLastError(), "WaitForSingleObject");
+
+  } else {
+    /* The write lock has already been acquired because there are other
+     * active readers.
+     */
+    rwlock->state_.num_readers_++;
+  }
+
+  LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
+  return err;
+}
+
+
+void uv_rwlock_rdunlock(uv_rwlock_t* rwlock) {
+  EnterCriticalSection(&rwlock->state_.num_readers_lock_);
+
+  if (--rwlock->state_.num_readers_ == 0) {
+    if (!ReleaseSemaphore(rwlock->state_.write_semaphore_, 1, NULL))
+      uv_fatal_error(GetLastError(), "ReleaseSemaphore");
+  }
+
+  LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
+}
+
+
+void uv_rwlock_wrlock(uv_rwlock_t* rwlock) {
+  DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, INFINITE);
+  if (r != WAIT_OBJECT_0)
+    uv_fatal_error(GetLastError(), "WaitForSingleObject");
+}
+
+
+int uv_rwlock_trywrlock(uv_rwlock_t* rwlock) {
+  DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, 0);
+  if (r == WAIT_OBJECT_0)
+    return 0;
+  else if (r == WAIT_TIMEOUT)
+    return UV_EBUSY;
+  else
+    uv_fatal_error(GetLastError(), "WaitForSingleObject");
+}
+
+
+void uv_rwlock_wrunlock(uv_rwlock_t* rwlock) {
+  if (!ReleaseSemaphore(rwlock->state_.write_semaphore_, 1, NULL))
+    uv_fatal_error(GetLastError(), "ReleaseSemaphore");
+}
+
+
+int uv_sem_init(uv_sem_t* sem, unsigned int value) {
+  *sem = CreateSemaphore(NULL, value, INT_MAX, NULL);
+  if (*sem == NULL)
+    return uv_translate_sys_error(GetLastError());
+  else
+    return 0;
+}
+
+
+void uv_sem_destroy(uv_sem_t* sem) {
+  if (!CloseHandle(*sem))
+    abort();
+}
+
+
+void uv_sem_post(uv_sem_t* sem) {
+  if (!ReleaseSemaphore(*sem, 1, NULL))
+    abort();
+}
+
+
+void uv_sem_wait(uv_sem_t* sem) {
+  if (WaitForSingleObject(*sem, INFINITE) != WAIT_OBJECT_0)
+    abort();
+}
+
+
+int uv_sem_trywait(uv_sem_t* sem) {
+  DWORD r = WaitForSingleObject(*sem, 0);
+
+  if (r == WAIT_OBJECT_0)
+    return 0;
+
+  if (r == WAIT_TIMEOUT)
+    return UV_EAGAIN;
+
+  abort();
+  return -1; /* Satisfy the compiler. */
+}
+
+
+/* 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.
+ */
+
+static int uv_cond_fallback_init(uv_cond_t* cond) {
+  int err;
+
+  /* Initialize the count to 0. */
+  cond->fallback.waiters_count = 0;
+
+  InitializeCriticalSection(&cond->fallback.waiters_count_lock);
+
+  /* Create an auto-reset event. */
+  cond->fallback.signal_event = CreateEvent(NULL,  /* no security */
+                                            FALSE, /* auto-reset event */
+                                            FALSE, /* non-signaled initially */
+                                            NULL); /* unnamed */
+  if (!cond->fallback.signal_event) {
+    err = GetLastError();
+    goto error2;
+  }
+
+  /* Create a manual-reset event. */
+  cond->fallback.broadcast_event = CreateEvent(NULL,  /* no security */
+                                               TRUE,  /* manual-reset */
+                                               FALSE, /* non-signaled */
+                                               NULL); /* unnamed */
+  if (!cond->fallback.broadcast_event) {
+    err = GetLastError();
+    goto error;
+  }
+
+  return 0;
+
+error:
+  CloseHandle(cond->fallback.signal_event);
+error2:
+  DeleteCriticalSection(&cond->fallback.waiters_count_lock);
+  return uv_translate_sys_error(err);
+}
+
+
+static int uv_cond_condvar_init(uv_cond_t* cond) {
+  pInitializeConditionVariable(&cond->cond_var);
+  return 0;
+}
+
+
+int uv_cond_init(uv_cond_t* cond) {
+  uv__once_init();
+
+  if (HAVE_CONDVAR_API())
+    return uv_cond_condvar_init(cond);
+  else
+    return uv_cond_fallback_init(cond);
+}
+
+
+static void uv_cond_fallback_destroy(uv_cond_t* cond) {
+  if (!CloseHandle(cond->fallback.broadcast_event))
+    abort();
+  if (!CloseHandle(cond->fallback.signal_event))
+    abort();
+  DeleteCriticalSection(&cond->fallback.waiters_count_lock);
+}
+
+
+static void uv_cond_condvar_destroy(uv_cond_t* cond) {
+  /* nothing to do */
+}
+
+
+void uv_cond_destroy(uv_cond_t* cond) {
+  if (HAVE_CONDVAR_API())
+    uv_cond_condvar_destroy(cond);
+  else
+    uv_cond_fallback_destroy(cond);
+}
+
+
+static void uv_cond_fallback_signal(uv_cond_t* cond) {
+  int have_waiters;
+
+  /* Avoid race conditions. */
+  EnterCriticalSection(&cond->fallback.waiters_count_lock);
+  have_waiters = cond->fallback.waiters_count > 0;
+  LeaveCriticalSection(&cond->fallback.waiters_count_lock);
+
+  if (have_waiters)
+    SetEvent(cond->fallback.signal_event);
+}
+
+
+static void uv_cond_condvar_signal(uv_cond_t* cond) {
+  pWakeConditionVariable(&cond->cond_var);
+}
+
+
+void uv_cond_signal(uv_cond_t* cond) {
+  if (HAVE_CONDVAR_API())
+    uv_cond_condvar_signal(cond);
+  else
+    uv_cond_fallback_signal(cond);
+}
+
+
+static void uv_cond_fallback_broadcast(uv_cond_t* cond) {
+  int have_waiters;
+
+  /* Avoid race conditions. */
+  EnterCriticalSection(&cond->fallback.waiters_count_lock);
+  have_waiters = cond->fallback.waiters_count > 0;
+  LeaveCriticalSection(&cond->fallback.waiters_count_lock);
+
+  if (have_waiters)
+    SetEvent(cond->fallback.broadcast_event);
+}
+
+
+static void uv_cond_condvar_broadcast(uv_cond_t* cond) {
+  pWakeAllConditionVariable(&cond->cond_var);
+}
+
+
+void uv_cond_broadcast(uv_cond_t* cond) {
+  if (HAVE_CONDVAR_API())
+    uv_cond_condvar_broadcast(cond);
+  else
+    uv_cond_fallback_broadcast(cond);
+}
+
+
+static int uv_cond_wait_helper(uv_cond_t* cond, uv_mutex_t* mutex,
+    DWORD dwMilliseconds) {
+  DWORD result;
+  int last_waiter;
+  HANDLE handles[2] = {
+    cond->fallback.signal_event,
+    cond->fallback.broadcast_event
+  };
+
+  /* Avoid race conditions. */
+  EnterCriticalSection(&cond->fallback.waiters_count_lock);
+  cond->fallback.waiters_count++;
+  LeaveCriticalSection(&cond->fallback.waiters_count_lock);
+
+  /* It's ok to release the <mutex> here since Win32 manual-reset events */
+  /* maintain state when used with <SetEvent>. This avoids the "lost wakeup" */
+  /* bug. */
+  uv_mutex_unlock(mutex);
+
+  /* Wait for either event to become signaled due to <uv_cond_signal> being */
+  /* called or <uv_cond_broadcast> being called. */
+  result = WaitForMultipleObjects(2, handles, FALSE, dwMilliseconds);
+
+  EnterCriticalSection(&cond->fallback.waiters_count_lock);
+  cond->fallback.waiters_count--;
+  last_waiter = result == WAIT_OBJECT_0 + 1
+      && cond->fallback.waiters_count == 0;
+  LeaveCriticalSection(&cond->fallback.waiters_count_lock);
+
+  /* Some thread called <pthread_cond_broadcast>. */
+  if (last_waiter) {
+    /* We're the last waiter to be notified or to stop waiting, so reset the */
+    /* the manual-reset event. */
+    ResetEvent(cond->fallback.broadcast_event);
+  }
+
+  /* Reacquire the <mutex>. */
+  uv_mutex_lock(mutex);
+
+  if (result == WAIT_OBJECT_0 || result == WAIT_OBJECT_0 + 1)
+    return 0;
+
+  if (result == WAIT_TIMEOUT)
+    return UV_ETIMEDOUT;
+
+  abort();
+  return -1; /* Satisfy the compiler. */
+}
+
+
+static void uv_cond_fallback_wait(uv_cond_t* cond, uv_mutex_t* mutex) {
+  if (uv_cond_wait_helper(cond, mutex, INFINITE))
+    abort();
+}
+
+
+static void uv_cond_condvar_wait(uv_cond_t* cond, uv_mutex_t* mutex) {
+  if (!pSleepConditionVariableCS(&cond->cond_var, mutex, INFINITE))
+    abort();
+}
+
+
+void uv_cond_wait(uv_cond_t* cond, uv_mutex_t* mutex) {
+  if (HAVE_CONDVAR_API())
+    uv_cond_condvar_wait(cond, mutex);
+  else
+    uv_cond_fallback_wait(cond, mutex);
+}
+
+
+static int uv_cond_fallback_timedwait(uv_cond_t* cond,
+    uv_mutex_t* mutex, uint64_t timeout) {
+  return uv_cond_wait_helper(cond, mutex, (DWORD)(timeout / 1e6));
+}
+
+
+static int uv_cond_condvar_timedwait(uv_cond_t* cond,
+    uv_mutex_t* mutex, uint64_t timeout) {
+  if (pSleepConditionVariableCS(&cond->cond_var, mutex, (DWORD)(timeout / 1e6)))
+    return 0;
+  if (GetLastError() != ERROR_TIMEOUT)
+    abort();
+  return UV_ETIMEDOUT;
+}
+
+
+int uv_cond_timedwait(uv_cond_t* cond, uv_mutex_t* mutex,
+    uint64_t timeout) {
+  if (HAVE_CONDVAR_API())
+    return uv_cond_condvar_timedwait(cond, mutex, timeout);
+  else
+    return uv_cond_fallback_timedwait(cond, mutex, timeout);
+}
+
+
+int uv_barrier_init(uv_barrier_t* barrier, unsigned int count) {
+  int err;
+
+  barrier->n = count;
+  barrier->count = 0;
+
+  err = uv_mutex_init(&barrier->mutex);
+  if (err)
+    return err;
+
+  err = uv_sem_init(&barrier->turnstile1, 0);
+  if (err)
+    goto error2;
+
+  err = uv_sem_init(&barrier->turnstile2, 1);
+  if (err)
+    goto error;
+
+  return 0;
+
+error:
+  uv_sem_destroy(&barrier->turnstile1);
+error2:
+  uv_mutex_destroy(&barrier->mutex);
+  return err;
+
+}
+
+
+void uv_barrier_destroy(uv_barrier_t* barrier) {
+  uv_sem_destroy(&barrier->turnstile2);
+  uv_sem_destroy(&barrier->turnstile1);
+  uv_mutex_destroy(&barrier->mutex);
+}
+
+
+int uv_barrier_wait(uv_barrier_t* barrier) {
+  int serial_thread;
+
+  uv_mutex_lock(&barrier->mutex);
+  if (++barrier->count == barrier->n) {
+    uv_sem_wait(&barrier->turnstile2);
+    uv_sem_post(&barrier->turnstile1);
+  }
+  uv_mutex_unlock(&barrier->mutex);
+
+  uv_sem_wait(&barrier->turnstile1);
+  uv_sem_post(&barrier->turnstile1);
+
+  uv_mutex_lock(&barrier->mutex);
+  serial_thread = (--barrier->count == 0);
+  if (serial_thread) {
+    uv_sem_wait(&barrier->turnstile1);
+    uv_sem_post(&barrier->turnstile2);
+  }
+  uv_mutex_unlock(&barrier->mutex);
+
+  uv_sem_wait(&barrier->turnstile2);
+  uv_sem_post(&barrier->turnstile2);
+  return serial_thread;
+}
+
+
+int uv_key_create(uv_key_t* key) {
+  key->tls_index = TlsAlloc();
+  if (key->tls_index == TLS_OUT_OF_INDEXES)
+    return UV_ENOMEM;
+  return 0;
+}
+
+
+void uv_key_delete(uv_key_t* key) {
+  if (TlsFree(key->tls_index) == FALSE)
+    abort();
+  key->tls_index = TLS_OUT_OF_INDEXES;
+}
+
+
+void* uv_key_get(uv_key_t* key) {
+  void* value;
+
+  value = TlsGetValue(key->tls_index);
+  if (value == NULL)
+    if (GetLastError() != ERROR_SUCCESS)
+      abort();
+
+  return value;
+}
+
+
+void uv_key_set(uv_key_t* key, void* value) {
+  if (TlsSetValue(key->tls_index, value) == FALSE)
+    abort();
+}
diff --git a/Utilities/cmlibuv/src/win/timer.c b/Utilities/cmlibuv/src/win/timer.c
new file mode 100644
index 0000000..27ca771
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/timer.c
@@ -0,0 +1,195 @@
+/* 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 <assert.h>
+#include <limits.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "tree.h"
+#include "handle-inl.h"
+
+
+/* The number of milliseconds in one second. */
+#define UV__MILLISEC 1000
+
+
+void uv_update_time(uv_loop_t* loop) {
+  uint64_t new_time = uv__hrtime(UV__MILLISEC);
+  assert(new_time >= loop->time);
+  loop->time = new_time;
+}
+
+
+static int uv_timer_compare(uv_timer_t* a, uv_timer_t* b) {
+  if (a->due < b->due)
+    return -1;
+  if (a->due > b->due)
+    return 1;
+  /*
+   *  compare start_id when both has the same due. start_id is
+   *  allocated with loop->timer_counter in uv_timer_start().
+   */
+  if (a->start_id < b->start_id)
+    return -1;
+  if (a->start_id > b->start_id)
+    return 1;
+  return 0;
+}
+
+
+RB_GENERATE_STATIC(uv_timer_tree_s, uv_timer_s, tree_entry, uv_timer_compare);
+
+
+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;
+}
+
+
+void uv_timer_endgame(uv_loop_t* loop, uv_timer_t* handle) {
+  if (handle->flags & UV__HANDLE_CLOSING) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+    uv__handle_close(handle);
+  }
+}
+
+
+static uint64_t get_clamped_due_time(uint64_t loop_time, uint64_t timeout) {
+  uint64_t clamped_timeout;
+
+  clamped_timeout = loop_time + timeout;
+  if (clamped_timeout < timeout)
+    clamped_timeout = (uint64_t) -1;
+
+  return clamped_timeout;
+}
+
+
+int uv_timer_start(uv_timer_t* handle, uv_timer_cb timer_cb, uint64_t timeout,
+    uint64_t repeat) {
+  uv_loop_t* loop = handle->loop;
+  uv_timer_t* old;
+
+  if (timer_cb == NULL)
+    return UV_EINVAL;
+
+  if (uv__is_active(handle))
+    uv_timer_stop(handle);
+
+  handle->timer_cb = timer_cb;
+  handle->due = get_clamped_due_time(loop->time, timeout);
+  handle->repeat = repeat;
+  uv__handle_start(handle);
+
+  /* start_id is the second index to be compared in uv__timer_cmp() */
+  handle->start_id = handle->loop->timer_counter++;
+
+  old = RB_INSERT(uv_timer_tree_s, &loop->timers, handle);
+  assert(old == NULL);
+
+  return 0;
+}
+
+
+int uv_timer_stop(uv_timer_t* handle) {
+  uv_loop_t* loop = handle->loop;
+
+  if (!uv__is_active(handle))
+    return 0;
+
+  RB_REMOVE(uv_timer_tree_s, &loop->timers, handle);
+  uv__handle_stop(handle);
+
+  return 0;
+}
+
+
+int uv_timer_again(uv_timer_t* handle) {
+  /* If timer_cb is NULL that means that the timer was never started. */
+  if (!handle->timer_cb) {
+    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) {
+  assert(handle->type == UV_TIMER);
+  handle->repeat = repeat;
+}
+
+
+uint64_t uv_timer_get_repeat(const uv_timer_t* handle) {
+  assert(handle->type == UV_TIMER);
+  return handle->repeat;
+}
+
+
+DWORD uv__next_timeout(const uv_loop_t* loop) {
+  uv_timer_t* timer;
+  int64_t delta;
+
+  /* Check if there are any running timers
+   * Need to cast away const first, since RB_MIN doesn't know what we are
+   * going to do with this return value, it can't be marked const
+   */
+  timer = RB_MIN(uv_timer_tree_s, &((uv_loop_t*)loop)->timers);
+  if (timer) {
+    delta = timer->due - loop->time;
+    if (delta >= UINT_MAX - 1) {
+      /* A timeout value of UINT_MAX means infinite, so that's no good. */
+      return UINT_MAX - 1;
+    } else if (delta < 0) {
+      /* Negative timeout values are not allowed */
+      return 0;
+    } else {
+      return (DWORD)delta;
+    }
+  } else {
+    /* No timers */
+    return INFINITE;
+  }
+}
+
+
+void uv_process_timers(uv_loop_t* loop) {
+  uv_timer_t* timer;
+
+  /* Call timer callbacks */
+  for (timer = RB_MIN(uv_timer_tree_s, &loop->timers);
+       timer != NULL && timer->due <= loop->time;
+       timer = RB_MIN(uv_timer_tree_s, &loop->timers)) {
+
+    uv_timer_stop(timer);
+    uv_timer_again(timer);
+    timer->timer_cb((uv_timer_t*) timer);
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/tty.c b/Utilities/cmlibuv/src/win/tty.c
new file mode 100644
index 0000000..18d68d0
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/tty.c
@@ -0,0 +1,2257 @@
+/* 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 <assert.h>
+#include <io.h>
+#include <string.h>
+#include <stdlib.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#ifndef COMMON_LVB_REVERSE_VIDEO
+# define COMMON_LVB_REVERSE_VIDEO 0x4000
+#endif
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "stream-inl.h"
+#include "req-inl.h"
+
+#ifndef InterlockedOr
+# define InterlockedOr _InterlockedOr
+#endif
+
+#define UNICODE_REPLACEMENT_CHARACTER (0xfffd)
+
+#define ANSI_NORMAL           0x00
+#define ANSI_ESCAPE_SEEN      0x02
+#define ANSI_CSI              0x04
+#define ANSI_ST_CONTROL       0x08
+#define ANSI_IGNORE           0x10
+#define ANSI_IN_ARG           0x20
+#define ANSI_IN_STRING        0x40
+#define ANSI_BACKSLASH_SEEN   0x80
+
+#define MAX_INPUT_BUFFER_LENGTH 8192
+
+#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
+#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
+#endif
+
+static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info);
+static void uv_tty_update_virtual_window(CONSOLE_SCREEN_BUFFER_INFO* info);
+static int uv__cancel_read_console(uv_tty_t* handle);
+
+
+/* Null uv_buf_t */
+static const uv_buf_t uv_null_buf_ = { 0, NULL };
+
+enum uv__read_console_status_e {
+  NOT_STARTED,
+  IN_PROGRESS,
+  TRAP_REQUESTED,
+  COMPLETED
+};
+
+static volatile LONG uv__read_console_status = NOT_STARTED;
+static volatile LONG uv__restore_screen_state;
+static CONSOLE_SCREEN_BUFFER_INFO uv__saved_screen_state;
+
+
+/*
+ * The console virtual window.
+ *
+ * Normally cursor movement in windows is relative to the console screen buffer,
+ * e.g. the application is allowed to overwrite the 'history'. This is very
+ * inconvenient, it makes absolute cursor movement pretty useless. There is
+ * also the concept of 'client rect' which is defined by the actual size of
+ * the console window and the scroll position of the screen buffer, but it's
+ * very volatile because it changes when the user scrolls.
+ *
+ * To make cursor movement behave sensibly we define a virtual window to which
+ * cursor movement is confined. The virtual window is always as wide as the
+ * console screen buffer, but it's height is defined by the size of the
+ * console window. The top of the virtual window aligns with the position
+ * of the caret when the first stdout/err handle is created, unless that would
+ * mean that it would extend beyond the bottom of the screen buffer -  in that
+ * that case it's located as far down as possible.
+ *
+ * When the user writes a long text or many newlines, such that the output
+ * reaches beyond the bottom of the virtual window, the virtual window is
+ * shifted downwards, but not resized.
+ *
+ * Since all tty i/o happens on the same console, this window is shared
+ * between all stdout/stderr handles.
+ */
+
+static int uv_tty_virtual_offset = -1;
+static int uv_tty_virtual_height = -1;
+static int uv_tty_virtual_width = -1;
+
+/* We use a semaphore rather than a mutex or critical section because in some
+   cases (uv__cancel_read_console) we need take the lock in the main thread and
+   release it in another thread. Using a semaphore ensures that in such
+   scenario the main thread will still block when trying to acquire the lock. */
+static uv_sem_t uv_tty_output_lock;
+
+static HANDLE uv_tty_output_handle = INVALID_HANDLE_VALUE;
+
+static WORD uv_tty_default_text_attributes =
+    FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
+
+static char uv_tty_default_fg_color = 7;
+static char uv_tty_default_bg_color = 0;
+static char uv_tty_default_fg_bright = 0;
+static char uv_tty_default_bg_bright = 0;
+static char uv_tty_default_inverse = 0;
+
+typedef enum {
+  UV_SUPPORTED,
+  UV_UNCHECKED,
+  UV_UNSUPPORTED
+} uv_vtermstate_t;
+/* Determine whether or not ANSI support is enabled. */
+static uv_vtermstate_t uv__vterm_state = UV_UNCHECKED;
+static void uv__determine_vterm_state(HANDLE handle);
+
+void uv_console_init() {
+  if (uv_sem_init(&uv_tty_output_lock, 1))
+    abort();
+}
+
+
+int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) {
+  HANDLE handle;
+  CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
+
+  handle = (HANDLE) uv__get_osfhandle(fd);
+  if (handle == INVALID_HANDLE_VALUE)
+    return UV_EBADF;
+
+  if (fd <= 2) {
+    /* In order to avoid closing a stdio file descriptor 0-2, duplicate the
+     * underlying OS handle and forget about the original fd.
+     * We could also opt to use the original OS handle and just never close it,
+     * but then there would be no reliable way to cancel pending read operations
+     * upon close.
+     */
+    if (!DuplicateHandle(INVALID_HANDLE_VALUE,
+                         handle,
+                         INVALID_HANDLE_VALUE,
+                         &handle,
+                         0,
+                         FALSE,
+                         DUPLICATE_SAME_ACCESS))
+      return uv_translate_sys_error(GetLastError());
+    fd = -1;
+  }
+
+  if (!readable) {
+    /* Obtain the screen buffer info with the output handle. */
+    if (!GetConsoleScreenBufferInfo(handle, &screen_buffer_info)) {
+      return uv_translate_sys_error(GetLastError());
+    }
+
+    /* Obtain the the tty_output_lock because the virtual window state is */
+    /* shared between all uv_tty_t handles. */
+    uv_sem_wait(&uv_tty_output_lock);
+
+    if (uv__vterm_state == UV_UNCHECKED)
+      uv__determine_vterm_state(handle);
+
+    /* Store the global tty output handle. This handle is used by TTY read */
+    /* streams to update the virtual window when a CONSOLE_BUFFER_SIZE_EVENT */
+    /* is received. */
+    uv_tty_output_handle = handle;
+
+    /* Remember the original console text attributes. */
+    uv_tty_capture_initial_style(&screen_buffer_info);
+
+    uv_tty_update_virtual_window(&screen_buffer_info);
+
+    uv_sem_post(&uv_tty_output_lock);
+  }
+
+
+  uv_stream_init(loop, (uv_stream_t*) tty, UV_TTY);
+  uv_connection_init((uv_stream_t*) tty);
+
+  tty->handle = handle;
+  tty->u.fd = fd;
+  tty->reqs_pending = 0;
+  tty->flags |= UV_HANDLE_BOUND;
+
+  if (readable) {
+    /* Initialize TTY input specific fields. */
+    tty->flags |= UV_HANDLE_TTY_READABLE | UV_HANDLE_READABLE;
+    /* TODO: remove me in v2.x. */
+    tty->tty.rd.unused_ = NULL;
+    tty->tty.rd.read_line_buffer = uv_null_buf_;
+    tty->tty.rd.read_raw_wait = NULL;
+
+    /* Init keycode-to-vt100 mapper state. */
+    tty->tty.rd.last_key_len = 0;
+    tty->tty.rd.last_key_offset = 0;
+    tty->tty.rd.last_utf16_high_surrogate = 0;
+    memset(&tty->tty.rd.last_input_record, 0, sizeof tty->tty.rd.last_input_record);
+  } else {
+    /* TTY output specific fields. */
+    tty->flags |= UV_HANDLE_WRITABLE;
+
+    /* Init utf8-to-utf16 conversion state. */
+    tty->tty.wr.utf8_bytes_left = 0;
+    tty->tty.wr.utf8_codepoint = 0;
+
+    /* Initialize eol conversion state */
+    tty->tty.wr.previous_eol = 0;
+
+    /* Init ANSI parser state. */
+    tty->tty.wr.ansi_parser_state = ANSI_NORMAL;
+  }
+
+  return 0;
+}
+
+
+/* Set the default console text attributes based on how the console was
+ * configured when libuv started.
+ */
+static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info) {
+  static int style_captured = 0;
+
+  /* Only do this once.
+     Assumption: Caller has acquired uv_tty_output_lock. */
+  if (style_captured)
+    return;
+
+  /* Save raw win32 attributes. */
+  uv_tty_default_text_attributes = info->wAttributes;
+
+  /* Convert black text on black background to use white text. */
+  if (uv_tty_default_text_attributes == 0)
+    uv_tty_default_text_attributes = 7;
+
+  /* Convert Win32 attributes to ANSI colors. */
+  uv_tty_default_fg_color = 0;
+  uv_tty_default_bg_color = 0;
+  uv_tty_default_fg_bright = 0;
+  uv_tty_default_bg_bright = 0;
+  uv_tty_default_inverse = 0;
+
+  if (uv_tty_default_text_attributes & FOREGROUND_RED)
+    uv_tty_default_fg_color |= 1;
+
+  if (uv_tty_default_text_attributes & FOREGROUND_GREEN)
+    uv_tty_default_fg_color |= 2;
+
+  if (uv_tty_default_text_attributes & FOREGROUND_BLUE)
+    uv_tty_default_fg_color |= 4;
+
+  if (uv_tty_default_text_attributes & BACKGROUND_RED)
+    uv_tty_default_bg_color |= 1;
+
+  if (uv_tty_default_text_attributes & BACKGROUND_GREEN)
+    uv_tty_default_bg_color |= 2;
+
+  if (uv_tty_default_text_attributes & BACKGROUND_BLUE)
+    uv_tty_default_bg_color |= 4;
+
+  if (uv_tty_default_text_attributes & FOREGROUND_INTENSITY)
+    uv_tty_default_fg_bright = 1;
+
+  if (uv_tty_default_text_attributes & BACKGROUND_INTENSITY)
+    uv_tty_default_bg_bright = 1;
+
+  if (uv_tty_default_text_attributes & COMMON_LVB_REVERSE_VIDEO)
+    uv_tty_default_inverse = 1;
+
+  style_captured = 1;
+}
+
+
+int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
+  DWORD flags;
+  unsigned char was_reading;
+  uv_alloc_cb alloc_cb;
+  uv_read_cb read_cb;
+  int err;
+
+  if (!(tty->flags & UV_HANDLE_TTY_READABLE)) {
+    return UV_EINVAL;
+  }
+
+  if (!!mode == !!(tty->flags & UV_HANDLE_TTY_RAW)) {
+    return 0;
+  }
+
+  switch (mode) {
+    case UV_TTY_MODE_NORMAL:
+      flags = ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
+      break;
+    case UV_TTY_MODE_RAW:
+      flags = ENABLE_WINDOW_INPUT;
+      break;
+    case UV_TTY_MODE_IO:
+      return UV_ENOTSUP;
+    default:
+      return UV_EINVAL;
+  }
+
+  /* If currently reading, stop, and restart reading. */
+  if (tty->flags & UV_HANDLE_READING) {
+    was_reading = 1;
+    alloc_cb = tty->alloc_cb;
+    read_cb = tty->read_cb;
+    err = uv_tty_read_stop(tty);
+    if (err) {
+      return uv_translate_sys_error(err);
+    }
+  } else {
+    was_reading = 0;
+  }
+
+  uv_sem_wait(&uv_tty_output_lock);
+  if (!SetConsoleMode(tty->handle, flags)) {
+    err = uv_translate_sys_error(GetLastError());
+    uv_sem_post(&uv_tty_output_lock);
+    return err;
+  }
+  uv_sem_post(&uv_tty_output_lock);
+
+  /* Update flag. */
+  tty->flags &= ~UV_HANDLE_TTY_RAW;
+  tty->flags |= mode ? UV_HANDLE_TTY_RAW : 0;
+
+  /* If we just stopped reading, restart. */
+  if (was_reading) {
+    err = uv_tty_read_start(tty, alloc_cb, read_cb);
+    if (err) {
+      return uv_translate_sys_error(err);
+    }
+  }
+
+  return 0;
+}
+
+
+int uv_is_tty(uv_file file) {
+  DWORD result;
+  return GetConsoleMode((HANDLE) _get_osfhandle(file), &result) != 0;
+}
+
+
+int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
+  CONSOLE_SCREEN_BUFFER_INFO info;
+
+  if (!GetConsoleScreenBufferInfo(tty->handle, &info)) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  uv_sem_wait(&uv_tty_output_lock);
+  uv_tty_update_virtual_window(&info);
+  uv_sem_post(&uv_tty_output_lock);
+
+  *width = uv_tty_virtual_width;
+  *height = uv_tty_virtual_height;
+
+  return 0;
+}
+
+
+static void CALLBACK uv_tty_post_raw_read(void* data, BOOLEAN didTimeout) {
+  uv_loop_t* loop;
+  uv_tty_t* handle;
+  uv_req_t* req;
+
+  assert(data);
+  assert(!didTimeout);
+
+  req = (uv_req_t*) data;
+  handle = (uv_tty_t*) req->data;
+  loop = handle->loop;
+
+  UnregisterWait(handle->tty.rd.read_raw_wait);
+  handle->tty.rd.read_raw_wait = NULL;
+
+  SET_REQ_SUCCESS(req);
+  POST_COMPLETION_FOR_REQ(loop, req);
+}
+
+
+static void uv_tty_queue_read_raw(uv_loop_t* loop, uv_tty_t* handle) {
+  uv_read_t* req;
+  BOOL r;
+
+  assert(handle->flags & UV_HANDLE_READING);
+  assert(!(handle->flags & UV_HANDLE_READ_PENDING));
+
+  assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE);
+
+  handle->tty.rd.read_line_buffer = uv_null_buf_;
+
+  req = &handle->read_req;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  r = RegisterWaitForSingleObject(&handle->tty.rd.read_raw_wait,
+                                  handle->handle,
+                                  uv_tty_post_raw_read,
+                                  (void*) req,
+                                  INFINITE,
+                                  WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
+  if (!r) {
+    handle->tty.rd.read_raw_wait = NULL;
+    SET_REQ_ERROR(req, GetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  }
+
+  handle->flags |= UV_HANDLE_READ_PENDING;
+  handle->reqs_pending++;
+}
+
+
+static DWORD CALLBACK uv_tty_line_read_thread(void* data) {
+  uv_loop_t* loop;
+  uv_tty_t* handle;
+  uv_req_t* req;
+  DWORD bytes, read_bytes;
+  WCHAR utf16[MAX_INPUT_BUFFER_LENGTH / 3];
+  DWORD chars, read_chars;
+  LONG status;
+  COORD pos;
+  BOOL read_console_success;
+
+  assert(data);
+
+  req = (uv_req_t*) data;
+  handle = (uv_tty_t*) req->data;
+  loop = handle->loop;
+
+  assert(handle->tty.rd.read_line_buffer.base != NULL);
+  assert(handle->tty.rd.read_line_buffer.len > 0);
+
+  /* ReadConsole can't handle big buffers. */
+  if (handle->tty.rd.read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) {
+    bytes = handle->tty.rd.read_line_buffer.len;
+  } else {
+    bytes = MAX_INPUT_BUFFER_LENGTH;
+  }
+
+  /* At last, unicode! */
+  /* One utf-16 codeunit never takes more than 3 utf-8 codeunits to encode */
+  chars = bytes / 3;
+
+  status = InterlockedExchange(&uv__read_console_status, IN_PROGRESS);
+  if (status == TRAP_REQUESTED) {
+    SET_REQ_SUCCESS(req);
+    req->u.io.overlapped.InternalHigh = 0;
+    POST_COMPLETION_FOR_REQ(loop, req);
+    return 0;
+  }
+
+  read_console_success = ReadConsoleW(handle->handle,
+                                      (void*) utf16,
+                                      chars,
+                                      &read_chars,
+                                      NULL);
+
+  if (read_console_success) {
+    read_bytes = WideCharToMultiByte(CP_UTF8,
+                                     0,
+                                     utf16,
+                                     read_chars,
+                                     handle->tty.rd.read_line_buffer.base,
+                                     bytes,
+                                     NULL,
+                                     NULL);
+    SET_REQ_SUCCESS(req);
+    req->u.io.overlapped.InternalHigh = read_bytes;
+  } else {
+    SET_REQ_ERROR(req, GetLastError());
+  }
+
+  status = InterlockedExchange(&uv__read_console_status, COMPLETED);
+
+  if (status ==  TRAP_REQUESTED) {
+    /* If we canceled the read by sending a VK_RETURN event, restore the
+       screen state to undo the visual effect of the VK_RETURN */
+    if (read_console_success && InterlockedOr(&uv__restore_screen_state, 0)) {
+      HANDLE active_screen_buffer;
+      active_screen_buffer = CreateFileA("conout$",
+                                         GENERIC_READ | GENERIC_WRITE,
+                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                         NULL,
+                                         OPEN_EXISTING,
+                                         FILE_ATTRIBUTE_NORMAL,
+                                         NULL);
+      if (active_screen_buffer != INVALID_HANDLE_VALUE) {
+        pos = uv__saved_screen_state.dwCursorPosition;
+
+        /* If the cursor was at the bottom line of the screen buffer, the
+           VK_RETURN would have caused the buffer contents to scroll up by one
+           line. The right position to reset the cursor to is therefore one line
+           higher */
+        if (pos.Y == uv__saved_screen_state.dwSize.Y - 1)
+          pos.Y--;
+
+        SetConsoleCursorPosition(active_screen_buffer, pos);
+        CloseHandle(active_screen_buffer);
+      }
+    }
+    uv_sem_post(&uv_tty_output_lock);
+  }
+  POST_COMPLETION_FOR_REQ(loop, req);
+  return 0;
+}
+
+
+static void uv_tty_queue_read_line(uv_loop_t* loop, uv_tty_t* handle) {
+  uv_read_t* req;
+  BOOL r;
+
+  assert(handle->flags & UV_HANDLE_READING);
+  assert(!(handle->flags & UV_HANDLE_READ_PENDING));
+  assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE);
+
+  req = &handle->read_req;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  handle->tty.rd.read_line_buffer = uv_buf_init(NULL, 0);
+  handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->tty.rd.read_line_buffer);
+  if (handle->tty.rd.read_line_buffer.base == NULL ||
+      handle->tty.rd.read_line_buffer.len == 0) {
+    handle->read_cb((uv_stream_t*) handle,
+                    UV_ENOBUFS,
+                    &handle->tty.rd.read_line_buffer);
+    return;
+  }
+  assert(handle->tty.rd.read_line_buffer.base != NULL);
+
+  /* Reset flags  No locking is required since there cannot be a line read
+     in progress. We are also relying on the memory barrier provided by
+     QueueUserWorkItem*/
+  uv__restore_screen_state = FALSE;
+  uv__read_console_status = NOT_STARTED;
+  r = QueueUserWorkItem(uv_tty_line_read_thread,
+                        (void*) req,
+                        WT_EXECUTELONGFUNCTION);
+  if (!r) {
+    SET_REQ_ERROR(req, GetLastError());
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  }
+
+  handle->flags |= UV_HANDLE_READ_PENDING;
+  handle->reqs_pending++;
+}
+
+
+static void uv_tty_queue_read(uv_loop_t* loop, uv_tty_t* handle) {
+  if (handle->flags & UV_HANDLE_TTY_RAW) {
+    uv_tty_queue_read_raw(loop, handle);
+  } else {
+    uv_tty_queue_read_line(loop, handle);
+  }
+}
+
+
+static const char* get_vt100_fn_key(DWORD code, char shift, char ctrl,
+    size_t* len) {
+#define VK_CASE(vk, normal_str, shift_str, ctrl_str, shift_ctrl_str)          \
+    case (vk):                                                                \
+      if (shift && ctrl) {                                                    \
+        *len = sizeof shift_ctrl_str;                                         \
+        return "\033" shift_ctrl_str;                                         \
+      } else if (shift) {                                                     \
+        *len = sizeof shift_str ;                                             \
+        return "\033" shift_str;                                              \
+      } else if (ctrl) {                                                      \
+        *len = sizeof ctrl_str;                                               \
+        return "\033" ctrl_str;                                               \
+      } else {                                                                \
+        *len = sizeof normal_str;                                             \
+        return "\033" normal_str;                                             \
+      }
+
+  switch (code) {
+    /* These mappings are the same as Cygwin's. Unmodified and alt-modified */
+    /* keypad keys comply with linux console, modifiers comply with xterm */
+    /* modifier usage. F1..f12 and shift-f1..f10 comply with linux console, */
+    /* f6..f12 with and without modifiers comply with rxvt. */
+    VK_CASE(VK_INSERT,  "[2~",  "[2;2~", "[2;5~", "[2;6~")
+    VK_CASE(VK_END,     "[4~",  "[4;2~", "[4;5~", "[4;6~")
+    VK_CASE(VK_DOWN,    "[B",   "[1;2B", "[1;5B", "[1;6B")
+    VK_CASE(VK_NEXT,    "[6~",  "[6;2~", "[6;5~", "[6;6~")
+    VK_CASE(VK_LEFT,    "[D",   "[1;2D", "[1;5D", "[1;6D")
+    VK_CASE(VK_CLEAR,   "[G",   "[1;2G", "[1;5G", "[1;6G")
+    VK_CASE(VK_RIGHT,   "[C",   "[1;2C", "[1;5C", "[1;6C")
+    VK_CASE(VK_UP,      "[A",   "[1;2A", "[1;5A", "[1;6A")
+    VK_CASE(VK_HOME,    "[1~",  "[1;2~", "[1;5~", "[1;6~")
+    VK_CASE(VK_PRIOR,   "[5~",  "[5;2~", "[5;5~", "[5;6~")
+    VK_CASE(VK_DELETE,  "[3~",  "[3;2~", "[3;5~", "[3;6~")
+    VK_CASE(VK_NUMPAD0, "[2~",  "[2;2~", "[2;5~", "[2;6~")
+    VK_CASE(VK_NUMPAD1, "[4~",  "[4;2~", "[4;5~", "[4;6~")
+    VK_CASE(VK_NUMPAD2, "[B",   "[1;2B", "[1;5B", "[1;6B")
+    VK_CASE(VK_NUMPAD3, "[6~",  "[6;2~", "[6;5~", "[6;6~")
+    VK_CASE(VK_NUMPAD4, "[D",   "[1;2D", "[1;5D", "[1;6D")
+    VK_CASE(VK_NUMPAD5, "[G",   "[1;2G", "[1;5G", "[1;6G")
+    VK_CASE(VK_NUMPAD6, "[C",   "[1;2C", "[1;5C", "[1;6C")
+    VK_CASE(VK_NUMPAD7, "[A",   "[1;2A", "[1;5A", "[1;6A")
+    VK_CASE(VK_NUMPAD8, "[1~",  "[1;2~", "[1;5~", "[1;6~")
+    VK_CASE(VK_NUMPAD9, "[5~",  "[5;2~", "[5;5~", "[5;6~")
+    VK_CASE(VK_DECIMAL, "[3~",  "[3;2~", "[3;5~", "[3;6~")
+    VK_CASE(VK_F1,      "[[A",  "[23~",  "[11^",  "[23^" )
+    VK_CASE(VK_F2,      "[[B",  "[24~",  "[12^",  "[24^" )
+    VK_CASE(VK_F3,      "[[C",  "[25~",  "[13^",  "[25^" )
+    VK_CASE(VK_F4,      "[[D",  "[26~",  "[14^",  "[26^" )
+    VK_CASE(VK_F5,      "[[E",  "[28~",  "[15^",  "[28^" )
+    VK_CASE(VK_F6,      "[17~", "[29~",  "[17^",  "[29^" )
+    VK_CASE(VK_F7,      "[18~", "[31~",  "[18^",  "[31^" )
+    VK_CASE(VK_F8,      "[19~", "[32~",  "[19^",  "[32^" )
+    VK_CASE(VK_F9,      "[20~", "[33~",  "[20^",  "[33^" )
+    VK_CASE(VK_F10,     "[21~", "[34~",  "[21^",  "[34^" )
+    VK_CASE(VK_F11,     "[23~", "[23$",  "[23^",  "[23@" )
+    VK_CASE(VK_F12,     "[24~", "[24$",  "[24^",  "[24@" )
+
+    default:
+      *len = 0;
+      return NULL;
+  }
+#undef VK_CASE
+}
+
+
+void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* req) {
+  /* Shortcut for handle->tty.rd.last_input_record.Event.KeyEvent. */
+#define KEV handle->tty.rd.last_input_record.Event.KeyEvent
+
+  DWORD records_left, records_read;
+  uv_buf_t buf;
+  off_t buf_used;
+
+  assert(handle->type == UV_TTY);
+  assert(handle->flags & UV_HANDLE_TTY_READABLE);
+  handle->flags &= ~UV_HANDLE_READ_PENDING;
+
+  if (!(handle->flags & UV_HANDLE_READING) ||
+      !(handle->flags & UV_HANDLE_TTY_RAW)) {
+    goto out;
+  }
+
+  if (!REQ_SUCCESS(req)) {
+    /* An error occurred while waiting for the event. */
+    if ((handle->flags & UV_HANDLE_READING)) {
+      handle->flags &= ~UV_HANDLE_READING;
+      handle->read_cb((uv_stream_t*)handle,
+                      uv_translate_sys_error(GET_REQ_ERROR(req)),
+                      &uv_null_buf_);
+    }
+    goto out;
+  }
+
+  /* Fetch the number of events  */
+  if (!GetNumberOfConsoleInputEvents(handle->handle, &records_left)) {
+    handle->flags &= ~UV_HANDLE_READING;
+    DECREASE_ACTIVE_COUNT(loop, handle);
+    handle->read_cb((uv_stream_t*)handle,
+                    uv_translate_sys_error(GetLastError()),
+                    &uv_null_buf_);
+    goto out;
+  }
+
+  /* Windows sends a lot of events that we're not interested in, so buf */
+  /* will be allocated on demand, when there's actually something to emit. */
+  buf = uv_null_buf_;
+  buf_used = 0;
+
+  while ((records_left > 0 || handle->tty.rd.last_key_len > 0) &&
+         (handle->flags & UV_HANDLE_READING)) {
+    if (handle->tty.rd.last_key_len == 0) {
+      /* Read the next input record */
+      if (!ReadConsoleInputW(handle->handle,
+                             &handle->tty.rd.last_input_record,
+                             1,
+                             &records_read)) {
+        handle->flags &= ~UV_HANDLE_READING;
+        DECREASE_ACTIVE_COUNT(loop, handle);
+        handle->read_cb((uv_stream_t*) handle,
+                        uv_translate_sys_error(GetLastError()),
+                        &buf);
+        goto out;
+      }
+      records_left--;
+
+      /* If the window was resized, recompute the virtual window size. This */
+      /* will trigger a SIGWINCH signal if the window size changed in an */
+      /* way that matters to libuv. */
+      if (handle->tty.rd.last_input_record.EventType == WINDOW_BUFFER_SIZE_EVENT) {
+        CONSOLE_SCREEN_BUFFER_INFO info;
+
+        uv_sem_wait(&uv_tty_output_lock);
+
+        if (uv_tty_output_handle != INVALID_HANDLE_VALUE &&
+            GetConsoleScreenBufferInfo(uv_tty_output_handle, &info)) {
+          uv_tty_update_virtual_window(&info);
+        }
+
+        uv_sem_post(&uv_tty_output_lock);
+
+        continue;
+      }
+
+      /* Ignore other events that are not key or resize events. */
+      if (handle->tty.rd.last_input_record.EventType != KEY_EVENT) {
+        continue;
+      }
+
+      /* Ignore keyup events, unless the left alt key was held and a valid */
+      /* unicode character was emitted. */
+      if (!KEV.bKeyDown && !(((KEV.dwControlKeyState & LEFT_ALT_PRESSED) ||
+          KEV.wVirtualKeyCode==VK_MENU) && KEV.uChar.UnicodeChar != 0)) {
+        continue;
+      }
+
+      /* Ignore keypresses to numpad number keys if the left alt is held */
+      /* because the user is composing a character, or windows simulating */
+      /* this. */
+      if ((KEV.dwControlKeyState & LEFT_ALT_PRESSED) &&
+          !(KEV.dwControlKeyState & ENHANCED_KEY) &&
+          (KEV.wVirtualKeyCode == VK_INSERT ||
+          KEV.wVirtualKeyCode == VK_END ||
+          KEV.wVirtualKeyCode == VK_DOWN ||
+          KEV.wVirtualKeyCode == VK_NEXT ||
+          KEV.wVirtualKeyCode == VK_LEFT ||
+          KEV.wVirtualKeyCode == VK_CLEAR ||
+          KEV.wVirtualKeyCode == VK_RIGHT ||
+          KEV.wVirtualKeyCode == VK_HOME ||
+          KEV.wVirtualKeyCode == VK_UP ||
+          KEV.wVirtualKeyCode == VK_PRIOR ||
+          KEV.wVirtualKeyCode == VK_NUMPAD0 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD1 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD2 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD3 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD4 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD5 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD6 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD7 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD8 ||
+          KEV.wVirtualKeyCode == VK_NUMPAD9)) {
+        continue;
+      }
+
+      if (KEV.uChar.UnicodeChar != 0) {
+        int prefix_len, char_len;
+
+        /* Character key pressed */
+        if (KEV.uChar.UnicodeChar >= 0xD800 &&
+            KEV.uChar.UnicodeChar < 0xDC00) {
+          /* UTF-16 high surrogate */
+          handle->tty.rd.last_utf16_high_surrogate = KEV.uChar.UnicodeChar;
+          continue;
+        }
+
+        /* Prefix with \u033 if alt was held, but alt was not used as part */
+        /* a compose sequence. */
+        if ((KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
+            && !(KEV.dwControlKeyState & (LEFT_CTRL_PRESSED |
+            RIGHT_CTRL_PRESSED)) && KEV.bKeyDown) {
+          handle->tty.rd.last_key[0] = '\033';
+          prefix_len = 1;
+        } else {
+          prefix_len = 0;
+        }
+
+        if (KEV.uChar.UnicodeChar >= 0xDC00 &&
+            KEV.uChar.UnicodeChar < 0xE000) {
+          /* UTF-16 surrogate pair */
+          WCHAR utf16_buffer[2] = { handle->tty.rd.last_utf16_high_surrogate,
+                                    KEV.uChar.UnicodeChar};
+          char_len = WideCharToMultiByte(CP_UTF8,
+                                         0,
+                                         utf16_buffer,
+                                         2,
+                                         &handle->tty.rd.last_key[prefix_len],
+                                         sizeof handle->tty.rd.last_key,
+                                         NULL,
+                                         NULL);
+        } else {
+          /* Single UTF-16 character */
+          char_len = WideCharToMultiByte(CP_UTF8,
+                                         0,
+                                         &KEV.uChar.UnicodeChar,
+                                         1,
+                                         &handle->tty.rd.last_key[prefix_len],
+                                         sizeof handle->tty.rd.last_key,
+                                         NULL,
+                                         NULL);
+        }
+
+        /* Whatever happened, the last character wasn't a high surrogate. */
+        handle->tty.rd.last_utf16_high_surrogate = 0;
+
+        /* If the utf16 character(s) couldn't be converted something must */
+        /* be wrong. */
+        if (!char_len) {
+          handle->flags &= ~UV_HANDLE_READING;
+          DECREASE_ACTIVE_COUNT(loop, handle);
+          handle->read_cb((uv_stream_t*) handle,
+                          uv_translate_sys_error(GetLastError()),
+                          &buf);
+          goto out;
+        }
+
+        handle->tty.rd.last_key_len = (unsigned char) (prefix_len + char_len);
+        handle->tty.rd.last_key_offset = 0;
+        continue;
+
+      } else {
+        /* Function key pressed */
+        const char* vt100;
+        size_t prefix_len, vt100_len;
+
+        vt100 = get_vt100_fn_key(KEV.wVirtualKeyCode,
+                                  !!(KEV.dwControlKeyState & SHIFT_PRESSED),
+                                  !!(KEV.dwControlKeyState & (
+                                    LEFT_CTRL_PRESSED |
+                                    RIGHT_CTRL_PRESSED)),
+                                  &vt100_len);
+
+        /* If we were unable to map to a vt100 sequence, just ignore. */
+        if (!vt100) {
+          continue;
+        }
+
+        /* Prefix with \x033 when the alt key was held. */
+        if (KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) {
+          handle->tty.rd.last_key[0] = '\033';
+          prefix_len = 1;
+        } else {
+          prefix_len = 0;
+        }
+
+        /* Copy the vt100 sequence to the handle buffer. */
+        assert(prefix_len + vt100_len < sizeof handle->tty.rd.last_key);
+        memcpy(&handle->tty.rd.last_key[prefix_len], vt100, vt100_len);
+
+        handle->tty.rd.last_key_len = (unsigned char) (prefix_len + vt100_len);
+        handle->tty.rd.last_key_offset = 0;
+        continue;
+      }
+    } else {
+      /* Copy any bytes left from the last keypress to the user buffer. */
+      if (handle->tty.rd.last_key_offset < handle->tty.rd.last_key_len) {
+        /* Allocate a buffer if needed */
+        if (buf_used == 0) {
+          buf = uv_buf_init(NULL, 0);
+          handle->alloc_cb((uv_handle_t*) handle, 1024, &buf);
+          if (buf.base == NULL || buf.len == 0) {
+            handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &buf);
+            goto out;
+          }
+          assert(buf.base != NULL);
+        }
+
+        buf.base[buf_used++] = handle->tty.rd.last_key[handle->tty.rd.last_key_offset++];
+
+        /* If the buffer is full, emit it */
+        if ((size_t) buf_used == buf.len) {
+          handle->read_cb((uv_stream_t*) handle, buf_used, &buf);
+          buf = uv_null_buf_;
+          buf_used = 0;
+        }
+
+        continue;
+      }
+
+      /* Apply dwRepeat from the last input record. */
+      if (--KEV.wRepeatCount > 0) {
+        handle->tty.rd.last_key_offset = 0;
+        continue;
+      }
+
+      handle->tty.rd.last_key_len = 0;
+      continue;
+    }
+  }
+
+  /* Send the buffer back to the user */
+  if (buf_used > 0) {
+    handle->read_cb((uv_stream_t*) handle, buf_used, &buf);
+  }
+
+ out:
+  /* Wait for more input events. */
+  if ((handle->flags & UV_HANDLE_READING) &&
+      !(handle->flags & UV_HANDLE_READ_PENDING)) {
+    uv_tty_queue_read(loop, handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+
+#undef KEV
+}
+
+
+
+void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* req) {
+  uv_buf_t buf;
+
+  assert(handle->type == UV_TTY);
+  assert(handle->flags & UV_HANDLE_TTY_READABLE);
+
+  buf = handle->tty.rd.read_line_buffer;
+
+  handle->flags &= ~UV_HANDLE_READ_PENDING;
+  handle->tty.rd.read_line_buffer = uv_null_buf_;
+
+  if (!REQ_SUCCESS(req)) {
+    /* Read was not successful */
+    if (handle->flags & UV_HANDLE_READING) {
+      /* Real error */
+      handle->flags &= ~UV_HANDLE_READING;
+      DECREASE_ACTIVE_COUNT(loop, handle);
+      handle->read_cb((uv_stream_t*) handle,
+                      uv_translate_sys_error(GET_REQ_ERROR(req)),
+                      &buf);
+    } else {
+      /* The read was cancelled, or whatever we don't care */
+      handle->read_cb((uv_stream_t*) handle, 0, &buf);
+    }
+
+  } else {
+    if (!(handle->flags & UV_HANDLE_CANCELLATION_PENDING)) {
+      /* Read successful */
+      /* TODO: read unicode, convert to utf-8 */
+      DWORD bytes = req->u.io.overlapped.InternalHigh;
+      handle->read_cb((uv_stream_t*) handle, bytes, &buf);
+    } else {
+      handle->flags &= ~UV_HANDLE_CANCELLATION_PENDING;
+      handle->read_cb((uv_stream_t*) handle, 0, &buf);
+    }
+  }
+
+  /* Wait for more input events. */
+  if ((handle->flags & UV_HANDLE_READING) &&
+      !(handle->flags & UV_HANDLE_READ_PENDING)) {
+    uv_tty_queue_read(loop, handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_tty_read_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* req) {
+  assert(handle->type == UV_TTY);
+  assert(handle->flags & UV_HANDLE_TTY_READABLE);
+
+  /* If the read_line_buffer member is zero, it must have been an raw read. */
+  /* Otherwise it was a line-buffered read. */
+  /* FIXME: This is quite obscure. Use a flag or something. */
+  if (handle->tty.rd.read_line_buffer.len == 0) {
+    uv_process_tty_read_raw_req(loop, handle, req);
+  } else {
+    uv_process_tty_read_line_req(loop, handle, req);
+  }
+}
+
+
+int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb,
+    uv_read_cb read_cb) {
+  uv_loop_t* loop = handle->loop;
+
+  if (!(handle->flags & UV_HANDLE_TTY_READABLE)) {
+    return ERROR_INVALID_PARAMETER;
+  }
+
+  handle->flags |= UV_HANDLE_READING;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+  handle->read_cb = read_cb;
+  handle->alloc_cb = alloc_cb;
+
+  /* If reading was stopped and then started again, there could still be a */
+  /* read request pending. */
+  if (handle->flags & UV_HANDLE_READ_PENDING) {
+    return 0;
+  }
+
+  /* Maybe the user stopped reading half-way while processing key events. */
+  /* Short-circuit if this could be the case. */
+  if (handle->tty.rd.last_key_len > 0) {
+    SET_REQ_SUCCESS(&handle->read_req);
+    uv_insert_pending_req(handle->loop, (uv_req_t*) &handle->read_req);
+    return 0;
+  }
+
+  uv_tty_queue_read(loop, handle);
+
+  return 0;
+}
+
+
+int uv_tty_read_stop(uv_tty_t* handle) {
+  INPUT_RECORD record;
+  DWORD written, err;
+
+  handle->flags &= ~UV_HANDLE_READING;
+  DECREASE_ACTIVE_COUNT(handle->loop, handle);
+
+  if (!(handle->flags & UV_HANDLE_READ_PENDING))
+    return 0;
+
+  if (handle->flags & UV_HANDLE_TTY_RAW) {
+    /* Cancel raw read */
+    /* Write some bullshit event to force the console wait to return. */
+    memset(&record, 0, sizeof record);
+    if (!WriteConsoleInputW(handle->handle, &record, 1, &written)) {
+      return GetLastError();
+    }
+  } else if (!(handle->flags & UV_HANDLE_CANCELLATION_PENDING)) {
+    /* Cancel line-buffered read if not already pending */
+    err = uv__cancel_read_console(handle);
+    if (err)
+      return err;
+
+    handle->flags |= UV_HANDLE_CANCELLATION_PENDING;
+  }
+
+  return 0;
+}
+
+static int uv__cancel_read_console(uv_tty_t* handle) {
+  HANDLE active_screen_buffer = INVALID_HANDLE_VALUE;
+  INPUT_RECORD record;
+  DWORD written;
+  DWORD err = 0;
+  LONG status;
+
+  assert(!(handle->flags & UV_HANDLE_CANCELLATION_PENDING));
+
+  /* Hold the output lock during the cancellation, to ensure that further
+     writes don't interfere with the screen state. It will be the ReadConsole
+     thread's responsibility to release the lock. */
+  uv_sem_wait(&uv_tty_output_lock);
+  status = InterlockedExchange(&uv__read_console_status, TRAP_REQUESTED);
+  if (status != IN_PROGRESS) {
+    /* Either we have managed to set a trap for the other thread before
+       ReadConsole is called, or ReadConsole has returned because the user
+       has pressed ENTER. In either case, there is nothing else to do. */
+    uv_sem_post(&uv_tty_output_lock);
+    return 0;
+  }
+
+  /* Save screen state before sending the VK_RETURN event */
+  active_screen_buffer = CreateFileA("conout$",
+                                     GENERIC_READ | GENERIC_WRITE,
+                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                     NULL,
+                                     OPEN_EXISTING,
+                                     FILE_ATTRIBUTE_NORMAL,
+                                     NULL);
+
+  if (active_screen_buffer != INVALID_HANDLE_VALUE &&
+      GetConsoleScreenBufferInfo(active_screen_buffer,
+                                 &uv__saved_screen_state)) {
+    InterlockedOr(&uv__restore_screen_state, 1);
+  }
+
+  /* Write enter key event to force the console wait to return. */
+  record.EventType = KEY_EVENT;
+  record.Event.KeyEvent.bKeyDown = TRUE;
+  record.Event.KeyEvent.wRepeatCount = 1;
+  record.Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
+  record.Event.KeyEvent.wVirtualScanCode =
+    MapVirtualKeyW(VK_RETURN, MAPVK_VK_TO_VSC);
+  record.Event.KeyEvent.uChar.UnicodeChar = L'\r';
+  record.Event.KeyEvent.dwControlKeyState = 0;
+  if (!WriteConsoleInputW(handle->handle, &record, 1, &written))
+    err = GetLastError();
+
+  if (active_screen_buffer != INVALID_HANDLE_VALUE)
+    CloseHandle(active_screen_buffer);
+
+  return err;
+}
+
+
+static void uv_tty_update_virtual_window(CONSOLE_SCREEN_BUFFER_INFO* info) {
+  int old_virtual_width = uv_tty_virtual_width;
+  int old_virtual_height = uv_tty_virtual_height;
+
+  uv_tty_virtual_width = info->dwSize.X;
+  uv_tty_virtual_height = info->srWindow.Bottom - info->srWindow.Top + 1;
+
+  /* Recompute virtual window offset row. */
+  if (uv_tty_virtual_offset == -1) {
+    uv_tty_virtual_offset = info->dwCursorPosition.Y;
+  } else if (uv_tty_virtual_offset < info->dwCursorPosition.Y -
+             uv_tty_virtual_height + 1) {
+    /* If suddenly find the cursor outside of the virtual window, it must */
+    /* have somehow scrolled. Update the virtual window offset. */
+    uv_tty_virtual_offset = info->dwCursorPosition.Y -
+                            uv_tty_virtual_height + 1;
+  }
+  if (uv_tty_virtual_offset + uv_tty_virtual_height > info->dwSize.Y) {
+    uv_tty_virtual_offset = info->dwSize.Y - uv_tty_virtual_height;
+  }
+  if (uv_tty_virtual_offset < 0) {
+    uv_tty_virtual_offset = 0;
+  }
+
+  /* If the virtual window size changed, emit a SIGWINCH signal. Don't emit */
+  /* if this was the first time the virtual window size was computed. */
+  if (old_virtual_width != -1 && old_virtual_height != -1 &&
+      (uv_tty_virtual_width != old_virtual_width ||
+       uv_tty_virtual_height != old_virtual_height)) {
+    uv__signal_dispatch(SIGWINCH);
+  }
+}
+
+
+static COORD uv_tty_make_real_coord(uv_tty_t* handle,
+    CONSOLE_SCREEN_BUFFER_INFO* info, int x, unsigned char x_relative, int y,
+    unsigned char y_relative) {
+  COORD result;
+
+  uv_tty_update_virtual_window(info);
+
+  /* Adjust y position */
+  if (y_relative) {
+    y = info->dwCursorPosition.Y + y;
+  } else {
+    y = uv_tty_virtual_offset + y;
+  }
+  /* Clip y to virtual client rectangle */
+  if (y < uv_tty_virtual_offset) {
+    y = uv_tty_virtual_offset;
+  } else if (y >= uv_tty_virtual_offset + uv_tty_virtual_height) {
+    y = uv_tty_virtual_offset + uv_tty_virtual_height - 1;
+  }
+
+  /* Adjust x */
+  if (x_relative) {
+    x = info->dwCursorPosition.X + x;
+  }
+  /* Clip x */
+  if (x < 0) {
+    x = 0;
+  } else if (x >= uv_tty_virtual_width) {
+    x = uv_tty_virtual_width - 1;
+  }
+
+  result.X = (unsigned short) x;
+  result.Y = (unsigned short) y;
+  return result;
+}
+
+
+static int uv_tty_emit_text(uv_tty_t* handle, WCHAR buffer[], DWORD length,
+    DWORD* error) {
+  DWORD written;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+  if (!WriteConsoleW(handle->handle,
+                     (void*) buffer,
+                     length,
+                     &written,
+                     NULL)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  return 0;
+}
+
+
+static int uv_tty_move_caret(uv_tty_t* handle, int x, unsigned char x_relative,
+    int y, unsigned char y_relative, DWORD* error) {
+  CONSOLE_SCREEN_BUFFER_INFO info;
+  COORD pos;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+ retry:
+  if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+    *error = GetLastError();
+  }
+
+  pos = uv_tty_make_real_coord(handle, &info, x, x_relative, y, y_relative);
+
+  if (!SetConsoleCursorPosition(handle->handle, pos)) {
+    if (GetLastError() == ERROR_INVALID_PARAMETER) {
+      /* The console may be resized - retry */
+      goto retry;
+    } else {
+      *error = GetLastError();
+      return -1;
+    }
+  }
+
+  return 0;
+}
+
+
+static int uv_tty_reset(uv_tty_t* handle, DWORD* error) {
+  const COORD origin = {0, 0};
+  const WORD char_attrs = uv_tty_default_text_attributes;
+  CONSOLE_SCREEN_BUFFER_INFO info;
+  DWORD count, written;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+  /* Reset original text attributes. */
+  if (!SetConsoleTextAttribute(handle->handle, char_attrs)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  /* Move the cursor position to (0, 0). */
+  if (!SetConsoleCursorPosition(handle->handle, origin)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  /* Clear the screen buffer. */
+ retry:
+  if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  count = info.dwSize.X * info.dwSize.Y;
+
+  if (!(FillConsoleOutputCharacterW(handle->handle,
+                                    L'\x20',
+                                    count,
+                                    origin,
+                                    &written) &&
+        FillConsoleOutputAttribute(handle->handle,
+                                   char_attrs,
+                                   written,
+                                   origin,
+                                   &written))) {
+    if (GetLastError() == ERROR_INVALID_PARAMETER) {
+      /* The console may be resized - retry */
+      goto retry;
+    } else {
+      *error = GetLastError();
+      return -1;
+    }
+  }
+
+  /* Move the virtual window up to the top. */
+  uv_tty_virtual_offset = 0;
+  uv_tty_update_virtual_window(&info);
+
+  return 0;
+}
+
+
+static int uv_tty_clear(uv_tty_t* handle, int dir, char entire_screen,
+    DWORD* error) {
+  CONSOLE_SCREEN_BUFFER_INFO info;
+  COORD start, end;
+  DWORD count, written;
+
+  int x1, x2, y1, y2;
+  int x1r, x2r, y1r, y2r;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+  if (dir == 0) {
+    /* Clear from current position */
+    x1 = 0;
+    x1r = 1;
+  } else {
+    /* Clear from column 0 */
+    x1 = 0;
+    x1r = 0;
+  }
+
+  if (dir == 1) {
+    /* Clear to current position */
+    x2 = 0;
+    x2r = 1;
+  } else {
+    /* Clear to end of row. We pretend the console is 65536 characters wide, */
+    /* uv_tty_make_real_coord will clip it to the actual console width. */
+    x2 = 0xffff;
+    x2r = 0;
+  }
+
+  if (!entire_screen) {
+    /* Stay on our own row */
+    y1 = y2 = 0;
+    y1r = y2r = 1;
+  } else {
+    /* Apply columns direction to row */
+    y1 = x1;
+    y1r = x1r;
+    y2 = x2;
+    y2r = x2r;
+  }
+
+ retry:
+  if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  start = uv_tty_make_real_coord(handle, &info, x1, x1r, y1, y1r);
+  end = uv_tty_make_real_coord(handle, &info, x2, x2r, y2, y2r);
+  count = (end.Y * info.dwSize.X + end.X) -
+          (start.Y * info.dwSize.X + start.X) + 1;
+
+  if (!(FillConsoleOutputCharacterW(handle->handle,
+                              L'\x20',
+                              count,
+                              start,
+                              &written) &&
+        FillConsoleOutputAttribute(handle->handle,
+                                   info.wAttributes,
+                                   written,
+                                   start,
+                                   &written))) {
+    if (GetLastError() == ERROR_INVALID_PARAMETER) {
+      /* The console may be resized - retry */
+      goto retry;
+    } else {
+      *error = GetLastError();
+      return -1;
+    }
+  }
+
+  return 0;
+}
+
+#define FLIP_FGBG                                                             \
+    do {                                                                      \
+      WORD fg = info.wAttributes & 0xF;                                       \
+      WORD bg = info.wAttributes & 0xF0;                                      \
+      info.wAttributes &= 0xFF00;                                             \
+      info.wAttributes |= fg << 4;                                            \
+      info.wAttributes |= bg >> 4;                                            \
+    } while (0)
+
+static int uv_tty_set_style(uv_tty_t* handle, DWORD* error) {
+  unsigned short argc = handle->tty.wr.ansi_csi_argc;
+  unsigned short* argv = handle->tty.wr.ansi_csi_argv;
+  int i;
+  CONSOLE_SCREEN_BUFFER_INFO info;
+
+  char fg_color = -1, bg_color = -1;
+  char fg_bright = -1, bg_bright = -1;
+  char inverse = -1;
+
+  if (argc == 0) {
+    /* Reset mode */
+    fg_color = uv_tty_default_fg_color;
+    bg_color = uv_tty_default_bg_color;
+    fg_bright = uv_tty_default_fg_bright;
+    bg_bright = uv_tty_default_bg_bright;
+    inverse = uv_tty_default_inverse;
+  }
+
+  for (i = 0; i < argc; i++) {
+    short arg = argv[i];
+
+    if (arg == 0) {
+      /* Reset mode */
+      fg_color = uv_tty_default_fg_color;
+      bg_color = uv_tty_default_bg_color;
+      fg_bright = uv_tty_default_fg_bright;
+      bg_bright = uv_tty_default_bg_bright;
+      inverse = uv_tty_default_inverse;
+
+    } else if (arg == 1) {
+      /* Foreground bright on */
+      fg_bright = 1;
+
+    } else if (arg == 2) {
+      /* Both bright off */
+      fg_bright = 0;
+      bg_bright = 0;
+
+    } else if (arg == 5) {
+      /* Background bright on */
+      bg_bright = 1;
+
+    } else if (arg == 7) {
+      /* Inverse: on */
+      inverse = 1;
+
+    } else if (arg == 21 || arg == 22) {
+      /* Foreground bright off */
+      fg_bright = 0;
+
+    } else if (arg == 25) {
+      /* Background bright off */
+      bg_bright = 0;
+
+    } else if (arg == 27) {
+      /* Inverse: off */
+      inverse = 0;
+
+    } else if (arg >= 30 && arg <= 37) {
+      /* Set foreground color */
+      fg_color = arg - 30;
+
+    } else if (arg == 39) {
+      /* Default text color */
+      fg_color = uv_tty_default_fg_color;
+      fg_bright = uv_tty_default_fg_bright;
+
+    } else if (arg >= 40 && arg <= 47) {
+      /* Set background color */
+      bg_color = arg - 40;
+
+    } else if (arg ==  49) {
+      /* Default background color */
+      bg_color = uv_tty_default_bg_color;
+      bg_bright = uv_tty_default_bg_bright;
+
+    } else if (arg >= 90 && arg <= 97) {
+      /* Set bold foreground color */
+      fg_bright = 1;
+      fg_color = arg - 90;
+
+    } else if (arg >= 100 && arg <= 107) {
+      /* Set bold background color */
+      bg_bright = 1;
+      bg_color = arg - 100;
+
+    }
+  }
+
+  if (fg_color == -1 && bg_color == -1 && fg_bright == -1 &&
+      bg_bright == -1 && inverse == -1) {
+    /* Nothing changed */
+    return 0;
+  }
+
+  if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  if ((info.wAttributes & COMMON_LVB_REVERSE_VIDEO) > 0) {
+    FLIP_FGBG;
+  }
+
+  if (fg_color != -1) {
+    info.wAttributes &= ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
+    if (fg_color & 1) info.wAttributes |= FOREGROUND_RED;
+    if (fg_color & 2) info.wAttributes |= FOREGROUND_GREEN;
+    if (fg_color & 4) info.wAttributes |= FOREGROUND_BLUE;
+  }
+
+  if (fg_bright != -1) {
+    if (fg_bright) {
+      info.wAttributes |= FOREGROUND_INTENSITY;
+    } else {
+      info.wAttributes &= ~FOREGROUND_INTENSITY;
+    }
+  }
+
+  if (bg_color != -1) {
+    info.wAttributes &= ~(BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
+    if (bg_color & 1) info.wAttributes |= BACKGROUND_RED;
+    if (bg_color & 2) info.wAttributes |= BACKGROUND_GREEN;
+    if (bg_color & 4) info.wAttributes |= BACKGROUND_BLUE;
+  }
+
+  if (bg_bright != -1) {
+    if (bg_bright) {
+      info.wAttributes |= BACKGROUND_INTENSITY;
+    } else {
+      info.wAttributes &= ~BACKGROUND_INTENSITY;
+    }
+  }
+
+  if (inverse != -1) {
+    if (inverse) {
+      info.wAttributes |= COMMON_LVB_REVERSE_VIDEO;
+    } else {
+      info.wAttributes &= ~COMMON_LVB_REVERSE_VIDEO;
+    }
+  }
+
+  if ((info.wAttributes & COMMON_LVB_REVERSE_VIDEO) > 0) {
+    FLIP_FGBG;
+  }
+
+  if (!SetConsoleTextAttribute(handle->handle, info.wAttributes)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  return 0;
+}
+
+
+static int uv_tty_save_state(uv_tty_t* handle, unsigned char save_attributes,
+    DWORD* error) {
+  CONSOLE_SCREEN_BUFFER_INFO info;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+  if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  uv_tty_update_virtual_window(&info);
+
+  handle->tty.wr.saved_position.X = info.dwCursorPosition.X;
+  handle->tty.wr.saved_position.Y = info.dwCursorPosition.Y - uv_tty_virtual_offset;
+  handle->flags |= UV_HANDLE_TTY_SAVED_POSITION;
+
+  if (save_attributes) {
+    handle->tty.wr.saved_attributes = info.wAttributes &
+        (FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
+    handle->flags |= UV_HANDLE_TTY_SAVED_ATTRIBUTES;
+  }
+
+  return 0;
+}
+
+
+static int uv_tty_restore_state(uv_tty_t* handle,
+    unsigned char restore_attributes, DWORD* error) {
+  CONSOLE_SCREEN_BUFFER_INFO info;
+  WORD new_attributes;
+
+  if (*error != ERROR_SUCCESS) {
+    return -1;
+  }
+
+  if (handle->flags & UV_HANDLE_TTY_SAVED_POSITION) {
+    if (uv_tty_move_caret(handle,
+                          handle->tty.wr.saved_position.X,
+                          0,
+                          handle->tty.wr.saved_position.Y,
+                          0,
+                          error) != 0) {
+      return -1;
+    }
+  }
+
+  if (restore_attributes &&
+      (handle->flags & UV_HANDLE_TTY_SAVED_ATTRIBUTES)) {
+    if (!GetConsoleScreenBufferInfo(handle->handle, &info)) {
+      *error = GetLastError();
+      return -1;
+    }
+
+    new_attributes = info.wAttributes;
+    new_attributes &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
+    new_attributes |= handle->tty.wr.saved_attributes;
+
+    if (!SetConsoleTextAttribute(handle->handle, new_attributes)) {
+      *error = GetLastError();
+      return -1;
+    }
+  }
+
+  return 0;
+}
+
+static int uv_tty_set_cursor_visibility(uv_tty_t* handle,
+                                        BOOL visible,
+                                        DWORD* error) {
+  CONSOLE_CURSOR_INFO cursor_info;
+
+  if (!GetConsoleCursorInfo(handle->handle, &cursor_info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  cursor_info.bVisible = visible;
+
+  if (!SetConsoleCursorInfo(handle->handle, &cursor_info)) {
+    *error = GetLastError();
+    return -1;
+  }
+
+  return 0;
+}
+
+static int uv_tty_write_bufs(uv_tty_t* handle,
+                             const uv_buf_t bufs[],
+                             unsigned int nbufs,
+                             DWORD* error) {
+  /* We can only write 8k characters at a time. Windows can't handle */
+  /* much more characters in a single console write anyway. */
+  WCHAR utf16_buf[8192];
+  DWORD utf16_buf_used = 0;
+  unsigned int i;
+
+#define FLUSH_TEXT()                                                \
+  do {                                                              \
+    if (utf16_buf_used > 0) {                                       \
+      uv_tty_emit_text(handle, utf16_buf, utf16_buf_used, error);   \
+      utf16_buf_used = 0;                                           \
+    }                                                               \
+  } while (0)
+
+#define ENSURE_BUFFER_SPACE(wchars_needed)                          \
+  if (wchars_needed > ARRAY_SIZE(utf16_buf) - utf16_buf_used) {     \
+    FLUSH_TEXT();                                                   \
+  }
+
+  /* Cache for fast access */
+  unsigned char utf8_bytes_left = handle->tty.wr.utf8_bytes_left;
+  unsigned int utf8_codepoint = handle->tty.wr.utf8_codepoint;
+  unsigned char previous_eol = handle->tty.wr.previous_eol;
+  unsigned char ansi_parser_state = handle->tty.wr.ansi_parser_state;
+
+  /* Store the error here. If we encounter an error, stop trying to do i/o */
+  /* but keep parsing the buffer so we leave the parser in a consistent */
+  /* state. */
+  *error = ERROR_SUCCESS;
+
+  uv_sem_wait(&uv_tty_output_lock);
+
+  for (i = 0; i < nbufs; i++) {
+    uv_buf_t buf = bufs[i];
+    unsigned int j;
+
+  if (uv__vterm_state == UV_SUPPORTED) {
+    utf16_buf_used = MultiByteToWideChar(CP_UTF8,
+                                         0,
+                                         buf.base,
+                                         buf.len,
+                                         NULL,
+                                         0);
+
+    if (utf16_buf_used == 0) {
+      *error = GetLastError();
+      break;
+    }
+
+    if (!MultiByteToWideChar(CP_UTF8,
+                             0,
+                             buf.base,
+                             buf.len,
+                             utf16_buf,
+                             utf16_buf_used)) {
+      *error = GetLastError();
+      break;
+    }
+
+    FLUSH_TEXT();
+    continue;
+  }
+
+    for (j = 0; j < buf.len; j++) {
+      unsigned char c = buf.base[j];
+
+      /* Run the character through the utf8 decoder We happily accept non */
+      /* shortest form encodings and invalid code points - there's no real */
+      /* harm that can be done. */
+      if (utf8_bytes_left == 0) {
+        /* Read utf-8 start byte */
+        DWORD first_zero_bit;
+        unsigned char not_c = ~c;
+#ifdef _MSC_VER /* msvc */
+        if (_BitScanReverse(&first_zero_bit, not_c)) {
+#else /* assume gcc */
+        if (c != 0) {
+          first_zero_bit = (sizeof(int) * 8) - 1 - __builtin_clz(not_c);
+#endif
+          if (first_zero_bit == 7) {
+            /* Ascii - pass right through */
+            utf8_codepoint = (unsigned int) c;
+
+          } else if (first_zero_bit <= 5) {
+            /* Multibyte sequence */
+            utf8_codepoint = (0xff >> (8 - first_zero_bit)) & c;
+            utf8_bytes_left = (char) (6 - first_zero_bit);
+
+          } else {
+            /* Invalid continuation */
+            utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
+          }
+
+        } else {
+          /* 0xff -- invalid */
+          utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
+        }
+
+      } else if ((c & 0xc0) == 0x80) {
+        /* Valid continuation of utf-8 multibyte sequence */
+        utf8_bytes_left--;
+        utf8_codepoint <<= 6;
+        utf8_codepoint |= ((unsigned int) c & 0x3f);
+
+      } else {
+        /* Start byte where continuation was expected. */
+        utf8_bytes_left = 0;
+        utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
+        /* Patch buf offset so this character will be parsed again as a */
+        /* start byte. */
+        j--;
+      }
+
+      /* Maybe we need to parse more bytes to find a character. */
+      if (utf8_bytes_left != 0) {
+        continue;
+      }
+
+      /* Parse vt100/ansi escape codes */
+      if (ansi_parser_state == ANSI_NORMAL) {
+        switch (utf8_codepoint) {
+          case '\033':
+            ansi_parser_state = ANSI_ESCAPE_SEEN;
+            continue;
+
+          case 0233:
+            ansi_parser_state = ANSI_CSI;
+            handle->tty.wr.ansi_csi_argc = 0;
+            continue;
+        }
+
+      } else if (ansi_parser_state == ANSI_ESCAPE_SEEN) {
+        switch (utf8_codepoint) {
+          case '[':
+            ansi_parser_state = ANSI_CSI;
+            handle->tty.wr.ansi_csi_argc = 0;
+            continue;
+
+          case '^':
+          case '_':
+          case 'P':
+          case ']':
+            /* Not supported, but we'll have to parse until we see a stop */
+            /* code, e.g. ESC \ or BEL. */
+            ansi_parser_state = ANSI_ST_CONTROL;
+            continue;
+
+          case '\033':
+            /* Ignore double escape. */
+            continue;
+
+          case 'c':
+            /* Full console reset. */
+            FLUSH_TEXT();
+            uv_tty_reset(handle, error);
+            ansi_parser_state = ANSI_NORMAL;
+            continue;
+
+          case '7':
+            /* Save the cursor position and text attributes. */
+            FLUSH_TEXT();
+            uv_tty_save_state(handle, 1, error);
+            ansi_parser_state = ANSI_NORMAL;
+            continue;
+
+           case '8':
+            /* Restore the cursor position and text attributes */
+            FLUSH_TEXT();
+            uv_tty_restore_state(handle, 1, error);
+            ansi_parser_state = ANSI_NORMAL;
+            continue;
+
+          default:
+            if (utf8_codepoint >= '@' && utf8_codepoint <= '_') {
+              /* Single-char control. */
+              ansi_parser_state = ANSI_NORMAL;
+              continue;
+            } else {
+              /* Invalid - proceed as normal, */
+              ansi_parser_state = ANSI_NORMAL;
+            }
+        }
+
+      } else if (ansi_parser_state & ANSI_CSI) {
+        if (!(ansi_parser_state & ANSI_IGNORE)) {
+          if (utf8_codepoint >= '0' && utf8_codepoint <= '9') {
+            /* Parsing a numerical argument */
+
+            if (!(ansi_parser_state & ANSI_IN_ARG)) {
+              /* We were not currently parsing a number */
+
+              /* Check for too many arguments */
+              if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) {
+                ansi_parser_state |= ANSI_IGNORE;
+                continue;
+              }
+
+              ansi_parser_state |= ANSI_IN_ARG;
+              handle->tty.wr.ansi_csi_argc++;
+              handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] =
+                  (unsigned short) utf8_codepoint - '0';
+              continue;
+            } else {
+              /* We were already parsing a number. Parse next digit. */
+              uint32_t value = 10 *
+                  handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1];
+
+              /* Check for overflow. */
+              if (value > UINT16_MAX) {
+                ansi_parser_state |= ANSI_IGNORE;
+                continue;
+              }
+
+               handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] =
+                   (unsigned short) value + (utf8_codepoint - '0');
+               continue;
+            }
+
+          } else if (utf8_codepoint == ';') {
+            /* Denotes the end of an argument. */
+            if (ansi_parser_state & ANSI_IN_ARG) {
+              ansi_parser_state &= ~ANSI_IN_ARG;
+              continue;
+
+            } else {
+              /* If ANSI_IN_ARG is not set, add another argument and */
+              /* default it to 0. */
+              /* Check for too many arguments */
+              if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) {
+                ansi_parser_state |= ANSI_IGNORE;
+                continue;
+              }
+
+              handle->tty.wr.ansi_csi_argc++;
+              handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = 0;
+              continue;
+            }
+
+          } else if (utf8_codepoint == '?' && !(ansi_parser_state & ANSI_IN_ARG) &&
+                     handle->tty.wr.ansi_csi_argc == 0) {
+            /* Ignores '?' if it is the first character after CSI[ */
+            /* This is an extension character from the VT100 codeset */
+            /* that is supported and used by most ANSI terminals today. */
+            continue;
+
+          } else if (utf8_codepoint >= '@' && utf8_codepoint <= '~' &&
+                     (handle->tty.wr.ansi_csi_argc > 0 || utf8_codepoint != '[')) {
+            int x, y, d;
+
+            /* Command byte */
+            switch (utf8_codepoint) {
+              case 'A':
+                /* cursor up */
+                FLUSH_TEXT();
+                y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1);
+                uv_tty_move_caret(handle, 0, 1, y, 1, error);
+                break;
+
+              case 'B':
+                /* cursor down */
+                FLUSH_TEXT();
+                y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1;
+                uv_tty_move_caret(handle, 0, 1, y, 1, error);
+                break;
+
+              case 'C':
+                /* cursor forward */
+                FLUSH_TEXT();
+                x = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1;
+                uv_tty_move_caret(handle, x, 1, 0, 1, error);
+                break;
+
+              case 'D':
+                /* cursor back */
+                FLUSH_TEXT();
+                x = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1);
+                uv_tty_move_caret(handle, x, 1, 0, 1, error);
+                break;
+
+              case 'E':
+                /* cursor next line */
+                FLUSH_TEXT();
+                y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1;
+                uv_tty_move_caret(handle, 0, 0, y, 1, error);
+                break;
+
+              case 'F':
+                /* cursor previous line */
+                FLUSH_TEXT();
+                y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1);
+                uv_tty_move_caret(handle, 0, 0, y, 1, error);
+                break;
+
+              case 'G':
+                /* cursor horizontal move absolute */
+                FLUSH_TEXT();
+                x = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0])
+                  ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0;
+                uv_tty_move_caret(handle, x, 0, 0, 1, error);
+                break;
+
+              case 'H':
+              case 'f':
+                /* cursor move absolute */
+                FLUSH_TEXT();
+                y = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0])
+                  ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0;
+                x = (handle->tty.wr.ansi_csi_argc >= 2 && handle->tty.wr.ansi_csi_argv[1])
+                  ? handle->tty.wr.ansi_csi_argv[1] - 1 : 0;
+                uv_tty_move_caret(handle, x, 0, y, 0, error);
+                break;
+
+              case 'J':
+                /* Erase screen */
+                FLUSH_TEXT();
+                d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0;
+                if (d >= 0 && d <= 2) {
+                  uv_tty_clear(handle, d, 1, error);
+                }
+                break;
+
+              case 'K':
+                /* Erase line */
+                FLUSH_TEXT();
+                d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0;
+                if (d >= 0 && d <= 2) {
+                  uv_tty_clear(handle, d, 0, error);
+                }
+                break;
+
+              case 'm':
+                /* Set style */
+                FLUSH_TEXT();
+                uv_tty_set_style(handle, error);
+                break;
+
+              case 's':
+                /* Save the cursor position. */
+                FLUSH_TEXT();
+                uv_tty_save_state(handle, 0, error);
+                break;
+
+              case 'u':
+                /* Restore the cursor position */
+                FLUSH_TEXT();
+                uv_tty_restore_state(handle, 0, error);
+                break;
+
+              case 'l':
+                /* Hide the cursor */
+                if (handle->tty.wr.ansi_csi_argc == 1 &&
+                    handle->tty.wr.ansi_csi_argv[0] == 25) {
+                  FLUSH_TEXT();
+                  uv_tty_set_cursor_visibility(handle, 0, error);
+                }
+                break;
+
+              case 'h':
+                /* Show the cursor */
+                if (handle->tty.wr.ansi_csi_argc == 1 &&
+                    handle->tty.wr.ansi_csi_argv[0] == 25) {
+                  FLUSH_TEXT();
+                  uv_tty_set_cursor_visibility(handle, 1, error);
+                }
+                break;
+            }
+
+            /* Sequence ended - go back to normal state. */
+            ansi_parser_state = ANSI_NORMAL;
+            continue;
+
+          } else {
+            /* We don't support commands that use private mode characters or */
+            /* intermediaries. Ignore the rest of the sequence. */
+            ansi_parser_state |= ANSI_IGNORE;
+            continue;
+          }
+        } else {
+          /* We're ignoring this command. Stop only on command character. */
+          if (utf8_codepoint >= '@' && utf8_codepoint <= '~') {
+            ansi_parser_state = ANSI_NORMAL;
+          }
+          continue;
+        }
+
+      } else if (ansi_parser_state & ANSI_ST_CONTROL) {
+        /* Unsupported control code */
+        /* Ignore everything until we see BEL or ESC \ */
+        if (ansi_parser_state & ANSI_IN_STRING) {
+          if (!(ansi_parser_state & ANSI_BACKSLASH_SEEN)) {
+            if (utf8_codepoint == '"') {
+              ansi_parser_state &= ~ANSI_IN_STRING;
+            } else if (utf8_codepoint == '\\') {
+              ansi_parser_state |= ANSI_BACKSLASH_SEEN;
+            }
+          } else {
+            ansi_parser_state &= ~ANSI_BACKSLASH_SEEN;
+          }
+        } else {
+          if (utf8_codepoint == '\007' || (utf8_codepoint == '\\' &&
+              (ansi_parser_state & ANSI_ESCAPE_SEEN))) {
+            /* End of sequence */
+            ansi_parser_state = ANSI_NORMAL;
+          } else if (utf8_codepoint == '\033') {
+            /* Escape character */
+            ansi_parser_state |= ANSI_ESCAPE_SEEN;
+          } else if (utf8_codepoint == '"') {
+             /* String starting */
+            ansi_parser_state |= ANSI_IN_STRING;
+            ansi_parser_state &= ~ANSI_ESCAPE_SEEN;
+            ansi_parser_state &= ~ANSI_BACKSLASH_SEEN;
+          } else {
+            ansi_parser_state &= ~ANSI_ESCAPE_SEEN;
+          }
+        }
+        continue;
+      } else {
+        /* Inconsistent state */
+        abort();
+      }
+
+      /* We wouldn't mind emitting utf-16 surrogate pairs. Too bad, the */
+      /* windows console doesn't really support UTF-16, so just emit the */
+      /* replacement character. */
+      if (utf8_codepoint > 0xffff) {
+        utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
+      }
+
+      if (utf8_codepoint == 0x0a || utf8_codepoint == 0x0d) {
+        /* EOL conversion - emit \r\n when we see \n. */
+
+        if (utf8_codepoint == 0x0a && previous_eol != 0x0d) {
+          /* \n was not preceded by \r; print \r\n. */
+          ENSURE_BUFFER_SPACE(2);
+          utf16_buf[utf16_buf_used++] = L'\r';
+          utf16_buf[utf16_buf_used++] = L'\n';
+        } else if (utf8_codepoint == 0x0d && previous_eol == 0x0a) {
+          /* \n was followed by \r; do not print the \r, since */
+          /* the source was either \r\n\r (so the second \r is */
+          /* redundant) or was \n\r (so the \n was processed */
+          /* by the last case and an \r automatically inserted). */
+        } else {
+          /* \r without \n; print \r as-is. */
+          ENSURE_BUFFER_SPACE(1);
+          utf16_buf[utf16_buf_used++] = (WCHAR) utf8_codepoint;
+        }
+
+        previous_eol = (char) utf8_codepoint;
+
+      } else if (utf8_codepoint <= 0xffff) {
+        /* Encode character into utf-16 buffer. */
+        ENSURE_BUFFER_SPACE(1);
+        utf16_buf[utf16_buf_used++] = (WCHAR) utf8_codepoint;
+        previous_eol = 0;
+      }
+    }
+  }
+
+  /* Flush remaining characters */
+  FLUSH_TEXT();
+
+  /* Copy cached values back to struct. */
+  handle->tty.wr.utf8_bytes_left = utf8_bytes_left;
+  handle->tty.wr.utf8_codepoint = utf8_codepoint;
+  handle->tty.wr.previous_eol = previous_eol;
+  handle->tty.wr.ansi_parser_state = ansi_parser_state;
+
+  uv_sem_post(&uv_tty_output_lock);
+
+  if (*error == STATUS_SUCCESS) {
+    return 0;
+  } else {
+    return -1;
+  }
+
+#undef FLUSH_TEXT
+}
+
+
+int uv_tty_write(uv_loop_t* loop,
+                 uv_write_t* req,
+                 uv_tty_t* handle,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs,
+                 uv_write_cb cb) {
+  DWORD error;
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_WRITE;
+  req->handle = (uv_stream_t*) handle;
+  req->cb = cb;
+
+  handle->reqs_pending++;
+  handle->stream.conn.write_reqs_pending++;
+  REGISTER_HANDLE_REQ(loop, handle, req);
+
+  req->u.io.queued_bytes = 0;
+
+  if (!uv_tty_write_bufs(handle, bufs, nbufs, &error)) {
+    SET_REQ_SUCCESS(req);
+  } else {
+    SET_REQ_ERROR(req, error);
+  }
+
+  uv_insert_pending_req(loop, (uv_req_t*) req);
+
+  return 0;
+}
+
+
+int uv__tty_try_write(uv_tty_t* handle,
+                      const uv_buf_t bufs[],
+                      unsigned int nbufs) {
+  DWORD error;
+
+  if (handle->stream.conn.write_reqs_pending > 0)
+    return UV_EAGAIN;
+
+  if (uv_tty_write_bufs(handle, bufs, nbufs, &error))
+    return uv_translate_sys_error(error);
+
+  return uv__count_bufs(bufs, nbufs);
+}
+
+
+void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle,
+  uv_write_t* req) {
+  int err;
+
+  handle->write_queue_size -= req->u.io.queued_bytes;
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (req->cb) {
+    err = GET_REQ_ERROR(req);
+    req->cb(req, uv_translate_sys_error(err));
+  }
+
+  handle->stream.conn.write_reqs_pending--;
+  if (handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+    uv_want_endgame(loop, (uv_handle_t*)handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_tty_close(uv_tty_t* handle) {
+  assert(handle->u.fd == -1 || handle->u.fd > 2);
+  if (handle->u.fd == -1)
+    CloseHandle(handle->handle);
+  else
+    close(handle->u.fd);
+
+  if (handle->flags & UV_HANDLE_READING)
+    uv_tty_read_stop(handle);
+
+  handle->u.fd = -1;
+  handle->handle = INVALID_HANDLE_VALUE;
+  handle->flags &= ~(UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
+  uv__handle_closing(handle);
+
+  if (handle->reqs_pending == 0) {
+    uv_want_endgame(handle->loop, (uv_handle_t*) handle);
+  }
+}
+
+
+void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle) {
+  if (!(handle->flags & UV_HANDLE_TTY_READABLE) &&
+      handle->stream.conn.shutdown_req != NULL &&
+      handle->stream.conn.write_reqs_pending == 0) {
+    UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req);
+
+    /* TTY shutdown is really just a no-op */
+    if (handle->stream.conn.shutdown_req->cb) {
+      if (handle->flags & UV__HANDLE_CLOSING) {
+        handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, UV_ECANCELED);
+      } else {
+        handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, 0);
+      }
+    }
+
+    handle->stream.conn.shutdown_req = NULL;
+
+    DECREASE_PENDING_REQ_COUNT(handle);
+    return;
+  }
+
+  if (handle->flags & UV__HANDLE_CLOSING &&
+      handle->reqs_pending == 0) {
+    /* The wait handle used for raw reading should be unregistered when the */
+    /* wait callback runs. */
+    assert(!(handle->flags & UV_HANDLE_TTY_READABLE) ||
+           handle->tty.rd.read_raw_wait == NULL);
+
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+    uv__handle_close(handle);
+  }
+}
+
+
+/* TODO: remove me */
+void uv_process_tty_accept_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_req_t* raw_req) {
+  abort();
+}
+
+
+/* TODO: remove me */
+void uv_process_tty_connect_req(uv_loop_t* loop, uv_tty_t* handle,
+    uv_connect_t* req) {
+  abort();
+}
+
+
+int uv_tty_reset_mode(void) {
+  /* Not necessary to do anything. */
+  return 0;
+}
+
+/* Determine whether or not this version of windows supports
+ * proper ANSI color codes. Should be supported as of windows
+ * 10 version 1511, build number 10.0.10586.
+ */
+static void uv__determine_vterm_state(HANDLE handle) {
+  DWORD dwMode = 0;
+
+  if (!GetConsoleMode(handle, &dwMode)) {
+    uv__vterm_state = UV_UNSUPPORTED;
+    return;
+  }
+
+  dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
+  if (!SetConsoleMode(handle, dwMode)) {
+    uv__vterm_state = UV_UNSUPPORTED;
+    return;
+  }
+
+  uv__vterm_state = UV_SUPPORTED;
+}
diff --git a/Utilities/cmlibuv/src/win/udp.c b/Utilities/cmlibuv/src/win/udp.c
new file mode 100644
index 0000000..9bf1453
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/udp.c
@@ -0,0 +1,928 @@
+/* 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 <assert.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+#include "handle-inl.h"
+#include "stream-inl.h"
+#include "req-inl.h"
+
+
+/*
+ * Threshold of active udp streams for which to preallocate udp read buffers.
+ */
+const unsigned int uv_active_udp_streams_threshold = 0;
+
+/* A zero-size buffer for use by uv_udp_read */
+static char uv_zero_[] = "";
+
+int uv_udp_getsockname(const uv_udp_t* handle,
+                       struct sockaddr* name,
+                       int* namelen) {
+  int result;
+
+  if (handle->socket == INVALID_SOCKET) {
+    return UV_EINVAL;
+  }
+
+  result = getsockname(handle->socket, name, namelen);
+  if (result != 0) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+static int uv_udp_set_socket(uv_loop_t* loop, uv_udp_t* handle, SOCKET socket,
+    int family) {
+  DWORD yes = 1;
+  WSAPROTOCOL_INFOW info;
+  int opt_len;
+
+  if (handle->socket != INVALID_SOCKET)
+    return UV_EBUSY;
+
+  /* Set the socket to nonblocking mode */
+  if (ioctlsocket(socket, FIONBIO, &yes) == SOCKET_ERROR) {
+    return WSAGetLastError();
+  }
+
+  /* Make the socket non-inheritable */
+  if (!SetHandleInformation((HANDLE)socket, HANDLE_FLAG_INHERIT, 0)) {
+    return GetLastError();
+  }
+
+  /* Associate it with the I/O completion port. */
+  /* Use uv_handle_t pointer as completion key. */
+  if (CreateIoCompletionPort((HANDLE)socket,
+                             loop->iocp,
+                             (ULONG_PTR)socket,
+                             0) == NULL) {
+    return GetLastError();
+  }
+
+  if (pSetFileCompletionNotificationModes) {
+    /* All known Windows that support SetFileCompletionNotificationModes */
+    /* have a bug that makes it impossible to use this function in */
+    /* conjunction with datagram sockets. We can work around that but only */
+    /* if the user is using the default UDP driver (AFD) and has no other */
+    /* LSPs stacked on top. Here we check whether that is the case. */
+    opt_len = (int) sizeof info;
+    if (getsockopt(socket,
+                   SOL_SOCKET,
+                   SO_PROTOCOL_INFOW,
+                   (char*) &info,
+                   &opt_len) == SOCKET_ERROR) {
+      return GetLastError();
+    }
+
+    if (info.ProtocolChain.ChainLen == 1) {
+      if (pSetFileCompletionNotificationModes((HANDLE)socket,
+          FILE_SKIP_SET_EVENT_ON_HANDLE |
+          FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)) {
+        handle->flags |= UV_HANDLE_SYNC_BYPASS_IOCP;
+        handle->func_wsarecv = uv_wsarecv_workaround;
+        handle->func_wsarecvfrom = uv_wsarecvfrom_workaround;
+      } else if (GetLastError() != ERROR_INVALID_FUNCTION) {
+        return GetLastError();
+      }
+    }
+  }
+
+  handle->socket = socket;
+
+  if (family == AF_INET6) {
+    handle->flags |= UV_HANDLE_IPV6;
+  } else {
+    assert(!(handle->flags & UV_HANDLE_IPV6));
+  }
+
+  return 0;
+}
+
+
+int uv_udp_init_ex(uv_loop_t* loop, uv_udp_t* handle, unsigned int flags) {
+  int domain;
+
+  /* Use the lower 8 bits for the domain */
+  domain = flags & 0xFF;
+  if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNSPEC)
+    return UV_EINVAL;
+
+  if (flags & ~0xFF)
+    return UV_EINVAL;
+
+  uv__handle_init(loop, (uv_handle_t*) handle, UV_UDP);
+  handle->socket = INVALID_SOCKET;
+  handle->reqs_pending = 0;
+  handle->activecnt = 0;
+  handle->func_wsarecv = WSARecv;
+  handle->func_wsarecvfrom = WSARecvFrom;
+  handle->send_queue_size = 0;
+  handle->send_queue_count = 0;
+  uv_req_init(loop, (uv_req_t*) &(handle->recv_req));
+  handle->recv_req.type = UV_UDP_RECV;
+  handle->recv_req.data = handle;
+
+  /* If anything fails beyond this point we need to remove the handle from
+   * the handle queue, since it was added by uv__handle_init.
+   */
+
+  if (domain != AF_UNSPEC) {
+    SOCKET sock;
+    DWORD err;
+
+    sock = socket(domain, SOCK_DGRAM, 0);
+    if (sock == INVALID_SOCKET) {
+      err = WSAGetLastError();
+      QUEUE_REMOVE(&handle->handle_queue);
+      return uv_translate_sys_error(err);
+    }
+
+    err = uv_udp_set_socket(handle->loop, handle, sock, domain);
+    if (err) {
+      closesocket(sock);
+      QUEUE_REMOVE(&handle->handle_queue);
+      return uv_translate_sys_error(err);
+    }
+  }
+
+  return 0;
+}
+
+
+int uv_udp_init(uv_loop_t* loop, uv_udp_t* handle) {
+  return uv_udp_init_ex(loop, handle, AF_UNSPEC);
+}
+
+
+void uv_udp_close(uv_loop_t* loop, uv_udp_t* handle) {
+  uv_udp_recv_stop(handle);
+  closesocket(handle->socket);
+  handle->socket = INVALID_SOCKET;
+
+  uv__handle_closing(handle);
+
+  if (handle->reqs_pending == 0) {
+    uv_want_endgame(loop, (uv_handle_t*) handle);
+  }
+}
+
+
+void uv_udp_endgame(uv_loop_t* loop, uv_udp_t* handle) {
+  if (handle->flags & UV__HANDLE_CLOSING &&
+      handle->reqs_pending == 0) {
+    assert(!(handle->flags & UV_HANDLE_CLOSED));
+    uv__handle_close(handle);
+  }
+}
+
+
+static int uv_udp_maybe_bind(uv_udp_t* handle,
+                             const struct sockaddr* addr,
+                             unsigned int addrlen,
+                             unsigned int flags) {
+  int r;
+  int err;
+  DWORD no = 0;
+
+  if (handle->flags & UV_HANDLE_BOUND)
+    return 0;
+
+  if ((flags & UV_UDP_IPV6ONLY) && addr->sa_family != AF_INET6) {
+    /* UV_UDP_IPV6ONLY is supported only for IPV6 sockets */
+    return ERROR_INVALID_PARAMETER;
+  }
+
+  if (handle->socket == INVALID_SOCKET) {
+    SOCKET sock = socket(addr->sa_family, SOCK_DGRAM, 0);
+    if (sock == INVALID_SOCKET) {
+      return WSAGetLastError();
+    }
+
+    err = uv_udp_set_socket(handle->loop, handle, sock, addr->sa_family);
+    if (err) {
+      closesocket(sock);
+      return err;
+    }
+  }
+
+  if (flags & UV_UDP_REUSEADDR) {
+    DWORD yes = 1;
+    /* Set SO_REUSEADDR on the socket. */
+    if (setsockopt(handle->socket,
+                   SOL_SOCKET,
+                   SO_REUSEADDR,
+                   (char*) &yes,
+                   sizeof yes) == SOCKET_ERROR) {
+      err = WSAGetLastError();
+      return err;
+    }
+  }
+
+  if (addr->sa_family == AF_INET6)
+    handle->flags |= UV_HANDLE_IPV6;
+
+  if (addr->sa_family == AF_INET6 && !(flags & UV_UDP_IPV6ONLY)) {
+    /* On windows IPV6ONLY is on by default. */
+    /* If the user doesn't specify it libuv turns it off. */
+
+    /* TODO: how to handle errors? This may fail if there is no ipv4 stack */
+    /* available, or when run on XP/2003 which have no support for dualstack */
+    /* sockets. For now we're silently ignoring the error. */
+    setsockopt(handle->socket,
+               IPPROTO_IPV6,
+               IPV6_V6ONLY,
+               (char*) &no,
+               sizeof no);
+  }
+
+  r = bind(handle->socket, addr, addrlen);
+  if (r == SOCKET_ERROR) {
+    return WSAGetLastError();
+  }
+
+  handle->flags |= UV_HANDLE_BOUND;
+
+  return 0;
+}
+
+
+static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) {
+  uv_req_t* req;
+  uv_buf_t buf;
+  DWORD bytes, flags;
+  int result;
+
+  assert(handle->flags & UV_HANDLE_READING);
+  assert(!(handle->flags & UV_HANDLE_READ_PENDING));
+
+  req = &handle->recv_req;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  /*
+   * Preallocate a read buffer if the number of active streams is below
+   * the threshold.
+  */
+  if (loop->active_udp_streams < uv_active_udp_streams_threshold) {
+    handle->flags &= ~UV_HANDLE_ZERO_READ;
+
+    handle->recv_buffer = uv_buf_init(NULL, 0);
+    handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->recv_buffer);
+    if (handle->recv_buffer.base == NULL || handle->recv_buffer.len == 0) {
+      handle->recv_cb(handle, UV_ENOBUFS, &handle->recv_buffer, NULL, 0);
+      return;
+    }
+    assert(handle->recv_buffer.base != NULL);
+
+    buf = handle->recv_buffer;
+    memset(&handle->recv_from, 0, sizeof handle->recv_from);
+    handle->recv_from_len = sizeof handle->recv_from;
+    flags = 0;
+
+    result = handle->func_wsarecvfrom(handle->socket,
+                                      (WSABUF*) &buf,
+                                      1,
+                                      &bytes,
+                                      &flags,
+                                      (struct sockaddr*) &handle->recv_from,
+                                      &handle->recv_from_len,
+                                      &req->u.io.overlapped,
+                                      NULL);
+
+    if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
+      /* Process the req without IOCP. */
+      handle->flags |= UV_HANDLE_READ_PENDING;
+      req->u.io.overlapped.InternalHigh = bytes;
+      handle->reqs_pending++;
+      uv_insert_pending_req(loop, req);
+    } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
+      /* The req will be processed with IOCP. */
+      handle->flags |= UV_HANDLE_READ_PENDING;
+      handle->reqs_pending++;
+    } else {
+      /* Make this req pending reporting an error. */
+      SET_REQ_ERROR(req, WSAGetLastError());
+      uv_insert_pending_req(loop, req);
+      handle->reqs_pending++;
+    }
+
+  } else {
+    handle->flags |= UV_HANDLE_ZERO_READ;
+
+    buf.base = (char*) uv_zero_;
+    buf.len = 0;
+    flags = MSG_PEEK;
+
+    result = handle->func_wsarecv(handle->socket,
+                                  (WSABUF*) &buf,
+                                  1,
+                                  &bytes,
+                                  &flags,
+                                  &req->u.io.overlapped,
+                                  NULL);
+
+    if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
+      /* Process the req without IOCP. */
+      handle->flags |= UV_HANDLE_READ_PENDING;
+      req->u.io.overlapped.InternalHigh = bytes;
+      handle->reqs_pending++;
+      uv_insert_pending_req(loop, req);
+    } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
+      /* The req will be processed with IOCP. */
+      handle->flags |= UV_HANDLE_READ_PENDING;
+      handle->reqs_pending++;
+    } else {
+      /* Make this req pending reporting an error. */
+      SET_REQ_ERROR(req, WSAGetLastError());
+      uv_insert_pending_req(loop, req);
+      handle->reqs_pending++;
+    }
+  }
+}
+
+
+int uv__udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloc_cb,
+    uv_udp_recv_cb recv_cb) {
+  uv_loop_t* loop = handle->loop;
+  int err;
+
+  if (handle->flags & UV_HANDLE_READING) {
+    return WSAEALREADY;
+  }
+
+  err = uv_udp_maybe_bind(handle,
+                          (const struct sockaddr*) &uv_addr_ip4_any_,
+                          sizeof(uv_addr_ip4_any_),
+                          0);
+  if (err)
+    return err;
+
+  handle->flags |= UV_HANDLE_READING;
+  INCREASE_ACTIVE_COUNT(loop, handle);
+  loop->active_udp_streams++;
+
+  handle->recv_cb = recv_cb;
+  handle->alloc_cb = alloc_cb;
+
+  /* If reading was stopped and then started again, there could still be a */
+  /* recv request pending. */
+  if (!(handle->flags & UV_HANDLE_READ_PENDING))
+    uv_udp_queue_recv(loop, handle);
+
+  return 0;
+}
+
+
+int uv__udp_recv_stop(uv_udp_t* handle) {
+  if (handle->flags & UV_HANDLE_READING) {
+    handle->flags &= ~UV_HANDLE_READING;
+    handle->loop->active_udp_streams--;
+    DECREASE_ACTIVE_COUNT(loop, handle);
+  }
+
+  return 0;
+}
+
+
+static int uv__send(uv_udp_send_t* req,
+                    uv_udp_t* handle,
+                    const uv_buf_t bufs[],
+                    unsigned int nbufs,
+                    const struct sockaddr* addr,
+                    unsigned int addrlen,
+                    uv_udp_send_cb cb) {
+  uv_loop_t* loop = handle->loop;
+  DWORD result, bytes;
+
+  uv_req_init(loop, (uv_req_t*) req);
+  req->type = UV_UDP_SEND;
+  req->handle = handle;
+  req->cb = cb;
+  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
+
+  result = WSASendTo(handle->socket,
+                     (WSABUF*)bufs,
+                     nbufs,
+                     &bytes,
+                     0,
+                     addr,
+                     addrlen,
+                     &req->u.io.overlapped,
+                     NULL);
+
+  if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
+    /* Request completed immediately. */
+    req->u.io.queued_bytes = 0;
+    handle->reqs_pending++;
+    handle->send_queue_size += req->u.io.queued_bytes;
+    handle->send_queue_count++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+    uv_insert_pending_req(loop, (uv_req_t*)req);
+  } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
+    /* Request queued by the kernel. */
+    req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs);
+    handle->reqs_pending++;
+    handle->send_queue_size += req->u.io.queued_bytes;
+    handle->send_queue_count++;
+    REGISTER_HANDLE_REQ(loop, handle, req);
+  } else {
+    /* Send failed due to an error. */
+    return WSAGetLastError();
+  }
+
+  return 0;
+}
+
+
+void uv_process_udp_recv_req(uv_loop_t* loop, uv_udp_t* handle,
+    uv_req_t* req) {
+  uv_buf_t buf;
+  int partial;
+
+  assert(handle->type == UV_UDP);
+
+  handle->flags &= ~UV_HANDLE_READ_PENDING;
+
+  if (!REQ_SUCCESS(req)) {
+    DWORD err = GET_REQ_SOCK_ERROR(req);
+    if (err == WSAEMSGSIZE) {
+      /* Not a real error, it just indicates that the received packet */
+      /* was bigger than the receive buffer. */
+    } else if (err == WSAECONNRESET || err == WSAENETRESET) {
+      /* A previous sendto operation failed; ignore this error. If */
+      /* zero-reading we need to call WSARecv/WSARecvFrom _without_ the */
+      /* MSG_PEEK flag to clear out the error queue. For nonzero reads, */
+      /* immediately queue a new receive. */
+      if (!(handle->flags & UV_HANDLE_ZERO_READ)) {
+        goto done;
+      }
+    } else {
+      /* A real error occurred. Report the error to the user only if we're */
+      /* currently reading. */
+      if (handle->flags & UV_HANDLE_READING) {
+        uv_udp_recv_stop(handle);
+        buf = (handle->flags & UV_HANDLE_ZERO_READ) ?
+              uv_buf_init(NULL, 0) : handle->recv_buffer;
+        handle->recv_cb(handle, uv_translate_sys_error(err), &buf, NULL, 0);
+      }
+      goto done;
+    }
+  }
+
+  if (!(handle->flags & UV_HANDLE_ZERO_READ)) {
+    /* Successful read */
+    partial = !REQ_SUCCESS(req);
+    handle->recv_cb(handle,
+                    req->u.io.overlapped.InternalHigh,
+                    &handle->recv_buffer,
+                    (const struct sockaddr*) &handle->recv_from,
+                    partial ? UV_UDP_PARTIAL : 0);
+  } else if (handle->flags & UV_HANDLE_READING) {
+    DWORD bytes, err, flags;
+    struct sockaddr_storage from;
+    int from_len;
+
+    /* Do a nonblocking receive */
+    /* TODO: try to read multiple datagrams at once. FIONREAD maybe? */
+    buf = uv_buf_init(NULL, 0);
+    handle->alloc_cb((uv_handle_t*) handle, 65536, &buf);
+    if (buf.base == NULL || buf.len == 0) {
+      handle->recv_cb(handle, UV_ENOBUFS, &buf, NULL, 0);
+      goto done;
+    }
+    assert(buf.base != NULL);
+
+    memset(&from, 0, sizeof from);
+    from_len = sizeof from;
+
+    flags = 0;
+
+    if (WSARecvFrom(handle->socket,
+                    (WSABUF*)&buf,
+                    1,
+                    &bytes,
+                    &flags,
+                    (struct sockaddr*) &from,
+                    &from_len,
+                    NULL,
+                    NULL) != SOCKET_ERROR) {
+
+      /* Message received */
+      handle->recv_cb(handle, bytes, &buf, (const struct sockaddr*) &from, 0);
+    } else {
+      err = WSAGetLastError();
+      if (err == WSAEMSGSIZE) {
+        /* Message truncated */
+        handle->recv_cb(handle,
+                        bytes,
+                        &buf,
+                        (const struct sockaddr*) &from,
+                        UV_UDP_PARTIAL);
+      } else if (err == WSAEWOULDBLOCK) {
+        /* Kernel buffer empty */
+        handle->recv_cb(handle, 0, &buf, NULL, 0);
+      } else if (err == WSAECONNRESET || err == WSAENETRESET) {
+        /* WSAECONNRESET/WSANETRESET is ignored because this just indicates
+         * that a previous sendto operation failed.
+         */
+        handle->recv_cb(handle, 0, &buf, NULL, 0);
+      } else {
+        /* Any other error that we want to report back to the user. */
+        uv_udp_recv_stop(handle);
+        handle->recv_cb(handle, uv_translate_sys_error(err), &buf, NULL, 0);
+      }
+    }
+  }
+
+done:
+  /* Post another read if still reading and not closing. */
+  if ((handle->flags & UV_HANDLE_READING) &&
+      !(handle->flags & UV_HANDLE_READ_PENDING)) {
+    uv_udp_queue_recv(loop, handle);
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+void uv_process_udp_send_req(uv_loop_t* loop, uv_udp_t* handle,
+    uv_udp_send_t* req) {
+  int err;
+
+  assert(handle->type == UV_UDP);
+
+  assert(handle->send_queue_size >= req->u.io.queued_bytes);
+  assert(handle->send_queue_count >= 1);
+  handle->send_queue_size -= req->u.io.queued_bytes;
+  handle->send_queue_count--;
+
+  UNREGISTER_HANDLE_REQ(loop, handle, req);
+
+  if (req->cb) {
+    err = 0;
+    if (!REQ_SUCCESS(req)) {
+      err = GET_REQ_SOCK_ERROR(req);
+    }
+    req->cb(req, uv_translate_sys_error(err));
+  }
+
+  DECREASE_PENDING_REQ_COUNT(handle);
+}
+
+
+static int uv__udp_set_membership4(uv_udp_t* handle,
+                                   const struct sockaddr_in* multicast_addr,
+                                   const char* interface_addr,
+                                   uv_membership membership) {
+  int err;
+  int optname;
+  struct ip_mreq mreq;
+
+  if (handle->flags & UV_HANDLE_IPV6)
+    return UV_EINVAL;
+
+  /* If the socket is unbound, bind to inaddr_any. */
+  err = uv_udp_maybe_bind(handle,
+                          (const struct sockaddr*) &uv_addr_ip4_any_,
+                          sizeof(uv_addr_ip4_any_),
+                          UV_UDP_REUSEADDR);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  memset(&mreq, 0, sizeof mreq);
+
+  if (interface_addr) {
+    err = uv_inet_pton(AF_INET, interface_addr, &mreq.imr_interface.s_addr);
+    if (err)
+      return err;
+  } else {
+    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
+  }
+
+  mreq.imr_multiaddr.s_addr = multicast_addr->sin_addr.s_addr;
+
+  switch (membership) {
+    case UV_JOIN_GROUP:
+      optname = IP_ADD_MEMBERSHIP;
+      break;
+    case UV_LEAVE_GROUP:
+      optname = IP_DROP_MEMBERSHIP;
+      break;
+    default:
+      return UV_EINVAL;
+  }
+
+  if (setsockopt(handle->socket,
+                 IPPROTO_IP,
+                 optname,
+                 (char*) &mreq,
+                 sizeof mreq) == SOCKET_ERROR) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+int uv__udp_set_membership6(uv_udp_t* handle,
+                            const struct sockaddr_in6* multicast_addr,
+                            const char* interface_addr,
+                            uv_membership membership) {
+  int optname;
+  int err;
+  struct ipv6_mreq mreq;
+  struct sockaddr_in6 addr6;
+
+  if ((handle->flags & UV_HANDLE_BOUND) && !(handle->flags & UV_HANDLE_IPV6))
+    return UV_EINVAL;
+
+  err = uv_udp_maybe_bind(handle,
+                          (const struct sockaddr*) &uv_addr_ip6_any_,
+                          sizeof(uv_addr_ip6_any_),
+                          UV_UDP_REUSEADDR);
+
+  if (err)
+    return uv_translate_sys_error(err);
+
+  memset(&mreq, 0, sizeof(mreq));
+
+  if (interface_addr) {
+    if (uv_ip6_addr(interface_addr, 0, &addr6))
+      return UV_EINVAL;
+    mreq.ipv6mr_interface = addr6.sin6_scope_id;
+  } else {
+    mreq.ipv6mr_interface = 0;
+  }
+
+  mreq.ipv6mr_multiaddr = multicast_addr->sin6_addr;
+
+  switch (membership) {
+  case UV_JOIN_GROUP:
+    optname = IPV6_ADD_MEMBERSHIP;
+    break;
+  case UV_LEAVE_GROUP:
+    optname = IPV6_DROP_MEMBERSHIP;
+    break;
+  default:
+    return UV_EINVAL;
+  }
+
+  if (setsockopt(handle->socket,
+                 IPPROTO_IPV6,
+                 optname,
+                 (char*) &mreq,
+                 sizeof mreq) == SOCKET_ERROR) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+int uv_udp_set_membership(uv_udp_t* handle,
+                          const char* multicast_addr,
+                          const char* interface_addr,
+                          uv_membership membership) {
+  struct sockaddr_in addr4;
+  struct sockaddr_in6 addr6;
+
+  if (uv_ip4_addr(multicast_addr, 0, &addr4) == 0)
+    return uv__udp_set_membership4(handle, &addr4, interface_addr, membership);
+  else if (uv_ip6_addr(multicast_addr, 0, &addr6) == 0)
+    return uv__udp_set_membership6(handle, &addr6, interface_addr, membership);
+  else
+    return UV_EINVAL;
+}
+
+
+int uv_udp_set_multicast_interface(uv_udp_t* handle, const char* interface_addr) {
+  struct sockaddr_storage addr_st;
+  struct sockaddr_in* addr4;
+  struct sockaddr_in6* addr6;
+
+  addr4 = (struct sockaddr_in*) &addr_st;
+  addr6 = (struct sockaddr_in6*) &addr_st;
+
+  if (!interface_addr) {
+    memset(&addr_st, 0, sizeof addr_st);
+    if (handle->flags & UV_HANDLE_IPV6) {
+      addr_st.ss_family = AF_INET6;
+      addr6->sin6_scope_id = 0;
+    } else {
+      addr_st.ss_family = AF_INET;
+      addr4->sin_addr.s_addr = htonl(INADDR_ANY);
+    }
+  } else if (uv_ip4_addr(interface_addr, 0, addr4) == 0) {
+    /* nothing, address was parsed */
+  } else if (uv_ip6_addr(interface_addr, 0, addr6) == 0) {
+    /* nothing, address was parsed */
+  } else {
+    return UV_EINVAL;
+  }
+
+  if (!(handle->flags & UV_HANDLE_BOUND))
+    return UV_EBADF;
+
+  if (addr_st.ss_family == AF_INET) {
+    if (setsockopt(handle->socket,
+                   IPPROTO_IP,
+                   IP_MULTICAST_IF,
+                   (char*) &addr4->sin_addr,
+                   sizeof(addr4->sin_addr)) == SOCKET_ERROR) {
+      return uv_translate_sys_error(WSAGetLastError());
+    }
+  } else if (addr_st.ss_family == AF_INET6) {
+    if (setsockopt(handle->socket,
+                   IPPROTO_IPV6,
+                   IPV6_MULTICAST_IF,
+                   (char*) &addr6->sin6_scope_id,
+                   sizeof(addr6->sin6_scope_id)) == SOCKET_ERROR) {
+      return uv_translate_sys_error(WSAGetLastError());
+    }
+  } else {
+    assert(0 && "unexpected address family");
+    abort();
+  }
+
+  return 0;
+}
+
+
+int uv_udp_set_broadcast(uv_udp_t* handle, int value) {
+  BOOL optval = (BOOL) value;
+
+  if (!(handle->flags & UV_HANDLE_BOUND))
+    return UV_EBADF;
+
+  if (setsockopt(handle->socket,
+                 SOL_SOCKET,
+                 SO_BROADCAST,
+                 (char*) &optval,
+                 sizeof optval)) {
+    return uv_translate_sys_error(WSAGetLastError());
+  }
+
+  return 0;
+}
+
+
+int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock) {
+  WSAPROTOCOL_INFOW protocol_info;
+  int opt_len;
+  int err;
+
+  /* Detect the address family of the socket. */
+  opt_len = (int) sizeof protocol_info;
+  if (getsockopt(sock,
+                 SOL_SOCKET,
+                 SO_PROTOCOL_INFOW,
+                 (char*) &protocol_info,
+                 &opt_len) == SOCKET_ERROR) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  err = uv_udp_set_socket(handle->loop,
+                          handle,
+                          sock,
+                          protocol_info.iAddressFamily);
+  return uv_translate_sys_error(err);
+}
+
+
+#define SOCKOPT_SETTER(name, option4, option6, validate)                      \
+  int uv_udp_set_##name(uv_udp_t* handle, int value) {                        \
+    DWORD optval = (DWORD) value;                                             \
+                                                                              \
+    if (!(validate(value))) {                                                 \
+      return UV_EINVAL;                                                       \
+    }                                                                         \
+                                                                              \
+    if (!(handle->flags & UV_HANDLE_BOUND))                                   \
+      return UV_EBADF;                                                        \
+                                                                              \
+    if (!(handle->flags & UV_HANDLE_IPV6)) {                                  \
+      /* Set IPv4 socket option */                                            \
+      if (setsockopt(handle->socket,                                          \
+                     IPPROTO_IP,                                              \
+                     option4,                                                 \
+                     (char*) &optval,                                         \
+                     sizeof optval)) {                                        \
+        return uv_translate_sys_error(WSAGetLastError());                     \
+      }                                                                       \
+    } else {                                                                  \
+      /* Set IPv6 socket option */                                            \
+      if (setsockopt(handle->socket,                                          \
+                     IPPROTO_IPV6,                                            \
+                     option6,                                                 \
+                     (char*) &optval,                                         \
+                     sizeof optval)) {                                        \
+        return uv_translate_sys_error(WSAGetLastError());                     \
+      }                                                                       \
+    }                                                                         \
+    return 0;                                                                 \
+  }
+
+#define VALIDATE_TTL(value) ((value) >= 1 && (value) <= 255)
+#define VALIDATE_MULTICAST_TTL(value) ((value) >= -1 && (value) <= 255)
+#define VALIDATE_MULTICAST_LOOP(value) (1)
+
+SOCKOPT_SETTER(ttl,
+               IP_TTL,
+               IPV6_HOPLIMIT,
+               VALIDATE_TTL)
+SOCKOPT_SETTER(multicast_ttl,
+               IP_MULTICAST_TTL,
+               IPV6_MULTICAST_HOPS,
+               VALIDATE_MULTICAST_TTL)
+SOCKOPT_SETTER(multicast_loop,
+               IP_MULTICAST_LOOP,
+               IPV6_MULTICAST_LOOP,
+               VALIDATE_MULTICAST_LOOP)
+
+#undef SOCKOPT_SETTER
+#undef VALIDATE_TTL
+#undef VALIDATE_MULTICAST_TTL
+#undef VALIDATE_MULTICAST_LOOP
+
+
+/* This function is an egress point, i.e. it returns libuv errors rather than
+ * system errors.
+ */
+int uv__udp_bind(uv_udp_t* handle,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 unsigned int flags) {
+  int err;
+
+  err = uv_udp_maybe_bind(handle, addr, addrlen, flags);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  return 0;
+}
+
+
+/* This function is an egress point, i.e. it returns libuv errors rather than
+ * system errors.
+ */
+int uv__udp_send(uv_udp_send_t* req,
+                 uv_udp_t* handle,
+                 const uv_buf_t bufs[],
+                 unsigned int nbufs,
+                 const struct sockaddr* addr,
+                 unsigned int addrlen,
+                 uv_udp_send_cb send_cb) {
+  const struct sockaddr* bind_addr;
+  int err;
+
+  if (!(handle->flags & UV_HANDLE_BOUND)) {
+    if (addrlen == sizeof(uv_addr_ip4_any_)) {
+      bind_addr = (const struct sockaddr*) &uv_addr_ip4_any_;
+    } else if (addrlen == sizeof(uv_addr_ip6_any_)) {
+      bind_addr = (const struct sockaddr*) &uv_addr_ip6_any_;
+    } else {
+      abort();
+    }
+    err = uv_udp_maybe_bind(handle, bind_addr, addrlen, 0);
+    if (err)
+      return uv_translate_sys_error(err);
+  }
+
+  err = uv__send(req, handle, bufs, nbufs, addr, addrlen, send_cb);
+  if (err)
+    return uv_translate_sys_error(err);
+
+  return 0;
+}
+
+
+int uv__udp_try_send(uv_udp_t* handle,
+                     const uv_buf_t bufs[],
+                     unsigned int nbufs,
+                     const struct sockaddr* addr,
+                     unsigned int addrlen) {
+  return UV_ENOSYS;
+}
diff --git a/Utilities/cmlibuv/src/win/util.c b/Utilities/cmlibuv/src/win/util.c
new file mode 100644
index 0000000..050058a
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/util.c
@@ -0,0 +1,1389 @@
+/* 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 <assert.h>
+#include <direct.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <wchar.h>
+
+#include "uv.h"
+#include "internal.h"
+
+#include <winsock2.h>
+#include <winperf.h>
+#include <iphlpapi.h>
+#include <psapi.h>
+#include <tlhelp32.h>
+#include <windows.h>
+#include <userenv.h>
+
+
+/*
+ * Max title length; the only thing MSDN tells us about the maximum length
+ * of the console title is that it is smaller than 64K. However in practice
+ * it is much smaller, and there is no way to figure out what the exact length
+ * of the title is or can be, at least not on XP. To make it even more
+ * annoying, GetConsoleTitle fails when the buffer to be read into is bigger
+ * than the actual maximum length. So we make a conservative guess here;
+ * just don't put the novel you're writing in the title, unless the plot
+ * survives truncation.
+ */
+#define MAX_TITLE_LENGTH 8192
+
+/* The number of nanoseconds in one second. */
+#define UV__NANOSEC 1000000000
+
+/* Max user name length, from iphlpapi.h */
+#ifndef UNLEN
+# define UNLEN 256
+#endif
+
+/* Cached copy of the process title, plus a mutex guarding it. */
+static char *process_title;
+static CRITICAL_SECTION process_title_lock;
+
+/* Cached copy of the process id, written once. */
+static DWORD current_pid = 0;
+
+
+/* Interval (in seconds) of the high-resolution clock. */
+static double hrtime_interval_ = 0;
+
+
+/*
+ * One-time initialization code for functionality defined in util.c.
+ */
+void uv__util_init() {
+  LARGE_INTEGER perf_frequency;
+
+  /* Initialize process title access mutex. */
+  InitializeCriticalSection(&process_title_lock);
+
+  /* Retrieve high-resolution timer frequency
+   * and precompute its reciprocal.
+   */
+  if (QueryPerformanceFrequency(&perf_frequency)) {
+    hrtime_interval_ = 1.0 / perf_frequency.QuadPart;
+  } else {
+    hrtime_interval_= 0;
+  }
+}
+
+
+int uv_exepath(char* buffer, size_t* size_ptr) {
+  int utf8_len, utf16_buffer_len, utf16_len;
+  WCHAR* utf16_buffer;
+  int err;
+
+  if (buffer == NULL || size_ptr == NULL || *size_ptr == 0) {
+    return UV_EINVAL;
+  }
+
+  if (*size_ptr > 32768) {
+    /* Windows paths can never be longer than this. */
+    utf16_buffer_len = 32768;
+  } else {
+    utf16_buffer_len = (int) *size_ptr;
+  }
+
+  utf16_buffer = (WCHAR*) uv__malloc(sizeof(WCHAR) * utf16_buffer_len);
+  if (!utf16_buffer) {
+    return UV_ENOMEM;
+  }
+
+  /* Get the path as UTF-16. */
+  utf16_len = GetModuleFileNameW(NULL, utf16_buffer, utf16_buffer_len);
+  if (utf16_len <= 0) {
+    err = GetLastError();
+    goto error;
+  }
+
+  /* utf16_len contains the length, *not* including the terminating null. */
+  utf16_buffer[utf16_len] = L'\0';
+
+  /* Convert to UTF-8 */
+  utf8_len = WideCharToMultiByte(CP_UTF8,
+                                 0,
+                                 utf16_buffer,
+                                 -1,
+                                 buffer,
+                                 (int) *size_ptr,
+                                 NULL,
+                                 NULL);
+  if (utf8_len == 0) {
+    err = GetLastError();
+    goto error;
+  }
+
+  uv__free(utf16_buffer);
+
+  /* utf8_len *does* include the terminating null at this point, but the */
+  /* returned size shouldn't. */
+  *size_ptr = utf8_len - 1;
+  return 0;
+
+ error:
+  uv__free(utf16_buffer);
+  return uv_translate_sys_error(err);
+}
+
+
+int uv_cwd(char* buffer, size_t* size) {
+  DWORD utf16_len;
+  WCHAR utf16_buffer[MAX_PATH];
+  int r;
+
+  if (buffer == NULL || size == NULL) {
+    return UV_EINVAL;
+  }
+
+  utf16_len = GetCurrentDirectoryW(MAX_PATH, utf16_buffer);
+  if (utf16_len == 0) {
+    return uv_translate_sys_error(GetLastError());
+  } else if (utf16_len > MAX_PATH) {
+    /* This should be impossible;  however the CRT has a code path to deal */
+    /* with this scenario, so I added a check anyway. */
+    return UV_EIO;
+  }
+
+  /* utf16_len contains the length, *not* including the terminating null. */
+  utf16_buffer[utf16_len] = L'\0';
+
+  /* The returned directory should not have a trailing slash, unless it */
+  /* points at a drive root, like c:\. Remove it if needed.*/
+  if (utf16_buffer[utf16_len - 1] == L'\\' &&
+      !(utf16_len == 3 && utf16_buffer[1] == L':')) {
+    utf16_len--;
+    utf16_buffer[utf16_len] = L'\0';
+  }
+
+  /* Check how much space we need */
+  r = WideCharToMultiByte(CP_UTF8,
+                          0,
+                          utf16_buffer,
+                          -1,
+                          NULL,
+                          0,
+                          NULL,
+                          NULL);
+  if (r == 0) {
+    return uv_translate_sys_error(GetLastError());
+  } else if (r > (int) *size) {
+    *size = r;
+    return UV_ENOBUFS;
+  }
+
+  /* Convert to UTF-8 */
+  r = WideCharToMultiByte(CP_UTF8,
+                          0,
+                          utf16_buffer,
+                          -1,
+                          buffer,
+                          *size > INT_MAX ? INT_MAX : (int) *size,
+                          NULL,
+                          NULL);
+  if (r == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  *size = r - 1;
+  return 0;
+}
+
+
+int uv_chdir(const char* dir) {
+  WCHAR utf16_buffer[MAX_PATH];
+  size_t utf16_len;
+  WCHAR drive_letter, env_var[4];
+
+  if (dir == NULL) {
+    return UV_EINVAL;
+  }
+
+  if (MultiByteToWideChar(CP_UTF8,
+                          0,
+                          dir,
+                          -1,
+                          utf16_buffer,
+                          MAX_PATH) == 0) {
+    DWORD error = GetLastError();
+    /* The maximum length of the current working directory is 260 chars, */
+    /* including terminating null. If it doesn't fit, the path name must be */
+    /* too long. */
+    if (error == ERROR_INSUFFICIENT_BUFFER) {
+      return UV_ENAMETOOLONG;
+    } else {
+      return uv_translate_sys_error(error);
+    }
+  }
+
+  if (!SetCurrentDirectoryW(utf16_buffer)) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  /* Windows stores the drive-local path in an "hidden" environment variable, */
+  /* which has the form "=C:=C:\Windows". SetCurrentDirectory does not */
+  /* update this, so we'll have to do it. */
+  utf16_len = GetCurrentDirectoryW(MAX_PATH, utf16_buffer);
+  if (utf16_len == 0) {
+    return uv_translate_sys_error(GetLastError());
+  } else if (utf16_len > MAX_PATH) {
+    return UV_EIO;
+  }
+
+  /* The returned directory should not have a trailing slash, unless it */
+  /* points at a drive root, like c:\. Remove it if needed. */
+  if (utf16_buffer[utf16_len - 1] == L'\\' &&
+      !(utf16_len == 3 && utf16_buffer[1] == L':')) {
+    utf16_len--;
+    utf16_buffer[utf16_len] = L'\0';
+  }
+
+  if (utf16_len < 2 || utf16_buffer[1] != L':') {
+    /* Doesn't look like a drive letter could be there - probably an UNC */
+    /* path. TODO: Need to handle win32 namespaces like \\?\C:\ ? */
+    drive_letter = 0;
+  } else if (utf16_buffer[0] >= L'A' && utf16_buffer[0] <= L'Z') {
+    drive_letter = utf16_buffer[0];
+  } else if (utf16_buffer[0] >= L'a' && utf16_buffer[0] <= L'z') {
+    /* Convert to uppercase. */
+    drive_letter = utf16_buffer[0] - L'a' + L'A';
+  } else {
+    /* Not valid. */
+    drive_letter = 0;
+  }
+
+  if (drive_letter != 0) {
+    /* Construct the environment variable name and set it. */
+    env_var[0] = L'=';
+    env_var[1] = drive_letter;
+    env_var[2] = L':';
+    env_var[3] = L'\0';
+
+    if (!SetEnvironmentVariableW(env_var, utf16_buffer)) {
+      return uv_translate_sys_error(GetLastError());
+    }
+  }
+
+  return 0;
+}
+
+
+void uv_loadavg(double avg[3]) {
+  /* Can't be implemented */
+  avg[0] = avg[1] = avg[2] = 0;
+}
+
+
+uint64_t uv_get_free_memory(void) {
+  MEMORYSTATUSEX memory_status;
+  memory_status.dwLength = sizeof(memory_status);
+
+  if (!GlobalMemoryStatusEx(&memory_status)) {
+     return -1;
+  }
+
+  return (uint64_t)memory_status.ullAvailPhys;
+}
+
+
+uint64_t uv_get_total_memory(void) {
+  MEMORYSTATUSEX memory_status;
+  memory_status.dwLength = sizeof(memory_status);
+
+  if (!GlobalMemoryStatusEx(&memory_status)) {
+    return -1;
+  }
+
+  return (uint64_t)memory_status.ullTotalPhys;
+}
+
+
+int uv_parent_pid() {
+  int parent_pid = -1;
+  HANDLE handle;
+  PROCESSENTRY32 pe;
+  DWORD current_pid = GetCurrentProcessId();
+
+  pe.dwSize = sizeof(PROCESSENTRY32);
+  handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+
+  if (Process32First(handle, &pe)) {
+    do {
+      if (pe.th32ProcessID == current_pid) {
+        parent_pid = pe.th32ParentProcessID;
+        break;
+      }
+    } while( Process32Next(handle, &pe));
+  }
+
+  CloseHandle(handle);
+  return parent_pid;
+}
+
+
+int uv_current_pid() {
+  if (current_pid == 0) {
+    current_pid = GetCurrentProcessId();
+  }
+  return current_pid;
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+  return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+  int err;
+  int length;
+  WCHAR* title_w = NULL;
+
+  uv__once_init();
+
+  /* Find out how big the buffer for the wide-char title must be */
+  length = MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0);
+  if (!length) {
+    err = GetLastError();
+    goto done;
+  }
+
+  /* Convert to wide-char string */
+  title_w = (WCHAR*)uv__malloc(sizeof(WCHAR) * length);
+  if (!title_w) {
+    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
+  }
+
+  length = MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w, length);
+  if (!length) {
+    err = GetLastError();
+    goto done;
+  }
+
+  /* If the title must be truncated insert a \0 terminator there */
+  if (length > MAX_TITLE_LENGTH) {
+    title_w[MAX_TITLE_LENGTH - 1] = L'\0';
+  }
+
+  if (!SetConsoleTitleW(title_w)) {
+    err = GetLastError();
+    goto done;
+  }
+
+  EnterCriticalSection(&process_title_lock);
+  uv__free(process_title);
+  process_title = uv__strdup(title);
+  LeaveCriticalSection(&process_title_lock);
+
+  err = 0;
+
+done:
+  uv__free(title_w);
+  return uv_translate_sys_error(err);
+}
+
+
+static int uv__get_process_title() {
+  WCHAR title_w[MAX_TITLE_LENGTH];
+
+  if (!GetConsoleTitleW(title_w, sizeof(title_w) / sizeof(WCHAR))) {
+    return -1;
+  }
+
+  if (uv__convert_utf16_to_utf8(title_w, -1, &process_title) != 0)
+    return -1;
+
+  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_init();
+
+  EnterCriticalSection(&process_title_lock);
+  /*
+   * If the process_title was never read before nor explicitly set,
+   * we must query it with getConsoleTitleW
+   */
+  if (!process_title && uv__get_process_title() == -1) {
+    LeaveCriticalSection(&process_title_lock);
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  assert(process_title);
+  len = strlen(process_title) + 1;
+
+  if (size < len) {
+    LeaveCriticalSection(&process_title_lock);
+    return UV_ENOBUFS;
+  }
+
+  memcpy(buffer, process_title, len);
+  LeaveCriticalSection(&process_title_lock);
+
+  return 0;
+}
+
+
+uint64_t uv_hrtime(void) {
+  uv__once_init();
+  return uv__hrtime(UV__NANOSEC);
+}
+
+uint64_t uv__hrtime(double scale) {
+  LARGE_INTEGER counter;
+
+  /* If the performance interval is zero, there's no support. */
+  if (hrtime_interval_ == 0) {
+    return 0;
+  }
+
+  if (!QueryPerformanceCounter(&counter)) {
+    return 0;
+  }
+
+  /* Because we have no guarantee about the order of magnitude of the
+   * performance counter interval, integer math could cause this computation
+   * to overflow. Therefore we resort to floating point math.
+   */
+  return (uint64_t) ((double) counter.QuadPart * hrtime_interval_ * scale);
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+  HANDLE current_process;
+  PROCESS_MEMORY_COUNTERS pmc;
+
+  current_process = GetCurrentProcess();
+
+  if (!GetProcessMemoryInfo(current_process, &pmc, sizeof(pmc))) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  *rss = pmc.WorkingSetSize;
+
+  return 0;
+}
+
+
+int uv_uptime(double* uptime) {
+  BYTE stack_buffer[4096];
+  BYTE* malloced_buffer = NULL;
+  BYTE* buffer = (BYTE*) stack_buffer;
+  size_t buffer_size = sizeof(stack_buffer);
+  DWORD data_size;
+
+  PERF_DATA_BLOCK* data_block;
+  PERF_OBJECT_TYPE* object_type;
+  PERF_COUNTER_DEFINITION* counter_definition;
+
+  DWORD i;
+
+  for (;;) {
+    LONG result;
+
+    data_size = (DWORD) buffer_size;
+    result = RegQueryValueExW(HKEY_PERFORMANCE_DATA,
+                              L"2",
+                              NULL,
+                              NULL,
+                              buffer,
+                              &data_size);
+    if (result == ERROR_SUCCESS) {
+      break;
+    } else if (result != ERROR_MORE_DATA) {
+      *uptime = 0;
+      return uv_translate_sys_error(result);
+    }
+
+    buffer_size *= 2;
+    /* Don't let the buffer grow infinitely. */
+    if (buffer_size > 1 << 20) {
+      goto internalError;
+    }
+
+    uv__free(malloced_buffer);
+
+    buffer = malloced_buffer = (BYTE*) uv__malloc(buffer_size);
+    if (malloced_buffer == NULL) {
+      *uptime = 0;
+      return UV_ENOMEM;
+    }
+  }
+
+  if (data_size < sizeof(*data_block))
+    goto internalError;
+
+  data_block = (PERF_DATA_BLOCK*) buffer;
+
+  if (wmemcmp(data_block->Signature, L"PERF", 4) != 0)
+    goto internalError;
+
+  if (data_size < data_block->HeaderLength + sizeof(*object_type))
+    goto internalError;
+
+  object_type = (PERF_OBJECT_TYPE*) (buffer + data_block->HeaderLength);
+
+  if (object_type->NumInstances != PERF_NO_INSTANCES)
+    goto internalError;
+
+  counter_definition = (PERF_COUNTER_DEFINITION*) (buffer +
+      data_block->HeaderLength + object_type->HeaderLength);
+  for (i = 0; i < object_type->NumCounters; i++) {
+    if ((BYTE*) counter_definition + sizeof(*counter_definition) >
+        buffer + data_size) {
+      break;
+    }
+
+    if (counter_definition->CounterNameTitleIndex == 674 &&
+        counter_definition->CounterSize == sizeof(uint64_t)) {
+      if (counter_definition->CounterOffset + sizeof(uint64_t) > data_size ||
+          !(counter_definition->CounterType & PERF_OBJECT_TIMER)) {
+        goto internalError;
+      } else {
+        BYTE* address = (BYTE*) object_type + object_type->DefinitionLength +
+                        counter_definition->CounterOffset;
+        uint64_t value = *((uint64_t*) address);
+        *uptime = (double) (object_type->PerfTime.QuadPart - value) /
+                  (double) object_type->PerfFreq.QuadPart;
+        uv__free(malloced_buffer);
+        return 0;
+      }
+    }
+
+    counter_definition = (PERF_COUNTER_DEFINITION*)
+        ((BYTE*) counter_definition + counter_definition->ByteLength);
+  }
+
+  /* If we get here, the uptime value was not found. */
+  uv__free(malloced_buffer);
+  *uptime = 0;
+  return UV_ENOSYS;
+
+ internalError:
+  uv__free(malloced_buffer);
+  *uptime = 0;
+  return UV_EIO;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos_ptr, int* cpu_count_ptr) {
+  uv_cpu_info_t* cpu_infos;
+  SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi;
+  DWORD sppi_size;
+  SYSTEM_INFO system_info;
+  DWORD cpu_count, r, i;
+  NTSTATUS status;
+  ULONG result_size;
+  int err;
+  uv_cpu_info_t* cpu_info;
+
+  cpu_infos = NULL;
+  cpu_count = 0;
+  sppi = NULL;
+
+  uv__once_init();
+
+  GetSystemInfo(&system_info);
+  cpu_count = system_info.dwNumberOfProcessors;
+
+  cpu_infos = uv__calloc(cpu_count, sizeof *cpu_infos);
+  if (cpu_infos == NULL) {
+    err = ERROR_OUTOFMEMORY;
+    goto error;
+  }
+
+  sppi_size = cpu_count * sizeof(*sppi);
+  sppi = uv__malloc(sppi_size);
+  if (sppi == NULL) {
+    err = ERROR_OUTOFMEMORY;
+    goto error;
+  }
+
+  status = pNtQuerySystemInformation(SystemProcessorPerformanceInformation,
+                                     sppi,
+                                     sppi_size,
+                                     &result_size);
+  if (!NT_SUCCESS(status)) {
+    err = pRtlNtStatusToDosError(status);
+    goto error;
+  }
+
+  assert(result_size == sppi_size);
+
+  for (i = 0; i < cpu_count; i++) {
+    WCHAR key_name[128];
+    HKEY processor_key;
+    DWORD cpu_speed;
+    DWORD cpu_speed_size = sizeof(cpu_speed);
+    WCHAR cpu_brand[256];
+    DWORD cpu_brand_size = sizeof(cpu_brand);
+    size_t len;
+
+    len = _snwprintf(key_name,
+                     ARRAY_SIZE(key_name),
+                     L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d",
+                     i);
+
+    assert(len > 0 && len < ARRAY_SIZE(key_name));
+
+    r = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+                      key_name,
+                      0,
+                      KEY_QUERY_VALUE,
+                      &processor_key);
+    if (r != ERROR_SUCCESS) {
+      err = GetLastError();
+      goto error;
+    }
+
+    if (RegQueryValueExW(processor_key,
+                         L"~MHz",
+                         NULL,
+                         NULL,
+                         (BYTE*) &cpu_speed,
+                         &cpu_speed_size) != ERROR_SUCCESS) {
+      err = GetLastError();
+      RegCloseKey(processor_key);
+      goto error;
+    }
+
+    if (RegQueryValueExW(processor_key,
+                         L"ProcessorNameString",
+                         NULL,
+                         NULL,
+                         (BYTE*) &cpu_brand,
+                         &cpu_brand_size) != ERROR_SUCCESS) {
+      err = GetLastError();
+      RegCloseKey(processor_key);
+      goto error;
+    }
+
+    RegCloseKey(processor_key);
+
+    cpu_info = &cpu_infos[i];
+    cpu_info->speed = cpu_speed;
+    cpu_info->cpu_times.user = sppi[i].UserTime.QuadPart / 10000;
+    cpu_info->cpu_times.sys = (sppi[i].KernelTime.QuadPart -
+        sppi[i].IdleTime.QuadPart) / 10000;
+    cpu_info->cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000;
+    cpu_info->cpu_times.irq = sppi[i].InterruptTime.QuadPart / 10000;
+    cpu_info->cpu_times.nice = 0;
+
+    uv__convert_utf16_to_utf8(cpu_brand,
+                              cpu_brand_size / sizeof(WCHAR),
+                              &(cpu_info->model));
+  }
+
+  uv__free(sppi);
+
+  *cpu_count_ptr = cpu_count;
+  *cpu_infos_ptr = cpu_infos;
+
+  return 0;
+
+ error:
+  /* This is safe because the cpu_infos array is zeroed on allocation. */
+  for (i = 0; i < cpu_count; i++)
+    uv__free(cpu_infos[i].model);
+
+  uv__free(cpu_infos);
+  uv__free(sppi);
+
+  return uv_translate_sys_error(err);
+}
+
+
+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);
+}
+
+
+static int is_windows_version_or_greater(DWORD os_major,
+                                         DWORD os_minor,
+                                         WORD service_pack_major,
+                                         WORD service_pack_minor) {
+  OSVERSIONINFOEX osvi;
+  DWORDLONG condition_mask = 0;
+  int op = VER_GREATER_EQUAL;
+
+  /* Initialize the OSVERSIONINFOEX structure. */
+  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
+  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+  osvi.dwMajorVersion = os_major;
+  osvi.dwMinorVersion = os_minor;
+  osvi.wServicePackMajor = service_pack_major;
+  osvi.wServicePackMinor = service_pack_minor;
+
+  /* Initialize the condition mask. */
+  VER_SET_CONDITION(condition_mask, VER_MAJORVERSION, op);
+  VER_SET_CONDITION(condition_mask, VER_MINORVERSION, op);
+  VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMAJOR, op);
+  VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMINOR, op);
+
+  /* Perform the test. */
+  return (int) VerifyVersionInfo(
+    &osvi,
+    VER_MAJORVERSION | VER_MINORVERSION |
+    VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
+    condition_mask);
+}
+
+
+static int address_prefix_match(int family,
+                                struct sockaddr* address,
+                                struct sockaddr* prefix_address,
+                                int prefix_len) {
+  uint8_t* address_data;
+  uint8_t* prefix_address_data;
+  int i;
+
+  assert(address->sa_family == family);
+  assert(prefix_address->sa_family == family);
+
+  if (family == AF_INET6) {
+    address_data = (uint8_t*) &(((struct sockaddr_in6 *) address)->sin6_addr);
+    prefix_address_data =
+      (uint8_t*) &(((struct sockaddr_in6 *) prefix_address)->sin6_addr);
+  } else {
+    address_data = (uint8_t*) &(((struct sockaddr_in *) address)->sin_addr);
+    prefix_address_data =
+      (uint8_t*) &(((struct sockaddr_in *) prefix_address)->sin_addr);
+  }
+
+  for (i = 0; i < prefix_len >> 3; i++) {
+    if (address_data[i] != prefix_address_data[i])
+      return 0;
+  }
+
+  if (prefix_len % 8)
+    return prefix_address_data[i] ==
+      (address_data[i] & (0xff << (8 - prefix_len % 8)));
+
+  return 1;
+}
+
+
+int uv_interface_addresses(uv_interface_address_t** addresses_ptr,
+    int* count_ptr) {
+  IP_ADAPTER_ADDRESSES* win_address_buf;
+  ULONG win_address_buf_size;
+  IP_ADAPTER_ADDRESSES* adapter;
+
+  uv_interface_address_t* uv_address_buf;
+  char* name_buf;
+  size_t uv_address_buf_size;
+  uv_interface_address_t* uv_address;
+
+  int count;
+
+  int is_vista_or_greater;
+  ULONG flags;
+
+  is_vista_or_greater = is_windows_version_or_greater(6, 0, 0, 0);
+  if (is_vista_or_greater) {
+    flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
+      GAA_FLAG_SKIP_DNS_SERVER;
+  } else {
+    /* We need at least XP SP1. */
+    if (!is_windows_version_or_greater(5, 1, 1, 0))
+      return UV_ENOTSUP;
+
+    flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
+      GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_INCLUDE_PREFIX;
+  }
+
+
+  /* Fetch the size of the adapters reported by windows, and then get the */
+  /* list itself. */
+  win_address_buf_size = 0;
+  win_address_buf = NULL;
+
+  for (;;) {
+    ULONG r;
+
+    /* If win_address_buf is 0, then GetAdaptersAddresses will fail with */
+    /* ERROR_BUFFER_OVERFLOW, and the required buffer size will be stored in */
+    /* win_address_buf_size. */
+    r = GetAdaptersAddresses(AF_UNSPEC,
+                             flags,
+                             NULL,
+                             win_address_buf,
+                             &win_address_buf_size);
+
+    if (r == ERROR_SUCCESS)
+      break;
+
+    uv__free(win_address_buf);
+
+    switch (r) {
+      case ERROR_BUFFER_OVERFLOW:
+        /* This happens when win_address_buf is NULL or too small to hold */
+        /* all adapters. */
+        win_address_buf = uv__malloc(win_address_buf_size);
+        if (win_address_buf == NULL)
+          return UV_ENOMEM;
+
+        continue;
+
+      case ERROR_NO_DATA: {
+        /* No adapters were found. */
+        uv_address_buf = uv__malloc(1);
+        if (uv_address_buf == NULL)
+          return UV_ENOMEM;
+
+        *count_ptr = 0;
+        *addresses_ptr = uv_address_buf;
+
+        return 0;
+      }
+
+      case ERROR_ADDRESS_NOT_ASSOCIATED:
+        return UV_EAGAIN;
+
+      case ERROR_INVALID_PARAMETER:
+        /* MSDN says:
+         *   "This error is returned for any of the following conditions: the
+         *   SizePointer parameter is NULL, the Address parameter is not
+         *   AF_INET, AF_INET6, or AF_UNSPEC, or the address information for
+         *   the parameters requested is greater than ULONG_MAX."
+         * Since the first two conditions are not met, it must be that the
+         * adapter data is too big.
+         */
+        return UV_ENOBUFS;
+
+      default:
+        /* Other (unspecified) errors can happen, but we don't have any */
+        /* special meaning for them. */
+        assert(r != ERROR_SUCCESS);
+        return uv_translate_sys_error(r);
+    }
+  }
+
+  /* Count the number of enabled interfaces and compute how much space is */
+  /* needed to store their info. */
+  count = 0;
+  uv_address_buf_size = 0;
+
+  for (adapter = win_address_buf;
+       adapter != NULL;
+       adapter = adapter->Next) {
+    IP_ADAPTER_UNICAST_ADDRESS* unicast_address;
+    int name_size;
+
+    /* Interfaces that are not 'up' should not be reported. Also skip */
+    /* interfaces that have no associated unicast address, as to avoid */
+    /* allocating space for the name for this interface. */
+    if (adapter->OperStatus != IfOperStatusUp ||
+        adapter->FirstUnicastAddress == NULL)
+      continue;
+
+    /* Compute the size of the interface name. */
+    name_size = WideCharToMultiByte(CP_UTF8,
+                                    0,
+                                    adapter->FriendlyName,
+                                    -1,
+                                    NULL,
+                                    0,
+                                    NULL,
+                                    FALSE);
+    if (name_size <= 0) {
+      uv__free(win_address_buf);
+      return uv_translate_sys_error(GetLastError());
+    }
+    uv_address_buf_size += name_size;
+
+    /* Count the number of addresses associated with this interface, and */
+    /* compute the size. */
+    for (unicast_address = (IP_ADAPTER_UNICAST_ADDRESS*)
+                           adapter->FirstUnicastAddress;
+         unicast_address != NULL;
+         unicast_address = unicast_address->Next) {
+      count++;
+      uv_address_buf_size += sizeof(uv_interface_address_t);
+    }
+  }
+
+  /* Allocate space to store interface data plus adapter names. */
+  uv_address_buf = uv__malloc(uv_address_buf_size);
+  if (uv_address_buf == NULL) {
+    uv__free(win_address_buf);
+    return UV_ENOMEM;
+  }
+
+  /* Compute the start of the uv_interface_address_t array, and the place in */
+  /* the buffer where the interface names will be stored. */
+  uv_address = uv_address_buf;
+  name_buf = (char*) (uv_address_buf + count);
+
+  /* Fill out the output buffer. */
+  for (adapter = win_address_buf;
+       adapter != NULL;
+       adapter = adapter->Next) {
+    IP_ADAPTER_UNICAST_ADDRESS* unicast_address;
+    int name_size;
+    size_t max_name_size;
+
+    if (adapter->OperStatus != IfOperStatusUp ||
+        adapter->FirstUnicastAddress == NULL)
+      continue;
+
+    /* Convert the interface name to UTF8. */
+    max_name_size = (char*) uv_address_buf + uv_address_buf_size - name_buf;
+    if (max_name_size > (size_t) INT_MAX)
+      max_name_size = INT_MAX;
+    name_size = WideCharToMultiByte(CP_UTF8,
+                                    0,
+                                    adapter->FriendlyName,
+                                    -1,
+                                    name_buf,
+                                    (int) max_name_size,
+                                    NULL,
+                                    FALSE);
+    if (name_size <= 0) {
+      uv__free(win_address_buf);
+      uv__free(uv_address_buf);
+      return uv_translate_sys_error(GetLastError());
+    }
+
+    /* Add an uv_interface_address_t element for every unicast address. */
+    for (unicast_address = (IP_ADAPTER_UNICAST_ADDRESS*)
+                           adapter->FirstUnicastAddress;
+         unicast_address != NULL;
+         unicast_address = unicast_address->Next) {
+      struct sockaddr* sa;
+      ULONG prefix_len;
+
+      sa = unicast_address->Address.lpSockaddr;
+
+      /* XP has no OnLinkPrefixLength field. */
+      if (is_vista_or_greater) {
+        prefix_len =
+          ((IP_ADAPTER_UNICAST_ADDRESS_LH*) unicast_address)->OnLinkPrefixLength;
+      } else {
+        /* Prior to Windows Vista the FirstPrefix pointed to the list with
+         * single prefix for each IP address assigned to the adapter.
+         * Order of FirstPrefix does not match order of FirstUnicastAddress,
+         * so we need to find corresponding prefix.
+         */
+        IP_ADAPTER_PREFIX* prefix;
+        prefix_len = 0;
+
+        for (prefix = adapter->FirstPrefix; prefix; prefix = prefix->Next) {
+          /* We want the longest matching prefix. */
+          if (prefix->Address.lpSockaddr->sa_family != sa->sa_family ||
+              prefix->PrefixLength <= prefix_len)
+            continue;
+
+          if (address_prefix_match(sa->sa_family, sa,
+              prefix->Address.lpSockaddr, prefix->PrefixLength)) {
+            prefix_len = prefix->PrefixLength;
+          }
+        }
+
+        /* If there is no matching prefix information, return a single-host
+         * subnet mask (e.g. 255.255.255.255 for IPv4).
+         */
+        if (!prefix_len)
+          prefix_len = (sa->sa_family == AF_INET6) ? 128 : 32;
+      }
+
+      memset(uv_address, 0, sizeof *uv_address);
+
+      uv_address->name = name_buf;
+
+      if (adapter->PhysicalAddressLength == sizeof(uv_address->phys_addr)) {
+        memcpy(uv_address->phys_addr,
+               adapter->PhysicalAddress,
+               sizeof(uv_address->phys_addr));
+      }
+
+      uv_address->is_internal =
+          (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK);
+
+      if (sa->sa_family == AF_INET6) {
+        uv_address->address.address6 = *((struct sockaddr_in6 *) sa);
+
+        uv_address->netmask.netmask6.sin6_family = AF_INET6;
+        memset(uv_address->netmask.netmask6.sin6_addr.s6_addr, 0xff, prefix_len >> 3);
+        /* This check ensures that we don't write past the size of the data. */
+        if (prefix_len % 8) {
+          uv_address->netmask.netmask6.sin6_addr.s6_addr[prefix_len >> 3] =
+              0xff << (8 - prefix_len % 8);
+        }
+
+      } else {
+        uv_address->address.address4 = *((struct sockaddr_in *) sa);
+
+        uv_address->netmask.netmask4.sin_family = AF_INET;
+        uv_address->netmask.netmask4.sin_addr.s_addr = (prefix_len > 0) ?
+            htonl(0xffffffff << (32 - prefix_len)) : 0;
+      }
+
+      uv_address++;
+    }
+
+    name_buf += name_size;
+  }
+
+  uv__free(win_address_buf);
+
+  *addresses_ptr = uv_address_buf;
+  *count_ptr = count;
+
+  return 0;
+}
+
+
+void uv_free_interface_addresses(uv_interface_address_t* addresses,
+    int count) {
+  uv__free(addresses);
+}
+
+
+int uv_getrusage(uv_rusage_t *uv_rusage) {
+  FILETIME createTime, exitTime, kernelTime, userTime;
+  SYSTEMTIME kernelSystemTime, userSystemTime;
+  PROCESS_MEMORY_COUNTERS memCounters;
+  IO_COUNTERS ioCounters;
+  int ret;
+
+  ret = GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime);
+  if (ret == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  ret = FileTimeToSystemTime(&kernelTime, &kernelSystemTime);
+  if (ret == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  ret = FileTimeToSystemTime(&userTime, &userSystemTime);
+  if (ret == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  ret = GetProcessMemoryInfo(GetCurrentProcess(),
+                             &memCounters,
+                             sizeof(memCounters));
+  if (ret == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  ret = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
+  if (ret == 0) {
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  memset(uv_rusage, 0, sizeof(*uv_rusage));
+
+  uv_rusage->ru_utime.tv_sec = userSystemTime.wHour * 3600 +
+                               userSystemTime.wMinute * 60 +
+                               userSystemTime.wSecond;
+  uv_rusage->ru_utime.tv_usec = userSystemTime.wMilliseconds * 1000;
+
+  uv_rusage->ru_stime.tv_sec = kernelSystemTime.wHour * 3600 +
+                               kernelSystemTime.wMinute * 60 +
+                               kernelSystemTime.wSecond;
+  uv_rusage->ru_stime.tv_usec = kernelSystemTime.wMilliseconds * 1000;
+
+  uv_rusage->ru_majflt = (uint64_t) memCounters.PageFaultCount;
+  uv_rusage->ru_maxrss = (uint64_t) memCounters.PeakWorkingSetSize / 1024;
+
+  uv_rusage->ru_oublock = (uint64_t) ioCounters.WriteOperationCount;
+  uv_rusage->ru_inblock = (uint64_t) ioCounters.ReadOperationCount;
+
+  return 0;
+}
+
+
+int uv_os_homedir(char* buffer, size_t* size) {
+  uv_passwd_t pwd;
+  wchar_t path[MAX_PATH];
+  DWORD bufsize;
+  size_t len;
+  int r;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return UV_EINVAL;
+
+  /* Check if the USERPROFILE environment variable is set first */
+  len = GetEnvironmentVariableW(L"USERPROFILE", path, MAX_PATH);
+
+  if (len == 0) {
+    r = GetLastError();
+
+    /* Don't return an error if USERPROFILE was not found */
+    if (r != ERROR_ENVVAR_NOT_FOUND)
+      return uv_translate_sys_error(r);
+  } else if (len > MAX_PATH) {
+    /* This should not be possible */
+    return UV_EIO;
+  } else {
+    /* Check how much space we need */
+    bufsize = WideCharToMultiByte(CP_UTF8, 0, path, -1, NULL, 0, NULL, NULL);
+
+    if (bufsize == 0) {
+      return uv_translate_sys_error(GetLastError());
+    } else if (bufsize > *size) {
+      *size = bufsize;
+      return UV_ENOBUFS;
+    }
+
+    /* Convert to UTF-8 */
+    bufsize = WideCharToMultiByte(CP_UTF8,
+                                  0,
+                                  path,
+                                  -1,
+                                  buffer,
+                                  *size,
+                                  NULL,
+                                  NULL);
+
+    if (bufsize == 0)
+      return uv_translate_sys_error(GetLastError());
+
+    *size = bufsize - 1;
+    return 0;
+  }
+
+  /* USERPROFILE is not set, so call uv__getpwuid_r() */
+  r = uv__getpwuid_r(&pwd);
+
+  if (r != 0) {
+    return r;
+  }
+
+  len = strlen(pwd.homedir);
+
+  if (len >= *size) {
+    *size = len + 1;
+    uv_os_free_passwd(&pwd);
+    return UV_ENOBUFS;
+  }
+
+  memcpy(buffer, pwd.homedir, len + 1);
+  *size = len;
+  uv_os_free_passwd(&pwd);
+
+  return 0;
+}
+
+
+int uv_os_tmpdir(char* buffer, size_t* size) {
+  wchar_t path[MAX_PATH + 1];
+  DWORD bufsize;
+  size_t len;
+
+  if (buffer == NULL || size == NULL || *size == 0)
+    return UV_EINVAL;
+
+  len = GetTempPathW(MAX_PATH + 1, path);
+
+  if (len == 0) {
+    return uv_translate_sys_error(GetLastError());
+  } else if (len > MAX_PATH + 1) {
+    /* This should not be possible */
+    return UV_EIO;
+  }
+
+  /* The returned directory should not have a trailing slash, unless it */
+  /* points at a drive root, like c:\. Remove it if needed.*/
+  if (path[len - 1] == L'\\' &&
+      !(len == 3 && path[1] == L':')) {
+    len--;
+    path[len] = L'\0';
+  }
+
+  /* Check how much space we need */
+  bufsize = WideCharToMultiByte(CP_UTF8, 0, path, -1, NULL, 0, NULL, NULL);
+
+  if (bufsize == 0) {
+    return uv_translate_sys_error(GetLastError());
+  } else if (bufsize > *size) {
+    *size = bufsize;
+    return UV_ENOBUFS;
+  }
+
+  /* Convert to UTF-8 */
+  bufsize = WideCharToMultiByte(CP_UTF8,
+                                0,
+                                path,
+                                -1,
+                                buffer,
+                                *size,
+                                NULL,
+                                NULL);
+
+  if (bufsize == 0)
+    return uv_translate_sys_error(GetLastError());
+
+  *size = bufsize - 1;
+  return 0;
+}
+
+
+void uv_os_free_passwd(uv_passwd_t* pwd) {
+  if (pwd == NULL)
+    return;
+
+  uv__free(pwd->username);
+  uv__free(pwd->homedir);
+  pwd->username = NULL;
+  pwd->homedir = NULL;
+}
+
+
+/*
+ * Converts a UTF-16 string into a UTF-8 one. The resulting string is
+ * null-terminated.
+ *
+ * If utf16 is null terminated, utf16len can be set to -1, otherwise it must
+ * be specified.
+ */
+int uv__convert_utf16_to_utf8(const WCHAR* utf16, int utf16len, char** utf8) {
+  DWORD bufsize;
+
+  if (utf16 == NULL)
+    return UV_EINVAL;
+
+  /* Check how much space we need */
+  bufsize = WideCharToMultiByte(CP_UTF8,
+                                0,
+                                utf16,
+                                utf16len,
+                                NULL,
+                                0,
+                                NULL,
+                                NULL);
+
+  if (bufsize == 0)
+    return uv_translate_sys_error(GetLastError());
+
+  /* Allocate the destination buffer adding an extra byte for the terminating
+   * NULL. If utf16len is not -1 WideCharToMultiByte will not add it, so
+   * we do it ourselves always, just in case. */
+  *utf8 = uv__malloc(bufsize + 1);
+
+  if (*utf8 == NULL)
+    return UV_ENOMEM;
+
+  /* Convert to UTF-8 */
+  bufsize = WideCharToMultiByte(CP_UTF8,
+                                0,
+                                utf16,
+                                utf16len,
+                                *utf8,
+                                bufsize,
+                                NULL,
+                                NULL);
+
+  if (bufsize == 0) {
+    uv__free(*utf8);
+    *utf8 = NULL;
+    return uv_translate_sys_error(GetLastError());
+  }
+
+  (*utf8)[bufsize] = '\0';
+  return 0;
+}
+
+
+int uv__getpwuid_r(uv_passwd_t* pwd) {
+  HANDLE token;
+  wchar_t username[UNLEN + 1];
+  wchar_t path[MAX_PATH];
+  DWORD bufsize;
+  int r;
+
+  if (pwd == NULL)
+    return UV_EINVAL;
+
+  /* Get the home directory using GetUserProfileDirectoryW() */
+  if (OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token) == 0)
+    return uv_translate_sys_error(GetLastError());
+
+  bufsize = sizeof(path);
+  if (!GetUserProfileDirectoryW(token, path, &bufsize)) {
+    r = GetLastError();
+    CloseHandle(token);
+
+    /* This should not be possible */
+    if (r == ERROR_INSUFFICIENT_BUFFER)
+      return UV_ENOMEM;
+
+    return uv_translate_sys_error(r);
+  }
+
+  CloseHandle(token);
+
+  /* Get the username using GetUserNameW() */
+  bufsize = sizeof(username);
+  if (!GetUserNameW(username, &bufsize)) {
+    r = GetLastError();
+
+    /* This should not be possible */
+    if (r == ERROR_INSUFFICIENT_BUFFER)
+      return UV_ENOMEM;
+
+    return uv_translate_sys_error(r);
+  }
+
+  pwd->homedir = NULL;
+  r = uv__convert_utf16_to_utf8(path, -1, &pwd->homedir);
+
+  if (r != 0)
+    return r;
+
+  pwd->username = NULL;
+  r = uv__convert_utf16_to_utf8(username, -1, &pwd->username);
+
+  if (r != 0) {
+    uv__free(pwd->homedir);
+    return r;
+  }
+
+  pwd->shell = NULL;
+  pwd->uid = -1;
+  pwd->gid = -1;
+
+  return 0;
+}
+
+
+int uv_os_get_passwd(uv_passwd_t* pwd) {
+  return uv__getpwuid_r(pwd);
+}
diff --git a/Utilities/cmlibuv/src/win/winapi.c b/Utilities/cmlibuv/src/win/winapi.c
new file mode 100644
index 0000000..1fa179b
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/winapi.c
@@ -0,0 +1,159 @@
+/* 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 <assert.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+/* Ntdll function pointers */
+sRtlNtStatusToDosError pRtlNtStatusToDosError;
+sNtDeviceIoControlFile pNtDeviceIoControlFile;
+sNtQueryInformationFile pNtQueryInformationFile;
+sNtSetInformationFile pNtSetInformationFile;
+sNtQueryVolumeInformationFile pNtQueryVolumeInformationFile;
+sNtQueryDirectoryFile pNtQueryDirectoryFile;
+sNtQuerySystemInformation pNtQuerySystemInformation;
+
+
+/* Kernel32 function pointers */
+sGetQueuedCompletionStatusEx pGetQueuedCompletionStatusEx;
+sSetFileCompletionNotificationModes pSetFileCompletionNotificationModes;
+sCreateSymbolicLinkW pCreateSymbolicLinkW;
+sCancelIoEx pCancelIoEx;
+sInitializeConditionVariable pInitializeConditionVariable;
+sSleepConditionVariableCS pSleepConditionVariableCS;
+sSleepConditionVariableSRW pSleepConditionVariableSRW;
+sWakeAllConditionVariable pWakeAllConditionVariable;
+sWakeConditionVariable pWakeConditionVariable;
+sCancelSynchronousIo pCancelSynchronousIo;
+sGetFinalPathNameByHandleW pGetFinalPathNameByHandleW;
+
+
+/* Powrprof.dll function pointer */
+sPowerRegisterSuspendResumeNotification pPowerRegisterSuspendResumeNotification;
+
+
+void uv_winapi_init() {
+  HMODULE ntdll_module;
+  HMODULE kernel32_module;
+  HMODULE powrprof_module;
+
+  ntdll_module = GetModuleHandleA("ntdll.dll");
+  if (ntdll_module == NULL) {
+    uv_fatal_error(GetLastError(), "GetModuleHandleA");
+  }
+
+  pRtlNtStatusToDosError = (sRtlNtStatusToDosError) GetProcAddress(
+      ntdll_module,
+      "RtlNtStatusToDosError");
+  if (pRtlNtStatusToDosError == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtDeviceIoControlFile = (sNtDeviceIoControlFile) GetProcAddress(
+      ntdll_module,
+      "NtDeviceIoControlFile");
+  if (pNtDeviceIoControlFile == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtQueryInformationFile = (sNtQueryInformationFile) GetProcAddress(
+      ntdll_module,
+      "NtQueryInformationFile");
+  if (pNtQueryInformationFile == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtSetInformationFile = (sNtSetInformationFile) GetProcAddress(
+      ntdll_module,
+      "NtSetInformationFile");
+  if (pNtSetInformationFile == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtQueryVolumeInformationFile = (sNtQueryVolumeInformationFile)
+      GetProcAddress(ntdll_module, "NtQueryVolumeInformationFile");
+  if (pNtQueryVolumeInformationFile == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtQueryDirectoryFile = (sNtQueryDirectoryFile)
+      GetProcAddress(ntdll_module, "NtQueryDirectoryFile");
+  if (pNtQueryVolumeInformationFile == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  pNtQuerySystemInformation = (sNtQuerySystemInformation) GetProcAddress(
+      ntdll_module,
+      "NtQuerySystemInformation");
+  if (pNtQuerySystemInformation == NULL) {
+    uv_fatal_error(GetLastError(), "GetProcAddress");
+  }
+
+  kernel32_module = GetModuleHandleA("kernel32.dll");
+  if (kernel32_module == NULL) {
+    uv_fatal_error(GetLastError(), "GetModuleHandleA");
+  }
+
+  pGetQueuedCompletionStatusEx = (sGetQueuedCompletionStatusEx) GetProcAddress(
+      kernel32_module,
+      "GetQueuedCompletionStatusEx");
+
+  pSetFileCompletionNotificationModes = (sSetFileCompletionNotificationModes)
+    GetProcAddress(kernel32_module, "SetFileCompletionNotificationModes");
+
+  pCreateSymbolicLinkW = (sCreateSymbolicLinkW)
+    GetProcAddress(kernel32_module, "CreateSymbolicLinkW");
+
+  pCancelIoEx = (sCancelIoEx)
+    GetProcAddress(kernel32_module, "CancelIoEx");
+
+  pInitializeConditionVariable = (sInitializeConditionVariable)
+    GetProcAddress(kernel32_module, "InitializeConditionVariable");
+
+  pSleepConditionVariableCS = (sSleepConditionVariableCS)
+    GetProcAddress(kernel32_module, "SleepConditionVariableCS");
+
+  pSleepConditionVariableSRW = (sSleepConditionVariableSRW)
+    GetProcAddress(kernel32_module, "SleepConditionVariableSRW");
+
+  pWakeAllConditionVariable = (sWakeAllConditionVariable)
+    GetProcAddress(kernel32_module, "WakeAllConditionVariable");
+
+  pWakeConditionVariable = (sWakeConditionVariable)
+    GetProcAddress(kernel32_module, "WakeConditionVariable");
+
+  pCancelSynchronousIo = (sCancelSynchronousIo)
+    GetProcAddress(kernel32_module, "CancelSynchronousIo");
+
+  pGetFinalPathNameByHandleW = (sGetFinalPathNameByHandleW)
+    GetProcAddress(kernel32_module, "GetFinalPathNameByHandleW");
+
+
+  powrprof_module = LoadLibraryA("powrprof.dll");
+  if (powrprof_module != NULL) {
+    pPowerRegisterSuspendResumeNotification = (sPowerRegisterSuspendResumeNotification)
+      GetProcAddress(powrprof_module, "PowerRegisterSuspendResumeNotification");
+  }
+
+}
diff --git a/Utilities/cmlibuv/src/win/winapi.h b/Utilities/cmlibuv/src/win/winapi.h
new file mode 100644
index 0000000..597a93d
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/winapi.h
@@ -0,0 +1,4757 @@
+/* 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_WIN_WINAPI_H_
+#define UV_WIN_WINAPI_H_
+
+#include <windows.h>
+
+
+/*
+ * Ntdll headers
+ */
+#ifndef STATUS_SEVERITY_SUCCESS
+# define STATUS_SEVERITY_SUCCESS 0x0
+#endif
+
+#ifndef STATUS_SEVERITY_INFORMATIONAL
+# define STATUS_SEVERITY_INFORMATIONAL 0x1
+#endif
+
+#ifndef STATUS_SEVERITY_WARNING
+# define STATUS_SEVERITY_WARNING 0x2
+#endif
+
+#ifndef STATUS_SEVERITY_ERROR
+# define STATUS_SEVERITY_ERROR 0x3
+#endif
+
+#ifndef FACILITY_NTWIN32
+# define FACILITY_NTWIN32 0x7
+#endif
+
+#ifndef NT_SUCCESS
+# define NT_SUCCESS(status) (((NTSTATUS) (status)) >= 0)
+#endif
+
+#ifndef NT_INFORMATION
+# define NT_INFORMATION(status) ((((ULONG) (status)) >> 30) == 1)
+#endif
+
+#ifndef NT_WARNING
+# define NT_WARNING(status) ((((ULONG) (status)) >> 30) == 2)
+#endif
+
+#ifndef NT_ERROR
+# define NT_ERROR(status) ((((ULONG) (status)) >> 30) == 3)
+#endif
+
+#ifndef STATUS_SUCCESS
+# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
+#endif
+
+#ifndef STATUS_WAIT_0
+# define STATUS_WAIT_0 ((NTSTATUS) 0x00000000L)
+#endif
+
+#ifndef STATUS_WAIT_1
+# define STATUS_WAIT_1 ((NTSTATUS) 0x00000001L)
+#endif
+
+#ifndef STATUS_WAIT_2
+# define STATUS_WAIT_2 ((NTSTATUS) 0x00000002L)
+#endif
+
+#ifndef STATUS_WAIT_3
+# define STATUS_WAIT_3 ((NTSTATUS) 0x00000003L)
+#endif
+
+#ifndef STATUS_WAIT_63
+# define STATUS_WAIT_63 ((NTSTATUS) 0x0000003FL)
+#endif
+
+#ifndef STATUS_ABANDONED
+# define STATUS_ABANDONED ((NTSTATUS) 0x00000080L)
+#endif
+
+#ifndef STATUS_ABANDONED_WAIT_0
+# define STATUS_ABANDONED_WAIT_0 ((NTSTATUS) 0x00000080L)
+#endif
+
+#ifndef STATUS_ABANDONED_WAIT_63
+# define STATUS_ABANDONED_WAIT_63 ((NTSTATUS) 0x000000BFL)
+#endif
+
+#ifndef STATUS_USER_APC
+# define STATUS_USER_APC ((NTSTATUS) 0x000000C0L)
+#endif
+
+#ifndef STATUS_KERNEL_APC
+# define STATUS_KERNEL_APC ((NTSTATUS) 0x00000100L)
+#endif
+
+#ifndef STATUS_ALERTED
+# define STATUS_ALERTED ((NTSTATUS) 0x00000101L)
+#endif
+
+#ifndef STATUS_TIMEOUT
+# define STATUS_TIMEOUT ((NTSTATUS) 0x00000102L)
+#endif
+
+#ifndef STATUS_PENDING
+# define STATUS_PENDING ((NTSTATUS) 0x00000103L)
+#endif
+
+#ifndef STATUS_REPARSE
+# define STATUS_REPARSE ((NTSTATUS) 0x00000104L)
+#endif
+
+#ifndef STATUS_MORE_ENTRIES
+# define STATUS_MORE_ENTRIES ((NTSTATUS) 0x00000105L)
+#endif
+
+#ifndef STATUS_NOT_ALL_ASSIGNED
+# define STATUS_NOT_ALL_ASSIGNED ((NTSTATUS) 0x00000106L)
+#endif
+
+#ifndef STATUS_SOME_NOT_MAPPED
+# define STATUS_SOME_NOT_MAPPED ((NTSTATUS) 0x00000107L)
+#endif
+
+#ifndef STATUS_OPLOCK_BREAK_IN_PROGRESS
+# define STATUS_OPLOCK_BREAK_IN_PROGRESS ((NTSTATUS) 0x00000108L)
+#endif
+
+#ifndef STATUS_VOLUME_MOUNTED
+# define STATUS_VOLUME_MOUNTED ((NTSTATUS) 0x00000109L)
+#endif
+
+#ifndef STATUS_RXACT_COMMITTED
+# define STATUS_RXACT_COMMITTED ((NTSTATUS) 0x0000010AL)
+#endif
+
+#ifndef STATUS_NOTIFY_CLEANUP
+# define STATUS_NOTIFY_CLEANUP ((NTSTATUS) 0x0000010BL)
+#endif
+
+#ifndef STATUS_NOTIFY_ENUM_DIR
+# define STATUS_NOTIFY_ENUM_DIR ((NTSTATUS) 0x0000010CL)
+#endif
+
+#ifndef STATUS_NO_QUOTAS_FOR_ACCOUNT
+# define STATUS_NO_QUOTAS_FOR_ACCOUNT ((NTSTATUS) 0x0000010DL)
+#endif
+
+#ifndef STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED
+# define STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED ((NTSTATUS) 0x0000010EL)
+#endif
+
+#ifndef STATUS_PAGE_FAULT_TRANSITION
+# define STATUS_PAGE_FAULT_TRANSITION ((NTSTATUS) 0x00000110L)
+#endif
+
+#ifndef STATUS_PAGE_FAULT_DEMAND_ZERO
+# define STATUS_PAGE_FAULT_DEMAND_ZERO ((NTSTATUS) 0x00000111L)
+#endif
+
+#ifndef STATUS_PAGE_FAULT_COPY_ON_WRITE
+# define STATUS_PAGE_FAULT_COPY_ON_WRITE ((NTSTATUS) 0x00000112L)
+#endif
+
+#ifndef STATUS_PAGE_FAULT_GUARD_PAGE
+# define STATUS_PAGE_FAULT_GUARD_PAGE ((NTSTATUS) 0x00000113L)
+#endif
+
+#ifndef STATUS_PAGE_FAULT_PAGING_FILE
+# define STATUS_PAGE_FAULT_PAGING_FILE ((NTSTATUS) 0x00000114L)
+#endif
+
+#ifndef STATUS_CACHE_PAGE_LOCKED
+# define STATUS_CACHE_PAGE_LOCKED ((NTSTATUS) 0x00000115L)
+#endif
+
+#ifndef STATUS_CRASH_DUMP
+# define STATUS_CRASH_DUMP ((NTSTATUS) 0x00000116L)
+#endif
+
+#ifndef STATUS_BUFFER_ALL_ZEROS
+# define STATUS_BUFFER_ALL_ZEROS ((NTSTATUS) 0x00000117L)
+#endif
+
+#ifndef STATUS_REPARSE_OBJECT
+# define STATUS_REPARSE_OBJECT ((NTSTATUS) 0x00000118L)
+#endif
+
+#ifndef STATUS_RESOURCE_REQUIREMENTS_CHANGED
+# define STATUS_RESOURCE_REQUIREMENTS_CHANGED ((NTSTATUS) 0x00000119L)
+#endif
+
+#ifndef STATUS_TRANSLATION_COMPLETE
+# define STATUS_TRANSLATION_COMPLETE ((NTSTATUS) 0x00000120L)
+#endif
+
+#ifndef STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY
+# define STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY ((NTSTATUS) 0x00000121L)
+#endif
+
+#ifndef STATUS_NOTHING_TO_TERMINATE
+# define STATUS_NOTHING_TO_TERMINATE ((NTSTATUS) 0x00000122L)
+#endif
+
+#ifndef STATUS_PROCESS_NOT_IN_JOB
+# define STATUS_PROCESS_NOT_IN_JOB ((NTSTATUS) 0x00000123L)
+#endif
+
+#ifndef STATUS_PROCESS_IN_JOB
+# define STATUS_PROCESS_IN_JOB ((NTSTATUS) 0x00000124L)
+#endif
+
+#ifndef STATUS_VOLSNAP_HIBERNATE_READY
+# define STATUS_VOLSNAP_HIBERNATE_READY ((NTSTATUS) 0x00000125L)
+#endif
+
+#ifndef STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY
+# define STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY ((NTSTATUS) 0x00000126L)
+#endif
+
+#ifndef STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED
+# define STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED ((NTSTATUS) 0x00000127L)
+#endif
+
+#ifndef STATUS_INTERRUPT_STILL_CONNECTED
+# define STATUS_INTERRUPT_STILL_CONNECTED ((NTSTATUS) 0x00000128L)
+#endif
+
+#ifndef STATUS_PROCESS_CLONED
+# define STATUS_PROCESS_CLONED ((NTSTATUS) 0x00000129L)
+#endif
+
+#ifndef STATUS_FILE_LOCKED_WITH_ONLY_READERS
+# define STATUS_FILE_LOCKED_WITH_ONLY_READERS ((NTSTATUS) 0x0000012AL)
+#endif
+
+#ifndef STATUS_FILE_LOCKED_WITH_WRITERS
+# define STATUS_FILE_LOCKED_WITH_WRITERS ((NTSTATUS) 0x0000012BL)
+#endif
+
+#ifndef STATUS_RESOURCEMANAGER_READ_ONLY
+# define STATUS_RESOURCEMANAGER_READ_ONLY ((NTSTATUS) 0x00000202L)
+#endif
+
+#ifndef STATUS_RING_PREVIOUSLY_EMPTY
+# define STATUS_RING_PREVIOUSLY_EMPTY ((NTSTATUS) 0x00000210L)
+#endif
+
+#ifndef STATUS_RING_PREVIOUSLY_FULL
+# define STATUS_RING_PREVIOUSLY_FULL ((NTSTATUS) 0x00000211L)
+#endif
+
+#ifndef STATUS_RING_PREVIOUSLY_ABOVE_QUOTA
+# define STATUS_RING_PREVIOUSLY_ABOVE_QUOTA ((NTSTATUS) 0x00000212L)
+#endif
+
+#ifndef STATUS_RING_NEWLY_EMPTY
+# define STATUS_RING_NEWLY_EMPTY ((NTSTATUS) 0x00000213L)
+#endif
+
+#ifndef STATUS_RING_SIGNAL_OPPOSITE_ENDPOINT
+# define STATUS_RING_SIGNAL_OPPOSITE_ENDPOINT ((NTSTATUS) 0x00000214L)
+#endif
+
+#ifndef STATUS_OPLOCK_SWITCHED_TO_NEW_HANDLE
+# define STATUS_OPLOCK_SWITCHED_TO_NEW_HANDLE ((NTSTATUS) 0x00000215L)
+#endif
+
+#ifndef STATUS_OPLOCK_HANDLE_CLOSED
+# define STATUS_OPLOCK_HANDLE_CLOSED ((NTSTATUS) 0x00000216L)
+#endif
+
+#ifndef STATUS_WAIT_FOR_OPLOCK
+# define STATUS_WAIT_FOR_OPLOCK ((NTSTATUS) 0x00000367L)
+#endif
+
+#ifndef STATUS_OBJECT_NAME_EXISTS
+# define STATUS_OBJECT_NAME_EXISTS ((NTSTATUS) 0x40000000L)
+#endif
+
+#ifndef STATUS_THREAD_WAS_SUSPENDED
+# define STATUS_THREAD_WAS_SUSPENDED ((NTSTATUS) 0x40000001L)
+#endif
+
+#ifndef STATUS_WORKING_SET_LIMIT_RANGE
+# define STATUS_WORKING_SET_LIMIT_RANGE ((NTSTATUS) 0x40000002L)
+#endif
+
+#ifndef STATUS_IMAGE_NOT_AT_BASE
+# define STATUS_IMAGE_NOT_AT_BASE ((NTSTATUS) 0x40000003L)
+#endif
+
+#ifndef STATUS_RXACT_STATE_CREATED
+# define STATUS_RXACT_STATE_CREATED ((NTSTATUS) 0x40000004L)
+#endif
+
+#ifndef STATUS_SEGMENT_NOTIFICATION
+# define STATUS_SEGMENT_NOTIFICATION ((NTSTATUS) 0x40000005L)
+#endif
+
+#ifndef STATUS_LOCAL_USER_SESSION_KEY
+# define STATUS_LOCAL_USER_SESSION_KEY ((NTSTATUS) 0x40000006L)
+#endif
+
+#ifndef STATUS_BAD_CURRENT_DIRECTORY
+# define STATUS_BAD_CURRENT_DIRECTORY ((NTSTATUS) 0x40000007L)
+#endif
+
+#ifndef STATUS_SERIAL_MORE_WRITES
+# define STATUS_SERIAL_MORE_WRITES ((NTSTATUS) 0x40000008L)
+#endif
+
+#ifndef STATUS_REGISTRY_RECOVERED
+# define STATUS_REGISTRY_RECOVERED ((NTSTATUS) 0x40000009L)
+#endif
+
+#ifndef STATUS_FT_READ_RECOVERY_FROM_BACKUP
+# define STATUS_FT_READ_RECOVERY_FROM_BACKUP ((NTSTATUS) 0x4000000AL)
+#endif
+
+#ifndef STATUS_FT_WRITE_RECOVERY
+# define STATUS_FT_WRITE_RECOVERY ((NTSTATUS) 0x4000000BL)
+#endif
+
+#ifndef STATUS_SERIAL_COUNTER_TIMEOUT
+# define STATUS_SERIAL_COUNTER_TIMEOUT ((NTSTATUS) 0x4000000CL)
+#endif
+
+#ifndef STATUS_NULL_LM_PASSWORD
+# define STATUS_NULL_LM_PASSWORD ((NTSTATUS) 0x4000000DL)
+#endif
+
+#ifndef STATUS_IMAGE_MACHINE_TYPE_MISMATCH
+# define STATUS_IMAGE_MACHINE_TYPE_MISMATCH ((NTSTATUS) 0x4000000EL)
+#endif
+
+#ifndef STATUS_RECEIVE_PARTIAL
+# define STATUS_RECEIVE_PARTIAL ((NTSTATUS) 0x4000000FL)
+#endif
+
+#ifndef STATUS_RECEIVE_EXPEDITED
+# define STATUS_RECEIVE_EXPEDITED ((NTSTATUS) 0x40000010L)
+#endif
+
+#ifndef STATUS_RECEIVE_PARTIAL_EXPEDITED
+# define STATUS_RECEIVE_PARTIAL_EXPEDITED ((NTSTATUS) 0x40000011L)
+#endif
+
+#ifndef STATUS_EVENT_DONE
+# define STATUS_EVENT_DONE ((NTSTATUS) 0x40000012L)
+#endif
+
+#ifndef STATUS_EVENT_PENDING
+# define STATUS_EVENT_PENDING ((NTSTATUS) 0x40000013L)
+#endif
+
+#ifndef STATUS_CHECKING_FILE_SYSTEM
+# define STATUS_CHECKING_FILE_SYSTEM ((NTSTATUS) 0x40000014L)
+#endif
+
+#ifndef STATUS_FATAL_APP_EXIT
+# define STATUS_FATAL_APP_EXIT ((NTSTATUS) 0x40000015L)
+#endif
+
+#ifndef STATUS_PREDEFINED_HANDLE
+# define STATUS_PREDEFINED_HANDLE ((NTSTATUS) 0x40000016L)
+#endif
+
+#ifndef STATUS_WAS_UNLOCKED
+# define STATUS_WAS_UNLOCKED ((NTSTATUS) 0x40000017L)
+#endif
+
+#ifndef STATUS_SERVICE_NOTIFICATION
+# define STATUS_SERVICE_NOTIFICATION ((NTSTATUS) 0x40000018L)
+#endif
+
+#ifndef STATUS_WAS_LOCKED
+# define STATUS_WAS_LOCKED ((NTSTATUS) 0x40000019L)
+#endif
+
+#ifndef STATUS_LOG_HARD_ERROR
+# define STATUS_LOG_HARD_ERROR ((NTSTATUS) 0x4000001AL)
+#endif
+
+#ifndef STATUS_ALREADY_WIN32
+# define STATUS_ALREADY_WIN32 ((NTSTATUS) 0x4000001BL)
+#endif
+
+#ifndef STATUS_WX86_UNSIMULATE
+# define STATUS_WX86_UNSIMULATE ((NTSTATUS) 0x4000001CL)
+#endif
+
+#ifndef STATUS_WX86_CONTINUE
+# define STATUS_WX86_CONTINUE ((NTSTATUS) 0x4000001DL)
+#endif
+
+#ifndef STATUS_WX86_SINGLE_STEP
+# define STATUS_WX86_SINGLE_STEP ((NTSTATUS) 0x4000001EL)
+#endif
+
+#ifndef STATUS_WX86_BREAKPOINT
+# define STATUS_WX86_BREAKPOINT ((NTSTATUS) 0x4000001FL)
+#endif
+
+#ifndef STATUS_WX86_EXCEPTION_CONTINUE
+# define STATUS_WX86_EXCEPTION_CONTINUE ((NTSTATUS) 0x40000020L)
+#endif
+
+#ifndef STATUS_WX86_EXCEPTION_LASTCHANCE
+# define STATUS_WX86_EXCEPTION_LASTCHANCE ((NTSTATUS) 0x40000021L)
+#endif
+
+#ifndef STATUS_WX86_EXCEPTION_CHAIN
+# define STATUS_WX86_EXCEPTION_CHAIN ((NTSTATUS) 0x40000022L)
+#endif
+
+#ifndef STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE
+# define STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE ((NTSTATUS) 0x40000023L)
+#endif
+
+#ifndef STATUS_NO_YIELD_PERFORMED
+# define STATUS_NO_YIELD_PERFORMED ((NTSTATUS) 0x40000024L)
+#endif
+
+#ifndef STATUS_TIMER_RESUME_IGNORED
+# define STATUS_TIMER_RESUME_IGNORED ((NTSTATUS) 0x40000025L)
+#endif
+
+#ifndef STATUS_ARBITRATION_UNHANDLED
+# define STATUS_ARBITRATION_UNHANDLED ((NTSTATUS) 0x40000026L)
+#endif
+
+#ifndef STATUS_CARDBUS_NOT_SUPPORTED
+# define STATUS_CARDBUS_NOT_SUPPORTED ((NTSTATUS) 0x40000027L)
+#endif
+
+#ifndef STATUS_WX86_CREATEWX86TIB
+# define STATUS_WX86_CREATEWX86TIB ((NTSTATUS) 0x40000028L)
+#endif
+
+#ifndef STATUS_MP_PROCESSOR_MISMATCH
+# define STATUS_MP_PROCESSOR_MISMATCH ((NTSTATUS) 0x40000029L)
+#endif
+
+#ifndef STATUS_HIBERNATED
+# define STATUS_HIBERNATED ((NTSTATUS) 0x4000002AL)
+#endif
+
+#ifndef STATUS_RESUME_HIBERNATION
+# define STATUS_RESUME_HIBERNATION ((NTSTATUS) 0x4000002BL)
+#endif
+
+#ifndef STATUS_FIRMWARE_UPDATED
+# define STATUS_FIRMWARE_UPDATED ((NTSTATUS) 0x4000002CL)
+#endif
+
+#ifndef STATUS_DRIVERS_LEAKING_LOCKED_PAGES
+# define STATUS_DRIVERS_LEAKING_LOCKED_PAGES ((NTSTATUS) 0x4000002DL)
+#endif
+
+#ifndef STATUS_MESSAGE_RETRIEVED
+# define STATUS_MESSAGE_RETRIEVED ((NTSTATUS) 0x4000002EL)
+#endif
+
+#ifndef STATUS_SYSTEM_POWERSTATE_TRANSITION
+# define STATUS_SYSTEM_POWERSTATE_TRANSITION ((NTSTATUS) 0x4000002FL)
+#endif
+
+#ifndef STATUS_ALPC_CHECK_COMPLETION_LIST
+# define STATUS_ALPC_CHECK_COMPLETION_LIST ((NTSTATUS) 0x40000030L)
+#endif
+
+#ifndef STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION
+# define STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION ((NTSTATUS) 0x40000031L)
+#endif
+
+#ifndef STATUS_ACCESS_AUDIT_BY_POLICY
+# define STATUS_ACCESS_AUDIT_BY_POLICY ((NTSTATUS) 0x40000032L)
+#endif
+
+#ifndef STATUS_ABANDON_HIBERFILE
+# define STATUS_ABANDON_HIBERFILE ((NTSTATUS) 0x40000033L)
+#endif
+
+#ifndef STATUS_BIZRULES_NOT_ENABLED
+# define STATUS_BIZRULES_NOT_ENABLED ((NTSTATUS) 0x40000034L)
+#endif
+
+#ifndef STATUS_GUARD_PAGE_VIOLATION
+# define STATUS_GUARD_PAGE_VIOLATION ((NTSTATUS) 0x80000001L)
+#endif
+
+#ifndef STATUS_DATATYPE_MISALIGNMENT
+# define STATUS_DATATYPE_MISALIGNMENT ((NTSTATUS) 0x80000002L)
+#endif
+
+#ifndef STATUS_BREAKPOINT
+# define STATUS_BREAKPOINT ((NTSTATUS) 0x80000003L)
+#endif
+
+#ifndef STATUS_SINGLE_STEP
+# define STATUS_SINGLE_STEP ((NTSTATUS) 0x80000004L)
+#endif
+
+#ifndef STATUS_BUFFER_OVERFLOW
+# define STATUS_BUFFER_OVERFLOW ((NTSTATUS) 0x80000005L)
+#endif
+
+#ifndef STATUS_NO_MORE_FILES
+# define STATUS_NO_MORE_FILES ((NTSTATUS) 0x80000006L)
+#endif
+
+#ifndef STATUS_WAKE_SYSTEM_DEBUGGER
+# define STATUS_WAKE_SYSTEM_DEBUGGER ((NTSTATUS) 0x80000007L)
+#endif
+
+#ifndef STATUS_HANDLES_CLOSED
+# define STATUS_HANDLES_CLOSED ((NTSTATUS) 0x8000000AL)
+#endif
+
+#ifndef STATUS_NO_INHERITANCE
+# define STATUS_NO_INHERITANCE ((NTSTATUS) 0x8000000BL)
+#endif
+
+#ifndef STATUS_GUID_SUBSTITUTION_MADE
+# define STATUS_GUID_SUBSTITUTION_MADE ((NTSTATUS) 0x8000000CL)
+#endif
+
+#ifndef STATUS_PARTIAL_COPY
+# define STATUS_PARTIAL_COPY ((NTSTATUS) 0x8000000DL)
+#endif
+
+#ifndef STATUS_DEVICE_PAPER_EMPTY
+# define STATUS_DEVICE_PAPER_EMPTY ((NTSTATUS) 0x8000000EL)
+#endif
+
+#ifndef STATUS_DEVICE_POWERED_OFF
+# define STATUS_DEVICE_POWERED_OFF ((NTSTATUS) 0x8000000FL)
+#endif
+
+#ifndef STATUS_DEVICE_OFF_LINE
+# define STATUS_DEVICE_OFF_LINE ((NTSTATUS) 0x80000010L)
+#endif
+
+#ifndef STATUS_DEVICE_BUSY
+# define STATUS_DEVICE_BUSY ((NTSTATUS) 0x80000011L)
+#endif
+
+#ifndef STATUS_NO_MORE_EAS
+# define STATUS_NO_MORE_EAS ((NTSTATUS) 0x80000012L)
+#endif
+
+#ifndef STATUS_INVALID_EA_NAME
+# define STATUS_INVALID_EA_NAME ((NTSTATUS) 0x80000013L)
+#endif
+
+#ifndef STATUS_EA_LIST_INCONSISTENT
+# define STATUS_EA_LIST_INCONSISTENT ((NTSTATUS) 0x80000014L)
+#endif
+
+#ifndef STATUS_INVALID_EA_FLAG
+# define STATUS_INVALID_EA_FLAG ((NTSTATUS) 0x80000015L)
+#endif
+
+#ifndef STATUS_VERIFY_REQUIRED
+# define STATUS_VERIFY_REQUIRED ((NTSTATUS) 0x80000016L)
+#endif
+
+#ifndef STATUS_EXTRANEOUS_INFORMATION
+# define STATUS_EXTRANEOUS_INFORMATION ((NTSTATUS) 0x80000017L)
+#endif
+
+#ifndef STATUS_RXACT_COMMIT_NECESSARY
+# define STATUS_RXACT_COMMIT_NECESSARY ((NTSTATUS) 0x80000018L)
+#endif
+
+#ifndef STATUS_NO_MORE_ENTRIES
+# define STATUS_NO_MORE_ENTRIES ((NTSTATUS) 0x8000001AL)
+#endif
+
+#ifndef STATUS_FILEMARK_DETECTED
+# define STATUS_FILEMARK_DETECTED ((NTSTATUS) 0x8000001BL)
+#endif
+
+#ifndef STATUS_MEDIA_CHANGED
+# define STATUS_MEDIA_CHANGED ((NTSTATUS) 0x8000001CL)
+#endif
+
+#ifndef STATUS_BUS_RESET
+# define STATUS_BUS_RESET ((NTSTATUS) 0x8000001DL)
+#endif
+
+#ifndef STATUS_END_OF_MEDIA
+# define STATUS_END_OF_MEDIA ((NTSTATUS) 0x8000001EL)
+#endif
+
+#ifndef STATUS_BEGINNING_OF_MEDIA
+# define STATUS_BEGINNING_OF_MEDIA ((NTSTATUS) 0x8000001FL)
+#endif
+
+#ifndef STATUS_MEDIA_CHECK
+# define STATUS_MEDIA_CHECK ((NTSTATUS) 0x80000020L)
+#endif
+
+#ifndef STATUS_SETMARK_DETECTED
+# define STATUS_SETMARK_DETECTED ((NTSTATUS) 0x80000021L)
+#endif
+
+#ifndef STATUS_NO_DATA_DETECTED
+# define STATUS_NO_DATA_DETECTED ((NTSTATUS) 0x80000022L)
+#endif
+
+#ifndef STATUS_REDIRECTOR_HAS_OPEN_HANDLES
+# define STATUS_REDIRECTOR_HAS_OPEN_HANDLES ((NTSTATUS) 0x80000023L)
+#endif
+
+#ifndef STATUS_SERVER_HAS_OPEN_HANDLES
+# define STATUS_SERVER_HAS_OPEN_HANDLES ((NTSTATUS) 0x80000024L)
+#endif
+
+#ifndef STATUS_ALREADY_DISCONNECTED
+# define STATUS_ALREADY_DISCONNECTED ((NTSTATUS) 0x80000025L)
+#endif
+
+#ifndef STATUS_LONGJUMP
+# define STATUS_LONGJUMP ((NTSTATUS) 0x80000026L)
+#endif
+
+#ifndef STATUS_CLEANER_CARTRIDGE_INSTALLED
+# define STATUS_CLEANER_CARTRIDGE_INSTALLED ((NTSTATUS) 0x80000027L)
+#endif
+
+#ifndef STATUS_PLUGPLAY_QUERY_VETOED
+# define STATUS_PLUGPLAY_QUERY_VETOED ((NTSTATUS) 0x80000028L)
+#endif
+
+#ifndef STATUS_UNWIND_CONSOLIDATE
+# define STATUS_UNWIND_CONSOLIDATE ((NTSTATUS) 0x80000029L)
+#endif
+
+#ifndef STATUS_REGISTRY_HIVE_RECOVERED
+# define STATUS_REGISTRY_HIVE_RECOVERED ((NTSTATUS) 0x8000002AL)
+#endif
+
+#ifndef STATUS_DLL_MIGHT_BE_INSECURE
+# define STATUS_DLL_MIGHT_BE_INSECURE ((NTSTATUS) 0x8000002BL)
+#endif
+
+#ifndef STATUS_DLL_MIGHT_BE_INCOMPATIBLE
+# define STATUS_DLL_MIGHT_BE_INCOMPATIBLE ((NTSTATUS) 0x8000002CL)
+#endif
+
+#ifndef STATUS_STOPPED_ON_SYMLINK
+# define STATUS_STOPPED_ON_SYMLINK ((NTSTATUS) 0x8000002DL)
+#endif
+
+#ifndef STATUS_CANNOT_GRANT_REQUESTED_OPLOCK
+# define STATUS_CANNOT_GRANT_REQUESTED_OPLOCK ((NTSTATUS) 0x8000002EL)
+#endif
+
+#ifndef STATUS_NO_ACE_CONDITION
+# define STATUS_NO_ACE_CONDITION ((NTSTATUS) 0x8000002FL)
+#endif
+
+#ifndef STATUS_UNSUCCESSFUL
+# define STATUS_UNSUCCESSFUL ((NTSTATUS) 0xC0000001L)
+#endif
+
+#ifndef STATUS_NOT_IMPLEMENTED
+# define STATUS_NOT_IMPLEMENTED ((NTSTATUS) 0xC0000002L)
+#endif
+
+#ifndef STATUS_INVALID_INFO_CLASS
+# define STATUS_INVALID_INFO_CLASS ((NTSTATUS) 0xC0000003L)
+#endif
+
+#ifndef STATUS_INFO_LENGTH_MISMATCH
+# define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS) 0xC0000004L)
+#endif
+
+#ifndef STATUS_ACCESS_VIOLATION
+# define STATUS_ACCESS_VIOLATION ((NTSTATUS) 0xC0000005L)
+#endif
+
+#ifndef STATUS_IN_PAGE_ERROR
+# define STATUS_IN_PAGE_ERROR ((NTSTATUS) 0xC0000006L)
+#endif
+
+#ifndef STATUS_PAGEFILE_QUOTA
+# define STATUS_PAGEFILE_QUOTA ((NTSTATUS) 0xC0000007L)
+#endif
+
+#ifndef STATUS_INVALID_HANDLE
+# define STATUS_INVALID_HANDLE ((NTSTATUS) 0xC0000008L)
+#endif
+
+#ifndef STATUS_BAD_INITIAL_STACK
+# define STATUS_BAD_INITIAL_STACK ((NTSTATUS) 0xC0000009L)
+#endif
+
+#ifndef STATUS_BAD_INITIAL_PC
+# define STATUS_BAD_INITIAL_PC ((NTSTATUS) 0xC000000AL)
+#endif
+
+#ifndef STATUS_INVALID_CID
+# define STATUS_INVALID_CID ((NTSTATUS) 0xC000000BL)
+#endif
+
+#ifndef STATUS_TIMER_NOT_CANCELED
+# define STATUS_TIMER_NOT_CANCELED ((NTSTATUS) 0xC000000CL)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER
+# define STATUS_INVALID_PARAMETER ((NTSTATUS) 0xC000000DL)
+#endif
+
+#ifndef STATUS_NO_SUCH_DEVICE
+# define STATUS_NO_SUCH_DEVICE ((NTSTATUS) 0xC000000EL)
+#endif
+
+#ifndef STATUS_NO_SUCH_FILE
+# define STATUS_NO_SUCH_FILE ((NTSTATUS) 0xC000000FL)
+#endif
+
+#ifndef STATUS_INVALID_DEVICE_REQUEST
+# define STATUS_INVALID_DEVICE_REQUEST ((NTSTATUS) 0xC0000010L)
+#endif
+
+#ifndef STATUS_END_OF_FILE
+# define STATUS_END_OF_FILE ((NTSTATUS) 0xC0000011L)
+#endif
+
+#ifndef STATUS_WRONG_VOLUME
+# define STATUS_WRONG_VOLUME ((NTSTATUS) 0xC0000012L)
+#endif
+
+#ifndef STATUS_NO_MEDIA_IN_DEVICE
+# define STATUS_NO_MEDIA_IN_DEVICE ((NTSTATUS) 0xC0000013L)
+#endif
+
+#ifndef STATUS_UNRECOGNIZED_MEDIA
+# define STATUS_UNRECOGNIZED_MEDIA ((NTSTATUS) 0xC0000014L)
+#endif
+
+#ifndef STATUS_NONEXISTENT_SECTOR
+# define STATUS_NONEXISTENT_SECTOR ((NTSTATUS) 0xC0000015L)
+#endif
+
+#ifndef STATUS_MORE_PROCESSING_REQUIRED
+# define STATUS_MORE_PROCESSING_REQUIRED ((NTSTATUS) 0xC0000016L)
+#endif
+
+#ifndef STATUS_NO_MEMORY
+# define STATUS_NO_MEMORY ((NTSTATUS) 0xC0000017L)
+#endif
+
+#ifndef STATUS_CONFLICTING_ADDRESSES
+# define STATUS_CONFLICTING_ADDRESSES ((NTSTATUS) 0xC0000018L)
+#endif
+
+#ifndef STATUS_NOT_MAPPED_VIEW
+# define STATUS_NOT_MAPPED_VIEW ((NTSTATUS) 0xC0000019L)
+#endif
+
+#ifndef STATUS_UNABLE_TO_FREE_VM
+# define STATUS_UNABLE_TO_FREE_VM ((NTSTATUS) 0xC000001AL)
+#endif
+
+#ifndef STATUS_UNABLE_TO_DELETE_SECTION
+# define STATUS_UNABLE_TO_DELETE_SECTION ((NTSTATUS) 0xC000001BL)
+#endif
+
+#ifndef STATUS_INVALID_SYSTEM_SERVICE
+# define STATUS_INVALID_SYSTEM_SERVICE ((NTSTATUS) 0xC000001CL)
+#endif
+
+#ifndef STATUS_ILLEGAL_INSTRUCTION
+# define STATUS_ILLEGAL_INSTRUCTION ((NTSTATUS) 0xC000001DL)
+#endif
+
+#ifndef STATUS_INVALID_LOCK_SEQUENCE
+# define STATUS_INVALID_LOCK_SEQUENCE ((NTSTATUS) 0xC000001EL)
+#endif
+
+#ifndef STATUS_INVALID_VIEW_SIZE
+# define STATUS_INVALID_VIEW_SIZE ((NTSTATUS) 0xC000001FL)
+#endif
+
+#ifndef STATUS_INVALID_FILE_FOR_SECTION
+# define STATUS_INVALID_FILE_FOR_SECTION ((NTSTATUS) 0xC0000020L)
+#endif
+
+#ifndef STATUS_ALREADY_COMMITTED
+# define STATUS_ALREADY_COMMITTED ((NTSTATUS) 0xC0000021L)
+#endif
+
+#ifndef STATUS_ACCESS_DENIED
+# define STATUS_ACCESS_DENIED ((NTSTATUS) 0xC0000022L)
+#endif
+
+#ifndef STATUS_BUFFER_TOO_SMALL
+# define STATUS_BUFFER_TOO_SMALL ((NTSTATUS) 0xC0000023L)
+#endif
+
+#ifndef STATUS_OBJECT_TYPE_MISMATCH
+# define STATUS_OBJECT_TYPE_MISMATCH ((NTSTATUS) 0xC0000024L)
+#endif
+
+#ifndef STATUS_NONCONTINUABLE_EXCEPTION
+# define STATUS_NONCONTINUABLE_EXCEPTION ((NTSTATUS) 0xC0000025L)
+#endif
+
+#ifndef STATUS_INVALID_DISPOSITION
+# define STATUS_INVALID_DISPOSITION ((NTSTATUS) 0xC0000026L)
+#endif
+
+#ifndef STATUS_UNWIND
+# define STATUS_UNWIND ((NTSTATUS) 0xC0000027L)
+#endif
+
+#ifndef STATUS_BAD_STACK
+# define STATUS_BAD_STACK ((NTSTATUS) 0xC0000028L)
+#endif
+
+#ifndef STATUS_INVALID_UNWIND_TARGET
+# define STATUS_INVALID_UNWIND_TARGET ((NTSTATUS) 0xC0000029L)
+#endif
+
+#ifndef STATUS_NOT_LOCKED
+# define STATUS_NOT_LOCKED ((NTSTATUS) 0xC000002AL)
+#endif
+
+#ifndef STATUS_PARITY_ERROR
+# define STATUS_PARITY_ERROR ((NTSTATUS) 0xC000002BL)
+#endif
+
+#ifndef STATUS_UNABLE_TO_DECOMMIT_VM
+# define STATUS_UNABLE_TO_DECOMMIT_VM ((NTSTATUS) 0xC000002CL)
+#endif
+
+#ifndef STATUS_NOT_COMMITTED
+# define STATUS_NOT_COMMITTED ((NTSTATUS) 0xC000002DL)
+#endif
+
+#ifndef STATUS_INVALID_PORT_ATTRIBUTES
+# define STATUS_INVALID_PORT_ATTRIBUTES ((NTSTATUS) 0xC000002EL)
+#endif
+
+#ifndef STATUS_PORT_MESSAGE_TOO_LONG
+# define STATUS_PORT_MESSAGE_TOO_LONG ((NTSTATUS) 0xC000002FL)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_MIX
+# define STATUS_INVALID_PARAMETER_MIX ((NTSTATUS) 0xC0000030L)
+#endif
+
+#ifndef STATUS_INVALID_QUOTA_LOWER
+# define STATUS_INVALID_QUOTA_LOWER ((NTSTATUS) 0xC0000031L)
+#endif
+
+#ifndef STATUS_DISK_CORRUPT_ERROR
+# define STATUS_DISK_CORRUPT_ERROR ((NTSTATUS) 0xC0000032L)
+#endif
+
+#ifndef STATUS_OBJECT_NAME_INVALID
+# define STATUS_OBJECT_NAME_INVALID ((NTSTATUS) 0xC0000033L)
+#endif
+
+#ifndef STATUS_OBJECT_NAME_NOT_FOUND
+# define STATUS_OBJECT_NAME_NOT_FOUND ((NTSTATUS) 0xC0000034L)
+#endif
+
+#ifndef STATUS_OBJECT_NAME_COLLISION
+# define STATUS_OBJECT_NAME_COLLISION ((NTSTATUS) 0xC0000035L)
+#endif
+
+#ifndef STATUS_PORT_DISCONNECTED
+# define STATUS_PORT_DISCONNECTED ((NTSTATUS) 0xC0000037L)
+#endif
+
+#ifndef STATUS_DEVICE_ALREADY_ATTACHED
+# define STATUS_DEVICE_ALREADY_ATTACHED ((NTSTATUS) 0xC0000038L)
+#endif
+
+#ifndef STATUS_OBJECT_PATH_INVALID
+# define STATUS_OBJECT_PATH_INVALID ((NTSTATUS) 0xC0000039L)
+#endif
+
+#ifndef STATUS_OBJECT_PATH_NOT_FOUND
+# define STATUS_OBJECT_PATH_NOT_FOUND ((NTSTATUS) 0xC000003AL)
+#endif
+
+#ifndef STATUS_OBJECT_PATH_SYNTAX_BAD
+# define STATUS_OBJECT_PATH_SYNTAX_BAD ((NTSTATUS) 0xC000003BL)
+#endif
+
+#ifndef STATUS_DATA_OVERRUN
+# define STATUS_DATA_OVERRUN ((NTSTATUS) 0xC000003CL)
+#endif
+
+#ifndef STATUS_DATA_LATE_ERROR
+# define STATUS_DATA_LATE_ERROR ((NTSTATUS) 0xC000003DL)
+#endif
+
+#ifndef STATUS_DATA_ERROR
+# define STATUS_DATA_ERROR ((NTSTATUS) 0xC000003EL)
+#endif
+
+#ifndef STATUS_CRC_ERROR
+# define STATUS_CRC_ERROR ((NTSTATUS) 0xC000003FL)
+#endif
+
+#ifndef STATUS_SECTION_TOO_BIG
+# define STATUS_SECTION_TOO_BIG ((NTSTATUS) 0xC0000040L)
+#endif
+
+#ifndef STATUS_PORT_CONNECTION_REFUSED
+# define STATUS_PORT_CONNECTION_REFUSED ((NTSTATUS) 0xC0000041L)
+#endif
+
+#ifndef STATUS_INVALID_PORT_HANDLE
+# define STATUS_INVALID_PORT_HANDLE ((NTSTATUS) 0xC0000042L)
+#endif
+
+#ifndef STATUS_SHARING_VIOLATION
+# define STATUS_SHARING_VIOLATION ((NTSTATUS) 0xC0000043L)
+#endif
+
+#ifndef STATUS_QUOTA_EXCEEDED
+# define STATUS_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000044L)
+#endif
+
+#ifndef STATUS_INVALID_PAGE_PROTECTION
+# define STATUS_INVALID_PAGE_PROTECTION ((NTSTATUS) 0xC0000045L)
+#endif
+
+#ifndef STATUS_MUTANT_NOT_OWNED
+# define STATUS_MUTANT_NOT_OWNED ((NTSTATUS) 0xC0000046L)
+#endif
+
+#ifndef STATUS_SEMAPHORE_LIMIT_EXCEEDED
+# define STATUS_SEMAPHORE_LIMIT_EXCEEDED ((NTSTATUS) 0xC0000047L)
+#endif
+
+#ifndef STATUS_PORT_ALREADY_SET
+# define STATUS_PORT_ALREADY_SET ((NTSTATUS) 0xC0000048L)
+#endif
+
+#ifndef STATUS_SECTION_NOT_IMAGE
+# define STATUS_SECTION_NOT_IMAGE ((NTSTATUS) 0xC0000049L)
+#endif
+
+#ifndef STATUS_SUSPEND_COUNT_EXCEEDED
+# define STATUS_SUSPEND_COUNT_EXCEEDED ((NTSTATUS) 0xC000004AL)
+#endif
+
+#ifndef STATUS_THREAD_IS_TERMINATING
+# define STATUS_THREAD_IS_TERMINATING ((NTSTATUS) 0xC000004BL)
+#endif
+
+#ifndef STATUS_BAD_WORKING_SET_LIMIT
+# define STATUS_BAD_WORKING_SET_LIMIT ((NTSTATUS) 0xC000004CL)
+#endif
+
+#ifndef STATUS_INCOMPATIBLE_FILE_MAP
+# define STATUS_INCOMPATIBLE_FILE_MAP ((NTSTATUS) 0xC000004DL)
+#endif
+
+#ifndef STATUS_SECTION_PROTECTION
+# define STATUS_SECTION_PROTECTION ((NTSTATUS) 0xC000004EL)
+#endif
+
+#ifndef STATUS_EAS_NOT_SUPPORTED
+# define STATUS_EAS_NOT_SUPPORTED ((NTSTATUS) 0xC000004FL)
+#endif
+
+#ifndef STATUS_EA_TOO_LARGE
+# define STATUS_EA_TOO_LARGE ((NTSTATUS) 0xC0000050L)
+#endif
+
+#ifndef STATUS_NONEXISTENT_EA_ENTRY
+# define STATUS_NONEXISTENT_EA_ENTRY ((NTSTATUS) 0xC0000051L)
+#endif
+
+#ifndef STATUS_NO_EAS_ON_FILE
+# define STATUS_NO_EAS_ON_FILE ((NTSTATUS) 0xC0000052L)
+#endif
+
+#ifndef STATUS_EA_CORRUPT_ERROR
+# define STATUS_EA_CORRUPT_ERROR ((NTSTATUS) 0xC0000053L)
+#endif
+
+#ifndef STATUS_FILE_LOCK_CONFLICT
+# define STATUS_FILE_LOCK_CONFLICT ((NTSTATUS) 0xC0000054L)
+#endif
+
+#ifndef STATUS_LOCK_NOT_GRANTED
+# define STATUS_LOCK_NOT_GRANTED ((NTSTATUS) 0xC0000055L)
+#endif
+
+#ifndef STATUS_DELETE_PENDING
+# define STATUS_DELETE_PENDING ((NTSTATUS) 0xC0000056L)
+#endif
+
+#ifndef STATUS_CTL_FILE_NOT_SUPPORTED
+# define STATUS_CTL_FILE_NOT_SUPPORTED ((NTSTATUS) 0xC0000057L)
+#endif
+
+#ifndef STATUS_UNKNOWN_REVISION
+# define STATUS_UNKNOWN_REVISION ((NTSTATUS) 0xC0000058L)
+#endif
+
+#ifndef STATUS_REVISION_MISMATCH
+# define STATUS_REVISION_MISMATCH ((NTSTATUS) 0xC0000059L)
+#endif
+
+#ifndef STATUS_INVALID_OWNER
+# define STATUS_INVALID_OWNER ((NTSTATUS) 0xC000005AL)
+#endif
+
+#ifndef STATUS_INVALID_PRIMARY_GROUP
+# define STATUS_INVALID_PRIMARY_GROUP ((NTSTATUS) 0xC000005BL)
+#endif
+
+#ifndef STATUS_NO_IMPERSONATION_TOKEN
+# define STATUS_NO_IMPERSONATION_TOKEN ((NTSTATUS) 0xC000005CL)
+#endif
+
+#ifndef STATUS_CANT_DISABLE_MANDATORY
+# define STATUS_CANT_DISABLE_MANDATORY ((NTSTATUS) 0xC000005DL)
+#endif
+
+#ifndef STATUS_NO_LOGON_SERVERS
+# define STATUS_NO_LOGON_SERVERS ((NTSTATUS) 0xC000005EL)
+#endif
+
+#ifndef STATUS_NO_SUCH_LOGON_SESSION
+# define STATUS_NO_SUCH_LOGON_SESSION ((NTSTATUS) 0xC000005FL)
+#endif
+
+#ifndef STATUS_NO_SUCH_PRIVILEGE
+# define STATUS_NO_SUCH_PRIVILEGE ((NTSTATUS) 0xC0000060L)
+#endif
+
+#ifndef STATUS_PRIVILEGE_NOT_HELD
+# define STATUS_PRIVILEGE_NOT_HELD ((NTSTATUS) 0xC0000061L)
+#endif
+
+#ifndef STATUS_INVALID_ACCOUNT_NAME
+# define STATUS_INVALID_ACCOUNT_NAME ((NTSTATUS) 0xC0000062L)
+#endif
+
+#ifndef STATUS_USER_EXISTS
+# define STATUS_USER_EXISTS ((NTSTATUS) 0xC0000063L)
+#endif
+
+#ifndef STATUS_NO_SUCH_USER
+# define STATUS_NO_SUCH_USER ((NTSTATUS) 0xC0000064L)
+#endif
+
+#ifndef STATUS_GROUP_EXISTS
+# define STATUS_GROUP_EXISTS ((NTSTATUS) 0xC0000065L)
+#endif
+
+#ifndef STATUS_NO_SUCH_GROUP
+# define STATUS_NO_SUCH_GROUP ((NTSTATUS) 0xC0000066L)
+#endif
+
+#ifndef STATUS_MEMBER_IN_GROUP
+# define STATUS_MEMBER_IN_GROUP ((NTSTATUS) 0xC0000067L)
+#endif
+
+#ifndef STATUS_MEMBER_NOT_IN_GROUP
+# define STATUS_MEMBER_NOT_IN_GROUP ((NTSTATUS) 0xC0000068L)
+#endif
+
+#ifndef STATUS_LAST_ADMIN
+# define STATUS_LAST_ADMIN ((NTSTATUS) 0xC0000069L)
+#endif
+
+#ifndef STATUS_WRONG_PASSWORD
+# define STATUS_WRONG_PASSWORD ((NTSTATUS) 0xC000006AL)
+#endif
+
+#ifndef STATUS_ILL_FORMED_PASSWORD
+# define STATUS_ILL_FORMED_PASSWORD ((NTSTATUS) 0xC000006BL)
+#endif
+
+#ifndef STATUS_PASSWORD_RESTRICTION
+# define STATUS_PASSWORD_RESTRICTION ((NTSTATUS) 0xC000006CL)
+#endif
+
+#ifndef STATUS_LOGON_FAILURE
+# define STATUS_LOGON_FAILURE ((NTSTATUS) 0xC000006DL)
+#endif
+
+#ifndef STATUS_ACCOUNT_RESTRICTION
+# define STATUS_ACCOUNT_RESTRICTION ((NTSTATUS) 0xC000006EL)
+#endif
+
+#ifndef STATUS_INVALID_LOGON_HOURS
+# define STATUS_INVALID_LOGON_HOURS ((NTSTATUS) 0xC000006FL)
+#endif
+
+#ifndef STATUS_INVALID_WORKSTATION
+# define STATUS_INVALID_WORKSTATION ((NTSTATUS) 0xC0000070L)
+#endif
+
+#ifndef STATUS_PASSWORD_EXPIRED
+# define STATUS_PASSWORD_EXPIRED ((NTSTATUS) 0xC0000071L)
+#endif
+
+#ifndef STATUS_ACCOUNT_DISABLED
+# define STATUS_ACCOUNT_DISABLED ((NTSTATUS) 0xC0000072L)
+#endif
+
+#ifndef STATUS_NONE_MAPPED
+# define STATUS_NONE_MAPPED ((NTSTATUS) 0xC0000073L)
+#endif
+
+#ifndef STATUS_TOO_MANY_LUIDS_REQUESTED
+# define STATUS_TOO_MANY_LUIDS_REQUESTED ((NTSTATUS) 0xC0000074L)
+#endif
+
+#ifndef STATUS_LUIDS_EXHAUSTED
+# define STATUS_LUIDS_EXHAUSTED ((NTSTATUS) 0xC0000075L)
+#endif
+
+#ifndef STATUS_INVALID_SUB_AUTHORITY
+# define STATUS_INVALID_SUB_AUTHORITY ((NTSTATUS) 0xC0000076L)
+#endif
+
+#ifndef STATUS_INVALID_ACL
+# define STATUS_INVALID_ACL ((NTSTATUS) 0xC0000077L)
+#endif
+
+#ifndef STATUS_INVALID_SID
+# define STATUS_INVALID_SID ((NTSTATUS) 0xC0000078L)
+#endif
+
+#ifndef STATUS_INVALID_SECURITY_DESCR
+# define STATUS_INVALID_SECURITY_DESCR ((NTSTATUS) 0xC0000079L)
+#endif
+
+#ifndef STATUS_PROCEDURE_NOT_FOUND
+# define STATUS_PROCEDURE_NOT_FOUND ((NTSTATUS) 0xC000007AL)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_FORMAT
+# define STATUS_INVALID_IMAGE_FORMAT ((NTSTATUS) 0xC000007BL)
+#endif
+
+#ifndef STATUS_NO_TOKEN
+# define STATUS_NO_TOKEN ((NTSTATUS) 0xC000007CL)
+#endif
+
+#ifndef STATUS_BAD_INHERITANCE_ACL
+# define STATUS_BAD_INHERITANCE_ACL ((NTSTATUS) 0xC000007DL)
+#endif
+
+#ifndef STATUS_RANGE_NOT_LOCKED
+# define STATUS_RANGE_NOT_LOCKED ((NTSTATUS) 0xC000007EL)
+#endif
+
+#ifndef STATUS_DISK_FULL
+# define STATUS_DISK_FULL ((NTSTATUS) 0xC000007FL)
+#endif
+
+#ifndef STATUS_SERVER_DISABLED
+# define STATUS_SERVER_DISABLED ((NTSTATUS) 0xC0000080L)
+#endif
+
+#ifndef STATUS_SERVER_NOT_DISABLED
+# define STATUS_SERVER_NOT_DISABLED ((NTSTATUS) 0xC0000081L)
+#endif
+
+#ifndef STATUS_TOO_MANY_GUIDS_REQUESTED
+# define STATUS_TOO_MANY_GUIDS_REQUESTED ((NTSTATUS) 0xC0000082L)
+#endif
+
+#ifndef STATUS_GUIDS_EXHAUSTED
+# define STATUS_GUIDS_EXHAUSTED ((NTSTATUS) 0xC0000083L)
+#endif
+
+#ifndef STATUS_INVALID_ID_AUTHORITY
+# define STATUS_INVALID_ID_AUTHORITY ((NTSTATUS) 0xC0000084L)
+#endif
+
+#ifndef STATUS_AGENTS_EXHAUSTED
+# define STATUS_AGENTS_EXHAUSTED ((NTSTATUS) 0xC0000085L)
+#endif
+
+#ifndef STATUS_INVALID_VOLUME_LABEL
+# define STATUS_INVALID_VOLUME_LABEL ((NTSTATUS) 0xC0000086L)
+#endif
+
+#ifndef STATUS_SECTION_NOT_EXTENDED
+# define STATUS_SECTION_NOT_EXTENDED ((NTSTATUS) 0xC0000087L)
+#endif
+
+#ifndef STATUS_NOT_MAPPED_DATA
+# define STATUS_NOT_MAPPED_DATA ((NTSTATUS) 0xC0000088L)
+#endif
+
+#ifndef STATUS_RESOURCE_DATA_NOT_FOUND
+# define STATUS_RESOURCE_DATA_NOT_FOUND ((NTSTATUS) 0xC0000089L)
+#endif
+
+#ifndef STATUS_RESOURCE_TYPE_NOT_FOUND
+# define STATUS_RESOURCE_TYPE_NOT_FOUND ((NTSTATUS) 0xC000008AL)
+#endif
+
+#ifndef STATUS_RESOURCE_NAME_NOT_FOUND
+# define STATUS_RESOURCE_NAME_NOT_FOUND ((NTSTATUS) 0xC000008BL)
+#endif
+
+#ifndef STATUS_ARRAY_BOUNDS_EXCEEDED
+# define STATUS_ARRAY_BOUNDS_EXCEEDED ((NTSTATUS) 0xC000008CL)
+#endif
+
+#ifndef STATUS_FLOAT_DENORMAL_OPERAND
+# define STATUS_FLOAT_DENORMAL_OPERAND ((NTSTATUS) 0xC000008DL)
+#endif
+
+#ifndef STATUS_FLOAT_DIVIDE_BY_ZERO
+# define STATUS_FLOAT_DIVIDE_BY_ZERO ((NTSTATUS) 0xC000008EL)
+#endif
+
+#ifndef STATUS_FLOAT_INEXACT_RESULT
+# define STATUS_FLOAT_INEXACT_RESULT ((NTSTATUS) 0xC000008FL)
+#endif
+
+#ifndef STATUS_FLOAT_INVALID_OPERATION
+# define STATUS_FLOAT_INVALID_OPERATION ((NTSTATUS) 0xC0000090L)
+#endif
+
+#ifndef STATUS_FLOAT_OVERFLOW
+# define STATUS_FLOAT_OVERFLOW ((NTSTATUS) 0xC0000091L)
+#endif
+
+#ifndef STATUS_FLOAT_STACK_CHECK
+# define STATUS_FLOAT_STACK_CHECK ((NTSTATUS) 0xC0000092L)
+#endif
+
+#ifndef STATUS_FLOAT_UNDERFLOW
+# define STATUS_FLOAT_UNDERFLOW ((NTSTATUS) 0xC0000093L)
+#endif
+
+#ifndef STATUS_INTEGER_DIVIDE_BY_ZERO
+# define STATUS_INTEGER_DIVIDE_BY_ZERO ((NTSTATUS) 0xC0000094L)
+#endif
+
+#ifndef STATUS_INTEGER_OVERFLOW
+# define STATUS_INTEGER_OVERFLOW ((NTSTATUS) 0xC0000095L)
+#endif
+
+#ifndef STATUS_PRIVILEGED_INSTRUCTION
+# define STATUS_PRIVILEGED_INSTRUCTION ((NTSTATUS) 0xC0000096L)
+#endif
+
+#ifndef STATUS_TOO_MANY_PAGING_FILES
+# define STATUS_TOO_MANY_PAGING_FILES ((NTSTATUS) 0xC0000097L)
+#endif
+
+#ifndef STATUS_FILE_INVALID
+# define STATUS_FILE_INVALID ((NTSTATUS) 0xC0000098L)
+#endif
+
+#ifndef STATUS_ALLOTTED_SPACE_EXCEEDED
+# define STATUS_ALLOTTED_SPACE_EXCEEDED ((NTSTATUS) 0xC0000099L)
+#endif
+
+#ifndef STATUS_INSUFFICIENT_RESOURCES
+# define STATUS_INSUFFICIENT_RESOURCES ((NTSTATUS) 0xC000009AL)
+#endif
+
+#ifndef STATUS_DFS_EXIT_PATH_FOUND
+# define STATUS_DFS_EXIT_PATH_FOUND ((NTSTATUS) 0xC000009BL)
+#endif
+
+#ifndef STATUS_DEVICE_DATA_ERROR
+# define STATUS_DEVICE_DATA_ERROR ((NTSTATUS) 0xC000009CL)
+#endif
+
+#ifndef STATUS_DEVICE_NOT_CONNECTED
+# define STATUS_DEVICE_NOT_CONNECTED ((NTSTATUS) 0xC000009DL)
+#endif
+
+#ifndef STATUS_DEVICE_POWER_FAILURE
+# define STATUS_DEVICE_POWER_FAILURE ((NTSTATUS) 0xC000009EL)
+#endif
+
+#ifndef STATUS_FREE_VM_NOT_AT_BASE
+# define STATUS_FREE_VM_NOT_AT_BASE ((NTSTATUS) 0xC000009FL)
+#endif
+
+#ifndef STATUS_MEMORY_NOT_ALLOCATED
+# define STATUS_MEMORY_NOT_ALLOCATED ((NTSTATUS) 0xC00000A0L)
+#endif
+
+#ifndef STATUS_WORKING_SET_QUOTA
+# define STATUS_WORKING_SET_QUOTA ((NTSTATUS) 0xC00000A1L)
+#endif
+
+#ifndef STATUS_MEDIA_WRITE_PROTECTED
+# define STATUS_MEDIA_WRITE_PROTECTED ((NTSTATUS) 0xC00000A2L)
+#endif
+
+#ifndef STATUS_DEVICE_NOT_READY
+# define STATUS_DEVICE_NOT_READY ((NTSTATUS) 0xC00000A3L)
+#endif
+
+#ifndef STATUS_INVALID_GROUP_ATTRIBUTES
+# define STATUS_INVALID_GROUP_ATTRIBUTES ((NTSTATUS) 0xC00000A4L)
+#endif
+
+#ifndef STATUS_BAD_IMPERSONATION_LEVEL
+# define STATUS_BAD_IMPERSONATION_LEVEL ((NTSTATUS) 0xC00000A5L)
+#endif
+
+#ifndef STATUS_CANT_OPEN_ANONYMOUS
+# define STATUS_CANT_OPEN_ANONYMOUS ((NTSTATUS) 0xC00000A6L)
+#endif
+
+#ifndef STATUS_BAD_VALIDATION_CLASS
+# define STATUS_BAD_VALIDATION_CLASS ((NTSTATUS) 0xC00000A7L)
+#endif
+
+#ifndef STATUS_BAD_TOKEN_TYPE
+# define STATUS_BAD_TOKEN_TYPE ((NTSTATUS) 0xC00000A8L)
+#endif
+
+#ifndef STATUS_BAD_MASTER_BOOT_RECORD
+# define STATUS_BAD_MASTER_BOOT_RECORD ((NTSTATUS) 0xC00000A9L)
+#endif
+
+#ifndef STATUS_INSTRUCTION_MISALIGNMENT
+# define STATUS_INSTRUCTION_MISALIGNMENT ((NTSTATUS) 0xC00000AAL)
+#endif
+
+#ifndef STATUS_INSTANCE_NOT_AVAILABLE
+# define STATUS_INSTANCE_NOT_AVAILABLE ((NTSTATUS) 0xC00000ABL)
+#endif
+
+#ifndef STATUS_PIPE_NOT_AVAILABLE
+# define STATUS_PIPE_NOT_AVAILABLE ((NTSTATUS) 0xC00000ACL)
+#endif
+
+#ifndef STATUS_INVALID_PIPE_STATE
+# define STATUS_INVALID_PIPE_STATE ((NTSTATUS) 0xC00000ADL)
+#endif
+
+#ifndef STATUS_PIPE_BUSY
+# define STATUS_PIPE_BUSY ((NTSTATUS) 0xC00000AEL)
+#endif
+
+#ifndef STATUS_ILLEGAL_FUNCTION
+# define STATUS_ILLEGAL_FUNCTION ((NTSTATUS) 0xC00000AFL)
+#endif
+
+#ifndef STATUS_PIPE_DISCONNECTED
+# define STATUS_PIPE_DISCONNECTED ((NTSTATUS) 0xC00000B0L)
+#endif
+
+#ifndef STATUS_PIPE_CLOSING
+# define STATUS_PIPE_CLOSING ((NTSTATUS) 0xC00000B1L)
+#endif
+
+#ifndef STATUS_PIPE_CONNECTED
+# define STATUS_PIPE_CONNECTED ((NTSTATUS) 0xC00000B2L)
+#endif
+
+#ifndef STATUS_PIPE_LISTENING
+# define STATUS_PIPE_LISTENING ((NTSTATUS) 0xC00000B3L)
+#endif
+
+#ifndef STATUS_INVALID_READ_MODE
+# define STATUS_INVALID_READ_MODE ((NTSTATUS) 0xC00000B4L)
+#endif
+
+#ifndef STATUS_IO_TIMEOUT
+# define STATUS_IO_TIMEOUT ((NTSTATUS) 0xC00000B5L)
+#endif
+
+#ifndef STATUS_FILE_FORCED_CLOSED
+# define STATUS_FILE_FORCED_CLOSED ((NTSTATUS) 0xC00000B6L)
+#endif
+
+#ifndef STATUS_PROFILING_NOT_STARTED
+# define STATUS_PROFILING_NOT_STARTED ((NTSTATUS) 0xC00000B7L)
+#endif
+
+#ifndef STATUS_PROFILING_NOT_STOPPED
+# define STATUS_PROFILING_NOT_STOPPED ((NTSTATUS) 0xC00000B8L)
+#endif
+
+#ifndef STATUS_COULD_NOT_INTERPRET
+# define STATUS_COULD_NOT_INTERPRET ((NTSTATUS) 0xC00000B9L)
+#endif
+
+#ifndef STATUS_FILE_IS_A_DIRECTORY
+# define STATUS_FILE_IS_A_DIRECTORY ((NTSTATUS) 0xC00000BAL)
+#endif
+
+#ifndef STATUS_NOT_SUPPORTED
+# define STATUS_NOT_SUPPORTED ((NTSTATUS) 0xC00000BBL)
+#endif
+
+#ifndef STATUS_REMOTE_NOT_LISTENING
+# define STATUS_REMOTE_NOT_LISTENING ((NTSTATUS) 0xC00000BCL)
+#endif
+
+#ifndef STATUS_DUPLICATE_NAME
+# define STATUS_DUPLICATE_NAME ((NTSTATUS) 0xC00000BDL)
+#endif
+
+#ifndef STATUS_BAD_NETWORK_PATH
+# define STATUS_BAD_NETWORK_PATH ((NTSTATUS) 0xC00000BEL)
+#endif
+
+#ifndef STATUS_NETWORK_BUSY
+# define STATUS_NETWORK_BUSY ((NTSTATUS) 0xC00000BFL)
+#endif
+
+#ifndef STATUS_DEVICE_DOES_NOT_EXIST
+# define STATUS_DEVICE_DOES_NOT_EXIST ((NTSTATUS) 0xC00000C0L)
+#endif
+
+#ifndef STATUS_TOO_MANY_COMMANDS
+# define STATUS_TOO_MANY_COMMANDS ((NTSTATUS) 0xC00000C1L)
+#endif
+
+#ifndef STATUS_ADAPTER_HARDWARE_ERROR
+# define STATUS_ADAPTER_HARDWARE_ERROR ((NTSTATUS) 0xC00000C2L)
+#endif
+
+#ifndef STATUS_INVALID_NETWORK_RESPONSE
+# define STATUS_INVALID_NETWORK_RESPONSE ((NTSTATUS) 0xC00000C3L)
+#endif
+
+#ifndef STATUS_UNEXPECTED_NETWORK_ERROR
+# define STATUS_UNEXPECTED_NETWORK_ERROR ((NTSTATUS) 0xC00000C4L)
+#endif
+
+#ifndef STATUS_BAD_REMOTE_ADAPTER
+# define STATUS_BAD_REMOTE_ADAPTER ((NTSTATUS) 0xC00000C5L)
+#endif
+
+#ifndef STATUS_PRINT_QUEUE_FULL
+# define STATUS_PRINT_QUEUE_FULL ((NTSTATUS) 0xC00000C6L)
+#endif
+
+#ifndef STATUS_NO_SPOOL_SPACE
+# define STATUS_NO_SPOOL_SPACE ((NTSTATUS) 0xC00000C7L)
+#endif
+
+#ifndef STATUS_PRINT_CANCELLED
+# define STATUS_PRINT_CANCELLED ((NTSTATUS) 0xC00000C8L)
+#endif
+
+#ifndef STATUS_NETWORK_NAME_DELETED
+# define STATUS_NETWORK_NAME_DELETED ((NTSTATUS) 0xC00000C9L)
+#endif
+
+#ifndef STATUS_NETWORK_ACCESS_DENIED
+# define STATUS_NETWORK_ACCESS_DENIED ((NTSTATUS) 0xC00000CAL)
+#endif
+
+#ifndef STATUS_BAD_DEVICE_TYPE
+# define STATUS_BAD_DEVICE_TYPE ((NTSTATUS) 0xC00000CBL)
+#endif
+
+#ifndef STATUS_BAD_NETWORK_NAME
+# define STATUS_BAD_NETWORK_NAME ((NTSTATUS) 0xC00000CCL)
+#endif
+
+#ifndef STATUS_TOO_MANY_NAMES
+# define STATUS_TOO_MANY_NAMES ((NTSTATUS) 0xC00000CDL)
+#endif
+
+#ifndef STATUS_TOO_MANY_SESSIONS
+# define STATUS_TOO_MANY_SESSIONS ((NTSTATUS) 0xC00000CEL)
+#endif
+
+#ifndef STATUS_SHARING_PAUSED
+# define STATUS_SHARING_PAUSED ((NTSTATUS) 0xC00000CFL)
+#endif
+
+#ifndef STATUS_REQUEST_NOT_ACCEPTED
+# define STATUS_REQUEST_NOT_ACCEPTED ((NTSTATUS) 0xC00000D0L)
+#endif
+
+#ifndef STATUS_REDIRECTOR_PAUSED
+# define STATUS_REDIRECTOR_PAUSED ((NTSTATUS) 0xC00000D1L)
+#endif
+
+#ifndef STATUS_NET_WRITE_FAULT
+# define STATUS_NET_WRITE_FAULT ((NTSTATUS) 0xC00000D2L)
+#endif
+
+#ifndef STATUS_PROFILING_AT_LIMIT
+# define STATUS_PROFILING_AT_LIMIT ((NTSTATUS) 0xC00000D3L)
+#endif
+
+#ifndef STATUS_NOT_SAME_DEVICE
+# define STATUS_NOT_SAME_DEVICE ((NTSTATUS) 0xC00000D4L)
+#endif
+
+#ifndef STATUS_FILE_RENAMED
+# define STATUS_FILE_RENAMED ((NTSTATUS) 0xC00000D5L)
+#endif
+
+#ifndef STATUS_VIRTUAL_CIRCUIT_CLOSED
+# define STATUS_VIRTUAL_CIRCUIT_CLOSED ((NTSTATUS) 0xC00000D6L)
+#endif
+
+#ifndef STATUS_NO_SECURITY_ON_OBJECT
+# define STATUS_NO_SECURITY_ON_OBJECT ((NTSTATUS) 0xC00000D7L)
+#endif
+
+#ifndef STATUS_CANT_WAIT
+# define STATUS_CANT_WAIT ((NTSTATUS) 0xC00000D8L)
+#endif
+
+#ifndef STATUS_PIPE_EMPTY
+# define STATUS_PIPE_EMPTY ((NTSTATUS) 0xC00000D9L)
+#endif
+
+#ifndef STATUS_CANT_ACCESS_DOMAIN_INFO
+# define STATUS_CANT_ACCESS_DOMAIN_INFO ((NTSTATUS) 0xC00000DAL)
+#endif
+
+#ifndef STATUS_CANT_TERMINATE_SELF
+# define STATUS_CANT_TERMINATE_SELF ((NTSTATUS) 0xC00000DBL)
+#endif
+
+#ifndef STATUS_INVALID_SERVER_STATE
+# define STATUS_INVALID_SERVER_STATE ((NTSTATUS) 0xC00000DCL)
+#endif
+
+#ifndef STATUS_INVALID_DOMAIN_STATE
+# define STATUS_INVALID_DOMAIN_STATE ((NTSTATUS) 0xC00000DDL)
+#endif
+
+#ifndef STATUS_INVALID_DOMAIN_ROLE
+# define STATUS_INVALID_DOMAIN_ROLE ((NTSTATUS) 0xC00000DEL)
+#endif
+
+#ifndef STATUS_NO_SUCH_DOMAIN
+# define STATUS_NO_SUCH_DOMAIN ((NTSTATUS) 0xC00000DFL)
+#endif
+
+#ifndef STATUS_DOMAIN_EXISTS
+# define STATUS_DOMAIN_EXISTS ((NTSTATUS) 0xC00000E0L)
+#endif
+
+#ifndef STATUS_DOMAIN_LIMIT_EXCEEDED
+# define STATUS_DOMAIN_LIMIT_EXCEEDED ((NTSTATUS) 0xC00000E1L)
+#endif
+
+#ifndef STATUS_OPLOCK_NOT_GRANTED
+# define STATUS_OPLOCK_NOT_GRANTED ((NTSTATUS) 0xC00000E2L)
+#endif
+
+#ifndef STATUS_INVALID_OPLOCK_PROTOCOL
+# define STATUS_INVALID_OPLOCK_PROTOCOL ((NTSTATUS) 0xC00000E3L)
+#endif
+
+#ifndef STATUS_INTERNAL_DB_CORRUPTION
+# define STATUS_INTERNAL_DB_CORRUPTION ((NTSTATUS) 0xC00000E4L)
+#endif
+
+#ifndef STATUS_INTERNAL_ERROR
+# define STATUS_INTERNAL_ERROR ((NTSTATUS) 0xC00000E5L)
+#endif
+
+#ifndef STATUS_GENERIC_NOT_MAPPED
+# define STATUS_GENERIC_NOT_MAPPED ((NTSTATUS) 0xC00000E6L)
+#endif
+
+#ifndef STATUS_BAD_DESCRIPTOR_FORMAT
+# define STATUS_BAD_DESCRIPTOR_FORMAT ((NTSTATUS) 0xC00000E7L)
+#endif
+
+#ifndef STATUS_INVALID_USER_BUFFER
+# define STATUS_INVALID_USER_BUFFER ((NTSTATUS) 0xC00000E8L)
+#endif
+
+#ifndef STATUS_UNEXPECTED_IO_ERROR
+# define STATUS_UNEXPECTED_IO_ERROR ((NTSTATUS) 0xC00000E9L)
+#endif
+
+#ifndef STATUS_UNEXPECTED_MM_CREATE_ERR
+# define STATUS_UNEXPECTED_MM_CREATE_ERR ((NTSTATUS) 0xC00000EAL)
+#endif
+
+#ifndef STATUS_UNEXPECTED_MM_MAP_ERROR
+# define STATUS_UNEXPECTED_MM_MAP_ERROR ((NTSTATUS) 0xC00000EBL)
+#endif
+
+#ifndef STATUS_UNEXPECTED_MM_EXTEND_ERR
+# define STATUS_UNEXPECTED_MM_EXTEND_ERR ((NTSTATUS) 0xC00000ECL)
+#endif
+
+#ifndef STATUS_NOT_LOGON_PROCESS
+# define STATUS_NOT_LOGON_PROCESS ((NTSTATUS) 0xC00000EDL)
+#endif
+
+#ifndef STATUS_LOGON_SESSION_EXISTS
+# define STATUS_LOGON_SESSION_EXISTS ((NTSTATUS) 0xC00000EEL)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_1
+# define STATUS_INVALID_PARAMETER_1 ((NTSTATUS) 0xC00000EFL)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_2
+# define STATUS_INVALID_PARAMETER_2 ((NTSTATUS) 0xC00000F0L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_3
+# define STATUS_INVALID_PARAMETER_3 ((NTSTATUS) 0xC00000F1L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_4
+# define STATUS_INVALID_PARAMETER_4 ((NTSTATUS) 0xC00000F2L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_5
+# define STATUS_INVALID_PARAMETER_5 ((NTSTATUS) 0xC00000F3L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_6
+# define STATUS_INVALID_PARAMETER_6 ((NTSTATUS) 0xC00000F4L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_7
+# define STATUS_INVALID_PARAMETER_7 ((NTSTATUS) 0xC00000F5L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_8
+# define STATUS_INVALID_PARAMETER_8 ((NTSTATUS) 0xC00000F6L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_9
+# define STATUS_INVALID_PARAMETER_9 ((NTSTATUS) 0xC00000F7L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_10
+# define STATUS_INVALID_PARAMETER_10 ((NTSTATUS) 0xC00000F8L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_11
+# define STATUS_INVALID_PARAMETER_11 ((NTSTATUS) 0xC00000F9L)
+#endif
+
+#ifndef STATUS_INVALID_PARAMETER_12
+# define STATUS_INVALID_PARAMETER_12 ((NTSTATUS) 0xC00000FAL)
+#endif
+
+#ifndef STATUS_REDIRECTOR_NOT_STARTED
+# define STATUS_REDIRECTOR_NOT_STARTED ((NTSTATUS) 0xC00000FBL)
+#endif
+
+#ifndef STATUS_REDIRECTOR_STARTED
+# define STATUS_REDIRECTOR_STARTED ((NTSTATUS) 0xC00000FCL)
+#endif
+
+#ifndef STATUS_STACK_OVERFLOW
+# define STATUS_STACK_OVERFLOW ((NTSTATUS) 0xC00000FDL)
+#endif
+
+#ifndef STATUS_NO_SUCH_PACKAGE
+# define STATUS_NO_SUCH_PACKAGE ((NTSTATUS) 0xC00000FEL)
+#endif
+
+#ifndef STATUS_BAD_FUNCTION_TABLE
+# define STATUS_BAD_FUNCTION_TABLE ((NTSTATUS) 0xC00000FFL)
+#endif
+
+#ifndef STATUS_VARIABLE_NOT_FOUND
+# define STATUS_VARIABLE_NOT_FOUND ((NTSTATUS) 0xC0000100L)
+#endif
+
+#ifndef STATUS_DIRECTORY_NOT_EMPTY
+# define STATUS_DIRECTORY_NOT_EMPTY ((NTSTATUS) 0xC0000101L)
+#endif
+
+#ifndef STATUS_FILE_CORRUPT_ERROR
+# define STATUS_FILE_CORRUPT_ERROR ((NTSTATUS) 0xC0000102L)
+#endif
+
+#ifndef STATUS_NOT_A_DIRECTORY
+# define STATUS_NOT_A_DIRECTORY ((NTSTATUS) 0xC0000103L)
+#endif
+
+#ifndef STATUS_BAD_LOGON_SESSION_STATE
+# define STATUS_BAD_LOGON_SESSION_STATE ((NTSTATUS) 0xC0000104L)
+#endif
+
+#ifndef STATUS_LOGON_SESSION_COLLISION
+# define STATUS_LOGON_SESSION_COLLISION ((NTSTATUS) 0xC0000105L)
+#endif
+
+#ifndef STATUS_NAME_TOO_LONG
+# define STATUS_NAME_TOO_LONG ((NTSTATUS) 0xC0000106L)
+#endif
+
+#ifndef STATUS_FILES_OPEN
+# define STATUS_FILES_OPEN ((NTSTATUS) 0xC0000107L)
+#endif
+
+#ifndef STATUS_CONNECTION_IN_USE
+# define STATUS_CONNECTION_IN_USE ((NTSTATUS) 0xC0000108L)
+#endif
+
+#ifndef STATUS_MESSAGE_NOT_FOUND
+# define STATUS_MESSAGE_NOT_FOUND ((NTSTATUS) 0xC0000109L)
+#endif
+
+#ifndef STATUS_PROCESS_IS_TERMINATING
+# define STATUS_PROCESS_IS_TERMINATING ((NTSTATUS) 0xC000010AL)
+#endif
+
+#ifndef STATUS_INVALID_LOGON_TYPE
+# define STATUS_INVALID_LOGON_TYPE ((NTSTATUS) 0xC000010BL)
+#endif
+
+#ifndef STATUS_NO_GUID_TRANSLATION
+# define STATUS_NO_GUID_TRANSLATION ((NTSTATUS) 0xC000010CL)
+#endif
+
+#ifndef STATUS_CANNOT_IMPERSONATE
+# define STATUS_CANNOT_IMPERSONATE ((NTSTATUS) 0xC000010DL)
+#endif
+
+#ifndef STATUS_IMAGE_ALREADY_LOADED
+# define STATUS_IMAGE_ALREADY_LOADED ((NTSTATUS) 0xC000010EL)
+#endif
+
+#ifndef STATUS_ABIOS_NOT_PRESENT
+# define STATUS_ABIOS_NOT_PRESENT ((NTSTATUS) 0xC000010FL)
+#endif
+
+#ifndef STATUS_ABIOS_LID_NOT_EXIST
+# define STATUS_ABIOS_LID_NOT_EXIST ((NTSTATUS) 0xC0000110L)
+#endif
+
+#ifndef STATUS_ABIOS_LID_ALREADY_OWNED
+# define STATUS_ABIOS_LID_ALREADY_OWNED ((NTSTATUS) 0xC0000111L)
+#endif
+
+#ifndef STATUS_ABIOS_NOT_LID_OWNER
+# define STATUS_ABIOS_NOT_LID_OWNER ((NTSTATUS) 0xC0000112L)
+#endif
+
+#ifndef STATUS_ABIOS_INVALID_COMMAND
+# define STATUS_ABIOS_INVALID_COMMAND ((NTSTATUS) 0xC0000113L)
+#endif
+
+#ifndef STATUS_ABIOS_INVALID_LID
+# define STATUS_ABIOS_INVALID_LID ((NTSTATUS) 0xC0000114L)
+#endif
+
+#ifndef STATUS_ABIOS_SELECTOR_NOT_AVAILABLE
+# define STATUS_ABIOS_SELECTOR_NOT_AVAILABLE ((NTSTATUS) 0xC0000115L)
+#endif
+
+#ifndef STATUS_ABIOS_INVALID_SELECTOR
+# define STATUS_ABIOS_INVALID_SELECTOR ((NTSTATUS) 0xC0000116L)
+#endif
+
+#ifndef STATUS_NO_LDT
+# define STATUS_NO_LDT ((NTSTATUS) 0xC0000117L)
+#endif
+
+#ifndef STATUS_INVALID_LDT_SIZE
+# define STATUS_INVALID_LDT_SIZE ((NTSTATUS) 0xC0000118L)
+#endif
+
+#ifndef STATUS_INVALID_LDT_OFFSET
+# define STATUS_INVALID_LDT_OFFSET ((NTSTATUS) 0xC0000119L)
+#endif
+
+#ifndef STATUS_INVALID_LDT_DESCRIPTOR
+# define STATUS_INVALID_LDT_DESCRIPTOR ((NTSTATUS) 0xC000011AL)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_NE_FORMAT
+# define STATUS_INVALID_IMAGE_NE_FORMAT ((NTSTATUS) 0xC000011BL)
+#endif
+
+#ifndef STATUS_RXACT_INVALID_STATE
+# define STATUS_RXACT_INVALID_STATE ((NTSTATUS) 0xC000011CL)
+#endif
+
+#ifndef STATUS_RXACT_COMMIT_FAILURE
+# define STATUS_RXACT_COMMIT_FAILURE ((NTSTATUS) 0xC000011DL)
+#endif
+
+#ifndef STATUS_MAPPED_FILE_SIZE_ZERO
+# define STATUS_MAPPED_FILE_SIZE_ZERO ((NTSTATUS) 0xC000011EL)
+#endif
+
+#ifndef STATUS_TOO_MANY_OPENED_FILES
+# define STATUS_TOO_MANY_OPENED_FILES ((NTSTATUS) 0xC000011FL)
+#endif
+
+#ifndef STATUS_CANCELLED
+# define STATUS_CANCELLED ((NTSTATUS) 0xC0000120L)
+#endif
+
+#ifndef STATUS_CANNOT_DELETE
+# define STATUS_CANNOT_DELETE ((NTSTATUS) 0xC0000121L)
+#endif
+
+#ifndef STATUS_INVALID_COMPUTER_NAME
+# define STATUS_INVALID_COMPUTER_NAME ((NTSTATUS) 0xC0000122L)
+#endif
+
+#ifndef STATUS_FILE_DELETED
+# define STATUS_FILE_DELETED ((NTSTATUS) 0xC0000123L)
+#endif
+
+#ifndef STATUS_SPECIAL_ACCOUNT
+# define STATUS_SPECIAL_ACCOUNT ((NTSTATUS) 0xC0000124L)
+#endif
+
+#ifndef STATUS_SPECIAL_GROUP
+# define STATUS_SPECIAL_GROUP ((NTSTATUS) 0xC0000125L)
+#endif
+
+#ifndef STATUS_SPECIAL_USER
+# define STATUS_SPECIAL_USER ((NTSTATUS) 0xC0000126L)
+#endif
+
+#ifndef STATUS_MEMBERS_PRIMARY_GROUP
+# define STATUS_MEMBERS_PRIMARY_GROUP ((NTSTATUS) 0xC0000127L)
+#endif
+
+#ifndef STATUS_FILE_CLOSED
+# define STATUS_FILE_CLOSED ((NTSTATUS) 0xC0000128L)
+#endif
+
+#ifndef STATUS_TOO_MANY_THREADS
+# define STATUS_TOO_MANY_THREADS ((NTSTATUS) 0xC0000129L)
+#endif
+
+#ifndef STATUS_THREAD_NOT_IN_PROCESS
+# define STATUS_THREAD_NOT_IN_PROCESS ((NTSTATUS) 0xC000012AL)
+#endif
+
+#ifndef STATUS_TOKEN_ALREADY_IN_USE
+# define STATUS_TOKEN_ALREADY_IN_USE ((NTSTATUS) 0xC000012BL)
+#endif
+
+#ifndef STATUS_PAGEFILE_QUOTA_EXCEEDED
+# define STATUS_PAGEFILE_QUOTA_EXCEEDED ((NTSTATUS) 0xC000012CL)
+#endif
+
+#ifndef STATUS_COMMITMENT_LIMIT
+# define STATUS_COMMITMENT_LIMIT ((NTSTATUS) 0xC000012DL)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_LE_FORMAT
+# define STATUS_INVALID_IMAGE_LE_FORMAT ((NTSTATUS) 0xC000012EL)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_NOT_MZ
+# define STATUS_INVALID_IMAGE_NOT_MZ ((NTSTATUS) 0xC000012FL)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_PROTECT
+# define STATUS_INVALID_IMAGE_PROTECT ((NTSTATUS) 0xC0000130L)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_WIN_16
+# define STATUS_INVALID_IMAGE_WIN_16 ((NTSTATUS) 0xC0000131L)
+#endif
+
+#ifndef STATUS_LOGON_SERVER_CONFLICT
+# define STATUS_LOGON_SERVER_CONFLICT ((NTSTATUS) 0xC0000132L)
+#endif
+
+#ifndef STATUS_TIME_DIFFERENCE_AT_DC
+# define STATUS_TIME_DIFFERENCE_AT_DC ((NTSTATUS) 0xC0000133L)
+#endif
+
+#ifndef STATUS_SYNCHRONIZATION_REQUIRED
+# define STATUS_SYNCHRONIZATION_REQUIRED ((NTSTATUS) 0xC0000134L)
+#endif
+
+#ifndef STATUS_DLL_NOT_FOUND
+# define STATUS_DLL_NOT_FOUND ((NTSTATUS) 0xC0000135L)
+#endif
+
+#ifndef STATUS_OPEN_FAILED
+# define STATUS_OPEN_FAILED ((NTSTATUS) 0xC0000136L)
+#endif
+
+#ifndef STATUS_IO_PRIVILEGE_FAILED
+# define STATUS_IO_PRIVILEGE_FAILED ((NTSTATUS) 0xC0000137L)
+#endif
+
+#ifndef STATUS_ORDINAL_NOT_FOUND
+# define STATUS_ORDINAL_NOT_FOUND ((NTSTATUS) 0xC0000138L)
+#endif
+
+#ifndef STATUS_ENTRYPOINT_NOT_FOUND
+# define STATUS_ENTRYPOINT_NOT_FOUND ((NTSTATUS) 0xC0000139L)
+#endif
+
+#ifndef STATUS_CONTROL_C_EXIT
+# define STATUS_CONTROL_C_EXIT ((NTSTATUS) 0xC000013AL)
+#endif
+
+#ifndef STATUS_LOCAL_DISCONNECT
+# define STATUS_LOCAL_DISCONNECT ((NTSTATUS) 0xC000013BL)
+#endif
+
+#ifndef STATUS_REMOTE_DISCONNECT
+# define STATUS_REMOTE_DISCONNECT ((NTSTATUS) 0xC000013CL)
+#endif
+
+#ifndef STATUS_REMOTE_RESOURCES
+# define STATUS_REMOTE_RESOURCES ((NTSTATUS) 0xC000013DL)
+#endif
+
+#ifndef STATUS_LINK_FAILED
+# define STATUS_LINK_FAILED ((NTSTATUS) 0xC000013EL)
+#endif
+
+#ifndef STATUS_LINK_TIMEOUT
+# define STATUS_LINK_TIMEOUT ((NTSTATUS) 0xC000013FL)
+#endif
+
+#ifndef STATUS_INVALID_CONNECTION
+# define STATUS_INVALID_CONNECTION ((NTSTATUS) 0xC0000140L)
+#endif
+
+#ifndef STATUS_INVALID_ADDRESS
+# define STATUS_INVALID_ADDRESS ((NTSTATUS) 0xC0000141L)
+#endif
+
+#ifndef STATUS_DLL_INIT_FAILED
+# define STATUS_DLL_INIT_FAILED ((NTSTATUS) 0xC0000142L)
+#endif
+
+#ifndef STATUS_MISSING_SYSTEMFILE
+# define STATUS_MISSING_SYSTEMFILE ((NTSTATUS) 0xC0000143L)
+#endif
+
+#ifndef STATUS_UNHANDLED_EXCEPTION
+# define STATUS_UNHANDLED_EXCEPTION ((NTSTATUS) 0xC0000144L)
+#endif
+
+#ifndef STATUS_APP_INIT_FAILURE
+# define STATUS_APP_INIT_FAILURE ((NTSTATUS) 0xC0000145L)
+#endif
+
+#ifndef STATUS_PAGEFILE_CREATE_FAILED
+# define STATUS_PAGEFILE_CREATE_FAILED ((NTSTATUS) 0xC0000146L)
+#endif
+
+#ifndef STATUS_NO_PAGEFILE
+# define STATUS_NO_PAGEFILE ((NTSTATUS) 0xC0000147L)
+#endif
+
+#ifndef STATUS_INVALID_LEVEL
+# define STATUS_INVALID_LEVEL ((NTSTATUS) 0xC0000148L)
+#endif
+
+#ifndef STATUS_WRONG_PASSWORD_CORE
+# define STATUS_WRONG_PASSWORD_CORE ((NTSTATUS) 0xC0000149L)
+#endif
+
+#ifndef STATUS_ILLEGAL_FLOAT_CONTEXT
+# define STATUS_ILLEGAL_FLOAT_CONTEXT ((NTSTATUS) 0xC000014AL)
+#endif
+
+#ifndef STATUS_PIPE_BROKEN
+# define STATUS_PIPE_BROKEN ((NTSTATUS) 0xC000014BL)
+#endif
+
+#ifndef STATUS_REGISTRY_CORRUPT
+# define STATUS_REGISTRY_CORRUPT ((NTSTATUS) 0xC000014CL)
+#endif
+
+#ifndef STATUS_REGISTRY_IO_FAILED
+# define STATUS_REGISTRY_IO_FAILED ((NTSTATUS) 0xC000014DL)
+#endif
+
+#ifndef STATUS_NO_EVENT_PAIR
+# define STATUS_NO_EVENT_PAIR ((NTSTATUS) 0xC000014EL)
+#endif
+
+#ifndef STATUS_UNRECOGNIZED_VOLUME
+# define STATUS_UNRECOGNIZED_VOLUME ((NTSTATUS) 0xC000014FL)
+#endif
+
+#ifndef STATUS_SERIAL_NO_DEVICE_INITED
+# define STATUS_SERIAL_NO_DEVICE_INITED ((NTSTATUS) 0xC0000150L)
+#endif
+
+#ifndef STATUS_NO_SUCH_ALIAS
+# define STATUS_NO_SUCH_ALIAS ((NTSTATUS) 0xC0000151L)
+#endif
+
+#ifndef STATUS_MEMBER_NOT_IN_ALIAS
+# define STATUS_MEMBER_NOT_IN_ALIAS ((NTSTATUS) 0xC0000152L)
+#endif
+
+#ifndef STATUS_MEMBER_IN_ALIAS
+# define STATUS_MEMBER_IN_ALIAS ((NTSTATUS) 0xC0000153L)
+#endif
+
+#ifndef STATUS_ALIAS_EXISTS
+# define STATUS_ALIAS_EXISTS ((NTSTATUS) 0xC0000154L)
+#endif
+
+#ifndef STATUS_LOGON_NOT_GRANTED
+# define STATUS_LOGON_NOT_GRANTED ((NTSTATUS) 0xC0000155L)
+#endif
+
+#ifndef STATUS_TOO_MANY_SECRETS
+# define STATUS_TOO_MANY_SECRETS ((NTSTATUS) 0xC0000156L)
+#endif
+
+#ifndef STATUS_SECRET_TOO_LONG
+# define STATUS_SECRET_TOO_LONG ((NTSTATUS) 0xC0000157L)
+#endif
+
+#ifndef STATUS_INTERNAL_DB_ERROR
+# define STATUS_INTERNAL_DB_ERROR ((NTSTATUS) 0xC0000158L)
+#endif
+
+#ifndef STATUS_FULLSCREEN_MODE
+# define STATUS_FULLSCREEN_MODE ((NTSTATUS) 0xC0000159L)
+#endif
+
+#ifndef STATUS_TOO_MANY_CONTEXT_IDS
+# define STATUS_TOO_MANY_CONTEXT_IDS ((NTSTATUS) 0xC000015AL)
+#endif
+
+#ifndef STATUS_LOGON_TYPE_NOT_GRANTED
+# define STATUS_LOGON_TYPE_NOT_GRANTED ((NTSTATUS) 0xC000015BL)
+#endif
+
+#ifndef STATUS_NOT_REGISTRY_FILE
+# define STATUS_NOT_REGISTRY_FILE ((NTSTATUS) 0xC000015CL)
+#endif
+
+#ifndef STATUS_NT_CROSS_ENCRYPTION_REQUIRED
+# define STATUS_NT_CROSS_ENCRYPTION_REQUIRED ((NTSTATUS) 0xC000015DL)
+#endif
+
+#ifndef STATUS_DOMAIN_CTRLR_CONFIG_ERROR
+# define STATUS_DOMAIN_CTRLR_CONFIG_ERROR ((NTSTATUS) 0xC000015EL)
+#endif
+
+#ifndef STATUS_FT_MISSING_MEMBER
+# define STATUS_FT_MISSING_MEMBER ((NTSTATUS) 0xC000015FL)
+#endif
+
+#ifndef STATUS_ILL_FORMED_SERVICE_ENTRY
+# define STATUS_ILL_FORMED_SERVICE_ENTRY ((NTSTATUS) 0xC0000160L)
+#endif
+
+#ifndef STATUS_ILLEGAL_CHARACTER
+# define STATUS_ILLEGAL_CHARACTER ((NTSTATUS) 0xC0000161L)
+#endif
+
+#ifndef STATUS_UNMAPPABLE_CHARACTER
+# define STATUS_UNMAPPABLE_CHARACTER ((NTSTATUS) 0xC0000162L)
+#endif
+
+#ifndef STATUS_UNDEFINED_CHARACTER
+# define STATUS_UNDEFINED_CHARACTER ((NTSTATUS) 0xC0000163L)
+#endif
+
+#ifndef STATUS_FLOPPY_VOLUME
+# define STATUS_FLOPPY_VOLUME ((NTSTATUS) 0xC0000164L)
+#endif
+
+#ifndef STATUS_FLOPPY_ID_MARK_NOT_FOUND
+# define STATUS_FLOPPY_ID_MARK_NOT_FOUND ((NTSTATUS) 0xC0000165L)
+#endif
+
+#ifndef STATUS_FLOPPY_WRONG_CYLINDER
+# define STATUS_FLOPPY_WRONG_CYLINDER ((NTSTATUS) 0xC0000166L)
+#endif
+
+#ifndef STATUS_FLOPPY_UNKNOWN_ERROR
+# define STATUS_FLOPPY_UNKNOWN_ERROR ((NTSTATUS) 0xC0000167L)
+#endif
+
+#ifndef STATUS_FLOPPY_BAD_REGISTERS
+# define STATUS_FLOPPY_BAD_REGISTERS ((NTSTATUS) 0xC0000168L)
+#endif
+
+#ifndef STATUS_DISK_RECALIBRATE_FAILED
+# define STATUS_DISK_RECALIBRATE_FAILED ((NTSTATUS) 0xC0000169L)
+#endif
+
+#ifndef STATUS_DISK_OPERATION_FAILED
+# define STATUS_DISK_OPERATION_FAILED ((NTSTATUS) 0xC000016AL)
+#endif
+
+#ifndef STATUS_DISK_RESET_FAILED
+# define STATUS_DISK_RESET_FAILED ((NTSTATUS) 0xC000016BL)
+#endif
+
+#ifndef STATUS_SHARED_IRQ_BUSY
+# define STATUS_SHARED_IRQ_BUSY ((NTSTATUS) 0xC000016CL)
+#endif
+
+#ifndef STATUS_FT_ORPHANING
+# define STATUS_FT_ORPHANING ((NTSTATUS) 0xC000016DL)
+#endif
+
+#ifndef STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT
+# define STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT ((NTSTATUS) 0xC000016EL)
+#endif
+
+#ifndef STATUS_PARTITION_FAILURE
+# define STATUS_PARTITION_FAILURE ((NTSTATUS) 0xC0000172L)
+#endif
+
+#ifndef STATUS_INVALID_BLOCK_LENGTH
+# define STATUS_INVALID_BLOCK_LENGTH ((NTSTATUS) 0xC0000173L)
+#endif
+
+#ifndef STATUS_DEVICE_NOT_PARTITIONED
+# define STATUS_DEVICE_NOT_PARTITIONED ((NTSTATUS) 0xC0000174L)
+#endif
+
+#ifndef STATUS_UNABLE_TO_LOCK_MEDIA
+# define STATUS_UNABLE_TO_LOCK_MEDIA ((NTSTATUS) 0xC0000175L)
+#endif
+
+#ifndef STATUS_UNABLE_TO_UNLOAD_MEDIA
+# define STATUS_UNABLE_TO_UNLOAD_MEDIA ((NTSTATUS) 0xC0000176L)
+#endif
+
+#ifndef STATUS_EOM_OVERFLOW
+# define STATUS_EOM_OVERFLOW ((NTSTATUS) 0xC0000177L)
+#endif
+
+#ifndef STATUS_NO_MEDIA
+# define STATUS_NO_MEDIA ((NTSTATUS) 0xC0000178L)
+#endif
+
+#ifndef STATUS_NO_SUCH_MEMBER
+# define STATUS_NO_SUCH_MEMBER ((NTSTATUS) 0xC000017AL)
+#endif
+
+#ifndef STATUS_INVALID_MEMBER
+# define STATUS_INVALID_MEMBER ((NTSTATUS) 0xC000017BL)
+#endif
+
+#ifndef STATUS_KEY_DELETED
+# define STATUS_KEY_DELETED ((NTSTATUS) 0xC000017CL)
+#endif
+
+#ifndef STATUS_NO_LOG_SPACE
+# define STATUS_NO_LOG_SPACE ((NTSTATUS) 0xC000017DL)
+#endif
+
+#ifndef STATUS_TOO_MANY_SIDS
+# define STATUS_TOO_MANY_SIDS ((NTSTATUS) 0xC000017EL)
+#endif
+
+#ifndef STATUS_LM_CROSS_ENCRYPTION_REQUIRED
+# define STATUS_LM_CROSS_ENCRYPTION_REQUIRED ((NTSTATUS) 0xC000017FL)
+#endif
+
+#ifndef STATUS_KEY_HAS_CHILDREN
+# define STATUS_KEY_HAS_CHILDREN ((NTSTATUS) 0xC0000180L)
+#endif
+
+#ifndef STATUS_CHILD_MUST_BE_VOLATILE
+# define STATUS_CHILD_MUST_BE_VOLATILE ((NTSTATUS) 0xC0000181L)
+#endif
+
+#ifndef STATUS_DEVICE_CONFIGURATION_ERROR
+# define STATUS_DEVICE_CONFIGURATION_ERROR ((NTSTATUS) 0xC0000182L)
+#endif
+
+#ifndef STATUS_DRIVER_INTERNAL_ERROR
+# define STATUS_DRIVER_INTERNAL_ERROR ((NTSTATUS) 0xC0000183L)
+#endif
+
+#ifndef STATUS_INVALID_DEVICE_STATE
+# define STATUS_INVALID_DEVICE_STATE ((NTSTATUS) 0xC0000184L)
+#endif
+
+#ifndef STATUS_IO_DEVICE_ERROR
+# define STATUS_IO_DEVICE_ERROR ((NTSTATUS) 0xC0000185L)
+#endif
+
+#ifndef STATUS_DEVICE_PROTOCOL_ERROR
+# define STATUS_DEVICE_PROTOCOL_ERROR ((NTSTATUS) 0xC0000186L)
+#endif
+
+#ifndef STATUS_BACKUP_CONTROLLER
+# define STATUS_BACKUP_CONTROLLER ((NTSTATUS) 0xC0000187L)
+#endif
+
+#ifndef STATUS_LOG_FILE_FULL
+# define STATUS_LOG_FILE_FULL ((NTSTATUS) 0xC0000188L)
+#endif
+
+#ifndef STATUS_TOO_LATE
+# define STATUS_TOO_LATE ((NTSTATUS) 0xC0000189L)
+#endif
+
+#ifndef STATUS_NO_TRUST_LSA_SECRET
+# define STATUS_NO_TRUST_LSA_SECRET ((NTSTATUS) 0xC000018AL)
+#endif
+
+#ifndef STATUS_NO_TRUST_SAM_ACCOUNT
+# define STATUS_NO_TRUST_SAM_ACCOUNT ((NTSTATUS) 0xC000018BL)
+#endif
+
+#ifndef STATUS_TRUSTED_DOMAIN_FAILURE
+# define STATUS_TRUSTED_DOMAIN_FAILURE ((NTSTATUS) 0xC000018CL)
+#endif
+
+#ifndef STATUS_TRUSTED_RELATIONSHIP_FAILURE
+# define STATUS_TRUSTED_RELATIONSHIP_FAILURE ((NTSTATUS) 0xC000018DL)
+#endif
+
+#ifndef STATUS_EVENTLOG_FILE_CORRUPT
+# define STATUS_EVENTLOG_FILE_CORRUPT ((NTSTATUS) 0xC000018EL)
+#endif
+
+#ifndef STATUS_EVENTLOG_CANT_START
+# define STATUS_EVENTLOG_CANT_START ((NTSTATUS) 0xC000018FL)
+#endif
+
+#ifndef STATUS_TRUST_FAILURE
+# define STATUS_TRUST_FAILURE ((NTSTATUS) 0xC0000190L)
+#endif
+
+#ifndef STATUS_MUTANT_LIMIT_EXCEEDED
+# define STATUS_MUTANT_LIMIT_EXCEEDED ((NTSTATUS) 0xC0000191L)
+#endif
+
+#ifndef STATUS_NETLOGON_NOT_STARTED
+# define STATUS_NETLOGON_NOT_STARTED ((NTSTATUS) 0xC0000192L)
+#endif
+
+#ifndef STATUS_ACCOUNT_EXPIRED
+# define STATUS_ACCOUNT_EXPIRED ((NTSTATUS) 0xC0000193L)
+#endif
+
+#ifndef STATUS_POSSIBLE_DEADLOCK
+# define STATUS_POSSIBLE_DEADLOCK ((NTSTATUS) 0xC0000194L)
+#endif
+
+#ifndef STATUS_NETWORK_CREDENTIAL_CONFLICT
+# define STATUS_NETWORK_CREDENTIAL_CONFLICT ((NTSTATUS) 0xC0000195L)
+#endif
+
+#ifndef STATUS_REMOTE_SESSION_LIMIT
+# define STATUS_REMOTE_SESSION_LIMIT ((NTSTATUS) 0xC0000196L)
+#endif
+
+#ifndef STATUS_EVENTLOG_FILE_CHANGED
+# define STATUS_EVENTLOG_FILE_CHANGED ((NTSTATUS) 0xC0000197L)
+#endif
+
+#ifndef STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT
+# define STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT ((NTSTATUS) 0xC0000198L)
+#endif
+
+#ifndef STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT
+# define STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT ((NTSTATUS) 0xC0000199L)
+#endif
+
+#ifndef STATUS_NOLOGON_SERVER_TRUST_ACCOUNT
+# define STATUS_NOLOGON_SERVER_TRUST_ACCOUNT ((NTSTATUS) 0xC000019AL)
+#endif
+
+#ifndef STATUS_DOMAIN_TRUST_INCONSISTENT
+# define STATUS_DOMAIN_TRUST_INCONSISTENT ((NTSTATUS) 0xC000019BL)
+#endif
+
+#ifndef STATUS_FS_DRIVER_REQUIRED
+# define STATUS_FS_DRIVER_REQUIRED ((NTSTATUS) 0xC000019CL)
+#endif
+
+#ifndef STATUS_IMAGE_ALREADY_LOADED_AS_DLL
+# define STATUS_IMAGE_ALREADY_LOADED_AS_DLL ((NTSTATUS) 0xC000019DL)
+#endif
+
+#ifndef STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING
+# define STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING ((NTSTATUS) 0xC000019EL)
+#endif
+
+#ifndef STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME
+# define STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME ((NTSTATUS) 0xC000019FL)
+#endif
+
+#ifndef STATUS_SECURITY_STREAM_IS_INCONSISTENT
+# define STATUS_SECURITY_STREAM_IS_INCONSISTENT ((NTSTATUS) 0xC00001A0L)
+#endif
+
+#ifndef STATUS_INVALID_LOCK_RANGE
+# define STATUS_INVALID_LOCK_RANGE ((NTSTATUS) 0xC00001A1L)
+#endif
+
+#ifndef STATUS_INVALID_ACE_CONDITION
+# define STATUS_INVALID_ACE_CONDITION ((NTSTATUS) 0xC00001A2L)
+#endif
+
+#ifndef STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT
+# define STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT ((NTSTATUS) 0xC00001A3L)
+#endif
+
+#ifndef STATUS_NOTIFICATION_GUID_ALREADY_DEFINED
+# define STATUS_NOTIFICATION_GUID_ALREADY_DEFINED ((NTSTATUS) 0xC00001A4L)
+#endif
+
+#ifndef STATUS_NETWORK_OPEN_RESTRICTION
+# define STATUS_NETWORK_OPEN_RESTRICTION ((NTSTATUS) 0xC0000201L)
+#endif
+
+#ifndef STATUS_NO_USER_SESSION_KEY
+# define STATUS_NO_USER_SESSION_KEY ((NTSTATUS) 0xC0000202L)
+#endif
+
+#ifndef STATUS_USER_SESSION_DELETED
+# define STATUS_USER_SESSION_DELETED ((NTSTATUS) 0xC0000203L)
+#endif
+
+#ifndef STATUS_RESOURCE_LANG_NOT_FOUND
+# define STATUS_RESOURCE_LANG_NOT_FOUND ((NTSTATUS) 0xC0000204L)
+#endif
+
+#ifndef STATUS_INSUFF_SERVER_RESOURCES
+# define STATUS_INSUFF_SERVER_RESOURCES ((NTSTATUS) 0xC0000205L)
+#endif
+
+#ifndef STATUS_INVALID_BUFFER_SIZE
+# define STATUS_INVALID_BUFFER_SIZE ((NTSTATUS) 0xC0000206L)
+#endif
+
+#ifndef STATUS_INVALID_ADDRESS_COMPONENT
+# define STATUS_INVALID_ADDRESS_COMPONENT ((NTSTATUS) 0xC0000207L)
+#endif
+
+#ifndef STATUS_INVALID_ADDRESS_WILDCARD
+# define STATUS_INVALID_ADDRESS_WILDCARD ((NTSTATUS) 0xC0000208L)
+#endif
+
+#ifndef STATUS_TOO_MANY_ADDRESSES
+# define STATUS_TOO_MANY_ADDRESSES ((NTSTATUS) 0xC0000209L)
+#endif
+
+#ifndef STATUS_ADDRESS_ALREADY_EXISTS
+# define STATUS_ADDRESS_ALREADY_EXISTS ((NTSTATUS) 0xC000020AL)
+#endif
+
+#ifndef STATUS_ADDRESS_CLOSED
+# define STATUS_ADDRESS_CLOSED ((NTSTATUS) 0xC000020BL)
+#endif
+
+#ifndef STATUS_CONNECTION_DISCONNECTED
+# define STATUS_CONNECTION_DISCONNECTED ((NTSTATUS) 0xC000020CL)
+#endif
+
+#ifndef STATUS_CONNECTION_RESET
+# define STATUS_CONNECTION_RESET ((NTSTATUS) 0xC000020DL)
+#endif
+
+#ifndef STATUS_TOO_MANY_NODES
+# define STATUS_TOO_MANY_NODES ((NTSTATUS) 0xC000020EL)
+#endif
+
+#ifndef STATUS_TRANSACTION_ABORTED
+# define STATUS_TRANSACTION_ABORTED ((NTSTATUS) 0xC000020FL)
+#endif
+
+#ifndef STATUS_TRANSACTION_TIMED_OUT
+# define STATUS_TRANSACTION_TIMED_OUT ((NTSTATUS) 0xC0000210L)
+#endif
+
+#ifndef STATUS_TRANSACTION_NO_RELEASE
+# define STATUS_TRANSACTION_NO_RELEASE ((NTSTATUS) 0xC0000211L)
+#endif
+
+#ifndef STATUS_TRANSACTION_NO_MATCH
+# define STATUS_TRANSACTION_NO_MATCH ((NTSTATUS) 0xC0000212L)
+#endif
+
+#ifndef STATUS_TRANSACTION_RESPONDED
+# define STATUS_TRANSACTION_RESPONDED ((NTSTATUS) 0xC0000213L)
+#endif
+
+#ifndef STATUS_TRANSACTION_INVALID_ID
+# define STATUS_TRANSACTION_INVALID_ID ((NTSTATUS) 0xC0000214L)
+#endif
+
+#ifndef STATUS_TRANSACTION_INVALID_TYPE
+# define STATUS_TRANSACTION_INVALID_TYPE ((NTSTATUS) 0xC0000215L)
+#endif
+
+#ifndef STATUS_NOT_SERVER_SESSION
+# define STATUS_NOT_SERVER_SESSION ((NTSTATUS) 0xC0000216L)
+#endif
+
+#ifndef STATUS_NOT_CLIENT_SESSION
+# define STATUS_NOT_CLIENT_SESSION ((NTSTATUS) 0xC0000217L)
+#endif
+
+#ifndef STATUS_CANNOT_LOAD_REGISTRY_FILE
+# define STATUS_CANNOT_LOAD_REGISTRY_FILE ((NTSTATUS) 0xC0000218L)
+#endif
+
+#ifndef STATUS_DEBUG_ATTACH_FAILED
+# define STATUS_DEBUG_ATTACH_FAILED ((NTSTATUS) 0xC0000219L)
+#endif
+
+#ifndef STATUS_SYSTEM_PROCESS_TERMINATED
+# define STATUS_SYSTEM_PROCESS_TERMINATED ((NTSTATUS) 0xC000021AL)
+#endif
+
+#ifndef STATUS_DATA_NOT_ACCEPTED
+# define STATUS_DATA_NOT_ACCEPTED ((NTSTATUS) 0xC000021BL)
+#endif
+
+#ifndef STATUS_NO_BROWSER_SERVERS_FOUND
+# define STATUS_NO_BROWSER_SERVERS_FOUND ((NTSTATUS) 0xC000021CL)
+#endif
+
+#ifndef STATUS_VDM_HARD_ERROR
+# define STATUS_VDM_HARD_ERROR ((NTSTATUS) 0xC000021DL)
+#endif
+
+#ifndef STATUS_DRIVER_CANCEL_TIMEOUT
+# define STATUS_DRIVER_CANCEL_TIMEOUT ((NTSTATUS) 0xC000021EL)
+#endif
+
+#ifndef STATUS_REPLY_MESSAGE_MISMATCH
+# define STATUS_REPLY_MESSAGE_MISMATCH ((NTSTATUS) 0xC000021FL)
+#endif
+
+#ifndef STATUS_MAPPED_ALIGNMENT
+# define STATUS_MAPPED_ALIGNMENT ((NTSTATUS) 0xC0000220L)
+#endif
+
+#ifndef STATUS_IMAGE_CHECKSUM_MISMATCH
+# define STATUS_IMAGE_CHECKSUM_MISMATCH ((NTSTATUS) 0xC0000221L)
+#endif
+
+#ifndef STATUS_LOST_WRITEBEHIND_DATA
+# define STATUS_LOST_WRITEBEHIND_DATA ((NTSTATUS) 0xC0000222L)
+#endif
+
+#ifndef STATUS_CLIENT_SERVER_PARAMETERS_INVALID
+# define STATUS_CLIENT_SERVER_PARAMETERS_INVALID ((NTSTATUS) 0xC0000223L)
+#endif
+
+#ifndef STATUS_PASSWORD_MUST_CHANGE
+# define STATUS_PASSWORD_MUST_CHANGE ((NTSTATUS) 0xC0000224L)
+#endif
+
+#ifndef STATUS_NOT_FOUND
+# define STATUS_NOT_FOUND ((NTSTATUS) 0xC0000225L)
+#endif
+
+#ifndef STATUS_NOT_TINY_STREAM
+# define STATUS_NOT_TINY_STREAM ((NTSTATUS) 0xC0000226L)
+#endif
+
+#ifndef STATUS_RECOVERY_FAILURE
+# define STATUS_RECOVERY_FAILURE ((NTSTATUS) 0xC0000227L)
+#endif
+
+#ifndef STATUS_STACK_OVERFLOW_READ
+# define STATUS_STACK_OVERFLOW_READ ((NTSTATUS) 0xC0000228L)
+#endif
+
+#ifndef STATUS_FAIL_CHECK
+# define STATUS_FAIL_CHECK ((NTSTATUS) 0xC0000229L)
+#endif
+
+#ifndef STATUS_DUPLICATE_OBJECTID
+# define STATUS_DUPLICATE_OBJECTID ((NTSTATUS) 0xC000022AL)
+#endif
+
+#ifndef STATUS_OBJECTID_EXISTS
+# define STATUS_OBJECTID_EXISTS ((NTSTATUS) 0xC000022BL)
+#endif
+
+#ifndef STATUS_CONVERT_TO_LARGE
+# define STATUS_CONVERT_TO_LARGE ((NTSTATUS) 0xC000022CL)
+#endif
+
+#ifndef STATUS_RETRY
+# define STATUS_RETRY ((NTSTATUS) 0xC000022DL)
+#endif
+
+#ifndef STATUS_FOUND_OUT_OF_SCOPE
+# define STATUS_FOUND_OUT_OF_SCOPE ((NTSTATUS) 0xC000022EL)
+#endif
+
+#ifndef STATUS_ALLOCATE_BUCKET
+# define STATUS_ALLOCATE_BUCKET ((NTSTATUS) 0xC000022FL)
+#endif
+
+#ifndef STATUS_PROPSET_NOT_FOUND
+# define STATUS_PROPSET_NOT_FOUND ((NTSTATUS) 0xC0000230L)
+#endif
+
+#ifndef STATUS_MARSHALL_OVERFLOW
+# define STATUS_MARSHALL_OVERFLOW ((NTSTATUS) 0xC0000231L)
+#endif
+
+#ifndef STATUS_INVALID_VARIANT
+# define STATUS_INVALID_VARIANT ((NTSTATUS) 0xC0000232L)
+#endif
+
+#ifndef STATUS_DOMAIN_CONTROLLER_NOT_FOUND
+# define STATUS_DOMAIN_CONTROLLER_NOT_FOUND ((NTSTATUS) 0xC0000233L)
+#endif
+
+#ifndef STATUS_ACCOUNT_LOCKED_OUT
+# define STATUS_ACCOUNT_LOCKED_OUT ((NTSTATUS) 0xC0000234L)
+#endif
+
+#ifndef STATUS_HANDLE_NOT_CLOSABLE
+# define STATUS_HANDLE_NOT_CLOSABLE ((NTSTATUS) 0xC0000235L)
+#endif
+
+#ifndef STATUS_CONNECTION_REFUSED
+# define STATUS_CONNECTION_REFUSED ((NTSTATUS) 0xC0000236L)
+#endif
+
+#ifndef STATUS_GRACEFUL_DISCONNECT
+# define STATUS_GRACEFUL_DISCONNECT ((NTSTATUS) 0xC0000237L)
+#endif
+
+#ifndef STATUS_ADDRESS_ALREADY_ASSOCIATED
+# define STATUS_ADDRESS_ALREADY_ASSOCIATED ((NTSTATUS) 0xC0000238L)
+#endif
+
+#ifndef STATUS_ADDRESS_NOT_ASSOCIATED
+# define STATUS_ADDRESS_NOT_ASSOCIATED ((NTSTATUS) 0xC0000239L)
+#endif
+
+#ifndef STATUS_CONNECTION_INVALID
+# define STATUS_CONNECTION_INVALID ((NTSTATUS) 0xC000023AL)
+#endif
+
+#ifndef STATUS_CONNECTION_ACTIVE
+# define STATUS_CONNECTION_ACTIVE ((NTSTATUS) 0xC000023BL)
+#endif
+
+#ifndef STATUS_NETWORK_UNREACHABLE
+# define STATUS_NETWORK_UNREACHABLE ((NTSTATUS) 0xC000023CL)
+#endif
+
+#ifndef STATUS_HOST_UNREACHABLE
+# define STATUS_HOST_UNREACHABLE ((NTSTATUS) 0xC000023DL)
+#endif
+
+#ifndef STATUS_PROTOCOL_UNREACHABLE
+# define STATUS_PROTOCOL_UNREACHABLE ((NTSTATUS) 0xC000023EL)
+#endif
+
+#ifndef STATUS_PORT_UNREACHABLE
+# define STATUS_PORT_UNREACHABLE ((NTSTATUS) 0xC000023FL)
+#endif
+
+#ifndef STATUS_REQUEST_ABORTED
+# define STATUS_REQUEST_ABORTED ((NTSTATUS) 0xC0000240L)
+#endif
+
+#ifndef STATUS_CONNECTION_ABORTED
+# define STATUS_CONNECTION_ABORTED ((NTSTATUS) 0xC0000241L)
+#endif
+
+#ifndef STATUS_BAD_COMPRESSION_BUFFER
+# define STATUS_BAD_COMPRESSION_BUFFER ((NTSTATUS) 0xC0000242L)
+#endif
+
+#ifndef STATUS_USER_MAPPED_FILE
+# define STATUS_USER_MAPPED_FILE ((NTSTATUS) 0xC0000243L)
+#endif
+
+#ifndef STATUS_AUDIT_FAILED
+# define STATUS_AUDIT_FAILED ((NTSTATUS) 0xC0000244L)
+#endif
+
+#ifndef STATUS_TIMER_RESOLUTION_NOT_SET
+# define STATUS_TIMER_RESOLUTION_NOT_SET ((NTSTATUS) 0xC0000245L)
+#endif
+
+#ifndef STATUS_CONNECTION_COUNT_LIMIT
+# define STATUS_CONNECTION_COUNT_LIMIT ((NTSTATUS) 0xC0000246L)
+#endif
+
+#ifndef STATUS_LOGIN_TIME_RESTRICTION
+# define STATUS_LOGIN_TIME_RESTRICTION ((NTSTATUS) 0xC0000247L)
+#endif
+
+#ifndef STATUS_LOGIN_WKSTA_RESTRICTION
+# define STATUS_LOGIN_WKSTA_RESTRICTION ((NTSTATUS) 0xC0000248L)
+#endif
+
+#ifndef STATUS_IMAGE_MP_UP_MISMATCH
+# define STATUS_IMAGE_MP_UP_MISMATCH ((NTSTATUS) 0xC0000249L)
+#endif
+
+#ifndef STATUS_INSUFFICIENT_LOGON_INFO
+# define STATUS_INSUFFICIENT_LOGON_INFO ((NTSTATUS) 0xC0000250L)
+#endif
+
+#ifndef STATUS_BAD_DLL_ENTRYPOINT
+# define STATUS_BAD_DLL_ENTRYPOINT ((NTSTATUS) 0xC0000251L)
+#endif
+
+#ifndef STATUS_BAD_SERVICE_ENTRYPOINT
+# define STATUS_BAD_SERVICE_ENTRYPOINT ((NTSTATUS) 0xC0000252L)
+#endif
+
+#ifndef STATUS_LPC_REPLY_LOST
+# define STATUS_LPC_REPLY_LOST ((NTSTATUS) 0xC0000253L)
+#endif
+
+#ifndef STATUS_IP_ADDRESS_CONFLICT1
+# define STATUS_IP_ADDRESS_CONFLICT1 ((NTSTATUS) 0xC0000254L)
+#endif
+
+#ifndef STATUS_IP_ADDRESS_CONFLICT2
+# define STATUS_IP_ADDRESS_CONFLICT2 ((NTSTATUS) 0xC0000255L)
+#endif
+
+#ifndef STATUS_REGISTRY_QUOTA_LIMIT
+# define STATUS_REGISTRY_QUOTA_LIMIT ((NTSTATUS) 0xC0000256L)
+#endif
+
+#ifndef STATUS_PATH_NOT_COVERED
+# define STATUS_PATH_NOT_COVERED ((NTSTATUS) 0xC0000257L)
+#endif
+
+#ifndef STATUS_NO_CALLBACK_ACTIVE
+# define STATUS_NO_CALLBACK_ACTIVE ((NTSTATUS) 0xC0000258L)
+#endif
+
+#ifndef STATUS_LICENSE_QUOTA_EXCEEDED
+# define STATUS_LICENSE_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000259L)
+#endif
+
+#ifndef STATUS_PWD_TOO_SHORT
+# define STATUS_PWD_TOO_SHORT ((NTSTATUS) 0xC000025AL)
+#endif
+
+#ifndef STATUS_PWD_TOO_RECENT
+# define STATUS_PWD_TOO_RECENT ((NTSTATUS) 0xC000025BL)
+#endif
+
+#ifndef STATUS_PWD_HISTORY_CONFLICT
+# define STATUS_PWD_HISTORY_CONFLICT ((NTSTATUS) 0xC000025CL)
+#endif
+
+#ifndef STATUS_PLUGPLAY_NO_DEVICE
+# define STATUS_PLUGPLAY_NO_DEVICE ((NTSTATUS) 0xC000025EL)
+#endif
+
+#ifndef STATUS_UNSUPPORTED_COMPRESSION
+# define STATUS_UNSUPPORTED_COMPRESSION ((NTSTATUS) 0xC000025FL)
+#endif
+
+#ifndef STATUS_INVALID_HW_PROFILE
+# define STATUS_INVALID_HW_PROFILE ((NTSTATUS) 0xC0000260L)
+#endif
+
+#ifndef STATUS_INVALID_PLUGPLAY_DEVICE_PATH
+# define STATUS_INVALID_PLUGPLAY_DEVICE_PATH ((NTSTATUS) 0xC0000261L)
+#endif
+
+#ifndef STATUS_DRIVER_ORDINAL_NOT_FOUND
+# define STATUS_DRIVER_ORDINAL_NOT_FOUND ((NTSTATUS) 0xC0000262L)
+#endif
+
+#ifndef STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
+# define STATUS_DRIVER_ENTRYPOINT_NOT_FOUND ((NTSTATUS) 0xC0000263L)
+#endif
+
+#ifndef STATUS_RESOURCE_NOT_OWNED
+# define STATUS_RESOURCE_NOT_OWNED ((NTSTATUS) 0xC0000264L)
+#endif
+
+#ifndef STATUS_TOO_MANY_LINKS
+# define STATUS_TOO_MANY_LINKS ((NTSTATUS) 0xC0000265L)
+#endif
+
+#ifndef STATUS_QUOTA_LIST_INCONSISTENT
+# define STATUS_QUOTA_LIST_INCONSISTENT ((NTSTATUS) 0xC0000266L)
+#endif
+
+#ifndef STATUS_FILE_IS_OFFLINE
+# define STATUS_FILE_IS_OFFLINE ((NTSTATUS) 0xC0000267L)
+#endif
+
+#ifndef STATUS_EVALUATION_EXPIRATION
+# define STATUS_EVALUATION_EXPIRATION ((NTSTATUS) 0xC0000268L)
+#endif
+
+#ifndef STATUS_ILLEGAL_DLL_RELOCATION
+# define STATUS_ILLEGAL_DLL_RELOCATION ((NTSTATUS) 0xC0000269L)
+#endif
+
+#ifndef STATUS_LICENSE_VIOLATION
+# define STATUS_LICENSE_VIOLATION ((NTSTATUS) 0xC000026AL)
+#endif
+
+#ifndef STATUS_DLL_INIT_FAILED_LOGOFF
+# define STATUS_DLL_INIT_FAILED_LOGOFF ((NTSTATUS) 0xC000026BL)
+#endif
+
+#ifndef STATUS_DRIVER_UNABLE_TO_LOAD
+# define STATUS_DRIVER_UNABLE_TO_LOAD ((NTSTATUS) 0xC000026CL)
+#endif
+
+#ifndef STATUS_DFS_UNAVAILABLE
+# define STATUS_DFS_UNAVAILABLE ((NTSTATUS) 0xC000026DL)
+#endif
+
+#ifndef STATUS_VOLUME_DISMOUNTED
+# define STATUS_VOLUME_DISMOUNTED ((NTSTATUS) 0xC000026EL)
+#endif
+
+#ifndef STATUS_WX86_INTERNAL_ERROR
+# define STATUS_WX86_INTERNAL_ERROR ((NTSTATUS) 0xC000026FL)
+#endif
+
+#ifndef STATUS_WX86_FLOAT_STACK_CHECK
+# define STATUS_WX86_FLOAT_STACK_CHECK ((NTSTATUS) 0xC0000270L)
+#endif
+
+#ifndef STATUS_VALIDATE_CONTINUE
+# define STATUS_VALIDATE_CONTINUE ((NTSTATUS) 0xC0000271L)
+#endif
+
+#ifndef STATUS_NO_MATCH
+# define STATUS_NO_MATCH ((NTSTATUS) 0xC0000272L)
+#endif
+
+#ifndef STATUS_NO_MORE_MATCHES
+# define STATUS_NO_MORE_MATCHES ((NTSTATUS) 0xC0000273L)
+#endif
+
+#ifndef STATUS_NOT_A_REPARSE_POINT
+# define STATUS_NOT_A_REPARSE_POINT ((NTSTATUS) 0xC0000275L)
+#endif
+
+#ifndef STATUS_IO_REPARSE_TAG_INVALID
+# define STATUS_IO_REPARSE_TAG_INVALID ((NTSTATUS) 0xC0000276L)
+#endif
+
+#ifndef STATUS_IO_REPARSE_TAG_MISMATCH
+# define STATUS_IO_REPARSE_TAG_MISMATCH ((NTSTATUS) 0xC0000277L)
+#endif
+
+#ifndef STATUS_IO_REPARSE_DATA_INVALID
+# define STATUS_IO_REPARSE_DATA_INVALID ((NTSTATUS) 0xC0000278L)
+#endif
+
+#ifndef STATUS_IO_REPARSE_TAG_NOT_HANDLED
+# define STATUS_IO_REPARSE_TAG_NOT_HANDLED ((NTSTATUS) 0xC0000279L)
+#endif
+
+#ifndef STATUS_REPARSE_POINT_NOT_RESOLVED
+# define STATUS_REPARSE_POINT_NOT_RESOLVED ((NTSTATUS) 0xC0000280L)
+#endif
+
+#ifndef STATUS_DIRECTORY_IS_A_REPARSE_POINT
+# define STATUS_DIRECTORY_IS_A_REPARSE_POINT ((NTSTATUS) 0xC0000281L)
+#endif
+
+#ifndef STATUS_RANGE_LIST_CONFLICT
+# define STATUS_RANGE_LIST_CONFLICT ((NTSTATUS) 0xC0000282L)
+#endif
+
+#ifndef STATUS_SOURCE_ELEMENT_EMPTY
+# define STATUS_SOURCE_ELEMENT_EMPTY ((NTSTATUS) 0xC0000283L)
+#endif
+
+#ifndef STATUS_DESTINATION_ELEMENT_FULL
+# define STATUS_DESTINATION_ELEMENT_FULL ((NTSTATUS) 0xC0000284L)
+#endif
+
+#ifndef STATUS_ILLEGAL_ELEMENT_ADDRESS
+# define STATUS_ILLEGAL_ELEMENT_ADDRESS ((NTSTATUS) 0xC0000285L)
+#endif
+
+#ifndef STATUS_MAGAZINE_NOT_PRESENT
+# define STATUS_MAGAZINE_NOT_PRESENT ((NTSTATUS) 0xC0000286L)
+#endif
+
+#ifndef STATUS_REINITIALIZATION_NEEDED
+# define STATUS_REINITIALIZATION_NEEDED ((NTSTATUS) 0xC0000287L)
+#endif
+
+#ifndef STATUS_DEVICE_REQUIRES_CLEANING
+# define STATUS_DEVICE_REQUIRES_CLEANING ((NTSTATUS) 0x80000288L)
+#endif
+
+#ifndef STATUS_DEVICE_DOOR_OPEN
+# define STATUS_DEVICE_DOOR_OPEN ((NTSTATUS) 0x80000289L)
+#endif
+
+#ifndef STATUS_ENCRYPTION_FAILED
+# define STATUS_ENCRYPTION_FAILED ((NTSTATUS) 0xC000028AL)
+#endif
+
+#ifndef STATUS_DECRYPTION_FAILED
+# define STATUS_DECRYPTION_FAILED ((NTSTATUS) 0xC000028BL)
+#endif
+
+#ifndef STATUS_RANGE_NOT_FOUND
+# define STATUS_RANGE_NOT_FOUND ((NTSTATUS) 0xC000028CL)
+#endif
+
+#ifndef STATUS_NO_RECOVERY_POLICY
+# define STATUS_NO_RECOVERY_POLICY ((NTSTATUS) 0xC000028DL)
+#endif
+
+#ifndef STATUS_NO_EFS
+# define STATUS_NO_EFS ((NTSTATUS) 0xC000028EL)
+#endif
+
+#ifndef STATUS_WRONG_EFS
+# define STATUS_WRONG_EFS ((NTSTATUS) 0xC000028FL)
+#endif
+
+#ifndef STATUS_NO_USER_KEYS
+# define STATUS_NO_USER_KEYS ((NTSTATUS) 0xC0000290L)
+#endif
+
+#ifndef STATUS_FILE_NOT_ENCRYPTED
+# define STATUS_FILE_NOT_ENCRYPTED ((NTSTATUS) 0xC0000291L)
+#endif
+
+#ifndef STATUS_NOT_EXPORT_FORMAT
+# define STATUS_NOT_EXPORT_FORMAT ((NTSTATUS) 0xC0000292L)
+#endif
+
+#ifndef STATUS_FILE_ENCRYPTED
+# define STATUS_FILE_ENCRYPTED ((NTSTATUS) 0xC0000293L)
+#endif
+
+#ifndef STATUS_WAKE_SYSTEM
+# define STATUS_WAKE_SYSTEM ((NTSTATUS) 0x40000294L)
+#endif
+
+#ifndef STATUS_WMI_GUID_NOT_FOUND
+# define STATUS_WMI_GUID_NOT_FOUND ((NTSTATUS) 0xC0000295L)
+#endif
+
+#ifndef STATUS_WMI_INSTANCE_NOT_FOUND
+# define STATUS_WMI_INSTANCE_NOT_FOUND ((NTSTATUS) 0xC0000296L)
+#endif
+
+#ifndef STATUS_WMI_ITEMID_NOT_FOUND
+# define STATUS_WMI_ITEMID_NOT_FOUND ((NTSTATUS) 0xC0000297L)
+#endif
+
+#ifndef STATUS_WMI_TRY_AGAIN
+# define STATUS_WMI_TRY_AGAIN ((NTSTATUS) 0xC0000298L)
+#endif
+
+#ifndef STATUS_SHARED_POLICY
+# define STATUS_SHARED_POLICY ((NTSTATUS) 0xC0000299L)
+#endif
+
+#ifndef STATUS_POLICY_OBJECT_NOT_FOUND
+# define STATUS_POLICY_OBJECT_NOT_FOUND ((NTSTATUS) 0xC000029AL)
+#endif
+
+#ifndef STATUS_POLICY_ONLY_IN_DS
+# define STATUS_POLICY_ONLY_IN_DS ((NTSTATUS) 0xC000029BL)
+#endif
+
+#ifndef STATUS_VOLUME_NOT_UPGRADED
+# define STATUS_VOLUME_NOT_UPGRADED ((NTSTATUS) 0xC000029CL)
+#endif
+
+#ifndef STATUS_REMOTE_STORAGE_NOT_ACTIVE
+# define STATUS_REMOTE_STORAGE_NOT_ACTIVE ((NTSTATUS) 0xC000029DL)
+#endif
+
+#ifndef STATUS_REMOTE_STORAGE_MEDIA_ERROR
+# define STATUS_REMOTE_STORAGE_MEDIA_ERROR ((NTSTATUS) 0xC000029EL)
+#endif
+
+#ifndef STATUS_NO_TRACKING_SERVICE
+# define STATUS_NO_TRACKING_SERVICE ((NTSTATUS) 0xC000029FL)
+#endif
+
+#ifndef STATUS_SERVER_SID_MISMATCH
+# define STATUS_SERVER_SID_MISMATCH ((NTSTATUS) 0xC00002A0L)
+#endif
+
+#ifndef STATUS_DS_NO_ATTRIBUTE_OR_VALUE
+# define STATUS_DS_NO_ATTRIBUTE_OR_VALUE ((NTSTATUS) 0xC00002A1L)
+#endif
+
+#ifndef STATUS_DS_INVALID_ATTRIBUTE_SYNTAX
+# define STATUS_DS_INVALID_ATTRIBUTE_SYNTAX ((NTSTATUS) 0xC00002A2L)
+#endif
+
+#ifndef STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED
+# define STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED ((NTSTATUS) 0xC00002A3L)
+#endif
+
+#ifndef STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS
+# define STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS ((NTSTATUS) 0xC00002A4L)
+#endif
+
+#ifndef STATUS_DS_BUSY
+# define STATUS_DS_BUSY ((NTSTATUS) 0xC00002A5L)
+#endif
+
+#ifndef STATUS_DS_UNAVAILABLE
+# define STATUS_DS_UNAVAILABLE ((NTSTATUS) 0xC00002A6L)
+#endif
+
+#ifndef STATUS_DS_NO_RIDS_ALLOCATED
+# define STATUS_DS_NO_RIDS_ALLOCATED ((NTSTATUS) 0xC00002A7L)
+#endif
+
+#ifndef STATUS_DS_NO_MORE_RIDS
+# define STATUS_DS_NO_MORE_RIDS ((NTSTATUS) 0xC00002A8L)
+#endif
+
+#ifndef STATUS_DS_INCORRECT_ROLE_OWNER
+# define STATUS_DS_INCORRECT_ROLE_OWNER ((NTSTATUS) 0xC00002A9L)
+#endif
+
+#ifndef STATUS_DS_RIDMGR_INIT_ERROR
+# define STATUS_DS_RIDMGR_INIT_ERROR ((NTSTATUS) 0xC00002AAL)
+#endif
+
+#ifndef STATUS_DS_OBJ_CLASS_VIOLATION
+# define STATUS_DS_OBJ_CLASS_VIOLATION ((NTSTATUS) 0xC00002ABL)
+#endif
+
+#ifndef STATUS_DS_CANT_ON_NON_LEAF
+# define STATUS_DS_CANT_ON_NON_LEAF ((NTSTATUS) 0xC00002ACL)
+#endif
+
+#ifndef STATUS_DS_CANT_ON_RDN
+# define STATUS_DS_CANT_ON_RDN ((NTSTATUS) 0xC00002ADL)
+#endif
+
+#ifndef STATUS_DS_CANT_MOD_OBJ_CLASS
+# define STATUS_DS_CANT_MOD_OBJ_CLASS ((NTSTATUS) 0xC00002AEL)
+#endif
+
+#ifndef STATUS_DS_CROSS_DOM_MOVE_FAILED
+# define STATUS_DS_CROSS_DOM_MOVE_FAILED ((NTSTATUS) 0xC00002AFL)
+#endif
+
+#ifndef STATUS_DS_GC_NOT_AVAILABLE
+# define STATUS_DS_GC_NOT_AVAILABLE ((NTSTATUS) 0xC00002B0L)
+#endif
+
+#ifndef STATUS_DIRECTORY_SERVICE_REQUIRED
+# define STATUS_DIRECTORY_SERVICE_REQUIRED ((NTSTATUS) 0xC00002B1L)
+#endif
+
+#ifndef STATUS_REPARSE_ATTRIBUTE_CONFLICT
+# define STATUS_REPARSE_ATTRIBUTE_CONFLICT ((NTSTATUS) 0xC00002B2L)
+#endif
+
+#ifndef STATUS_CANT_ENABLE_DENY_ONLY
+# define STATUS_CANT_ENABLE_DENY_ONLY ((NTSTATUS) 0xC00002B3L)
+#endif
+
+#ifndef STATUS_FLOAT_MULTIPLE_FAULTS
+# define STATUS_FLOAT_MULTIPLE_FAULTS ((NTSTATUS) 0xC00002B4L)
+#endif
+
+#ifndef STATUS_FLOAT_MULTIPLE_TRAPS
+# define STATUS_FLOAT_MULTIPLE_TRAPS ((NTSTATUS) 0xC00002B5L)
+#endif
+
+#ifndef STATUS_DEVICE_REMOVED
+# define STATUS_DEVICE_REMOVED ((NTSTATUS) 0xC00002B6L)
+#endif
+
+#ifndef STATUS_JOURNAL_DELETE_IN_PROGRESS
+# define STATUS_JOURNAL_DELETE_IN_PROGRESS ((NTSTATUS) 0xC00002B7L)
+#endif
+
+#ifndef STATUS_JOURNAL_NOT_ACTIVE
+# define STATUS_JOURNAL_NOT_ACTIVE ((NTSTATUS) 0xC00002B8L)
+#endif
+
+#ifndef STATUS_NOINTERFACE
+# define STATUS_NOINTERFACE ((NTSTATUS) 0xC00002B9L)
+#endif
+
+#ifndef STATUS_DS_ADMIN_LIMIT_EXCEEDED
+# define STATUS_DS_ADMIN_LIMIT_EXCEEDED ((NTSTATUS) 0xC00002C1L)
+#endif
+
+#ifndef STATUS_DRIVER_FAILED_SLEEP
+# define STATUS_DRIVER_FAILED_SLEEP ((NTSTATUS) 0xC00002C2L)
+#endif
+
+#ifndef STATUS_MUTUAL_AUTHENTICATION_FAILED
+# define STATUS_MUTUAL_AUTHENTICATION_FAILED ((NTSTATUS) 0xC00002C3L)
+#endif
+
+#ifndef STATUS_CORRUPT_SYSTEM_FILE
+# define STATUS_CORRUPT_SYSTEM_FILE ((NTSTATUS) 0xC00002C4L)
+#endif
+
+#ifndef STATUS_DATATYPE_MISALIGNMENT_ERROR
+# define STATUS_DATATYPE_MISALIGNMENT_ERROR ((NTSTATUS) 0xC00002C5L)
+#endif
+
+#ifndef STATUS_WMI_READ_ONLY
+# define STATUS_WMI_READ_ONLY ((NTSTATUS) 0xC00002C6L)
+#endif
+
+#ifndef STATUS_WMI_SET_FAILURE
+# define STATUS_WMI_SET_FAILURE ((NTSTATUS) 0xC00002C7L)
+#endif
+
+#ifndef STATUS_COMMITMENT_MINIMUM
+# define STATUS_COMMITMENT_MINIMUM ((NTSTATUS) 0xC00002C8L)
+#endif
+
+#ifndef STATUS_REG_NAT_CONSUMPTION
+# define STATUS_REG_NAT_CONSUMPTION ((NTSTATUS) 0xC00002C9L)
+#endif
+
+#ifndef STATUS_TRANSPORT_FULL
+# define STATUS_TRANSPORT_FULL ((NTSTATUS) 0xC00002CAL)
+#endif
+
+#ifndef STATUS_DS_SAM_INIT_FAILURE
+# define STATUS_DS_SAM_INIT_FAILURE ((NTSTATUS) 0xC00002CBL)
+#endif
+
+#ifndef STATUS_ONLY_IF_CONNECTED
+# define STATUS_ONLY_IF_CONNECTED ((NTSTATUS) 0xC00002CCL)
+#endif
+
+#ifndef STATUS_DS_SENSITIVE_GROUP_VIOLATION
+# define STATUS_DS_SENSITIVE_GROUP_VIOLATION ((NTSTATUS) 0xC00002CDL)
+#endif
+
+#ifndef STATUS_PNP_RESTART_ENUMERATION
+# define STATUS_PNP_RESTART_ENUMERATION ((NTSTATUS) 0xC00002CEL)
+#endif
+
+#ifndef STATUS_JOURNAL_ENTRY_DELETED
+# define STATUS_JOURNAL_ENTRY_DELETED ((NTSTATUS) 0xC00002CFL)
+#endif
+
+#ifndef STATUS_DS_CANT_MOD_PRIMARYGROUPID
+# define STATUS_DS_CANT_MOD_PRIMARYGROUPID ((NTSTATUS) 0xC00002D0L)
+#endif
+
+#ifndef STATUS_SYSTEM_IMAGE_BAD_SIGNATURE
+# define STATUS_SYSTEM_IMAGE_BAD_SIGNATURE ((NTSTATUS) 0xC00002D1L)
+#endif
+
+#ifndef STATUS_PNP_REBOOT_REQUIRED
+# define STATUS_PNP_REBOOT_REQUIRED ((NTSTATUS) 0xC00002D2L)
+#endif
+
+#ifndef STATUS_POWER_STATE_INVALID
+# define STATUS_POWER_STATE_INVALID ((NTSTATUS) 0xC00002D3L)
+#endif
+
+#ifndef STATUS_DS_INVALID_GROUP_TYPE
+# define STATUS_DS_INVALID_GROUP_TYPE ((NTSTATUS) 0xC00002D4L)
+#endif
+
+#ifndef STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN
+# define STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN ((NTSTATUS) 0xC00002D5L)
+#endif
+
+#ifndef STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN
+# define STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN ((NTSTATUS) 0xC00002D6L)
+#endif
+
+#ifndef STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER
+# define STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER ((NTSTATUS) 0xC00002D7L)
+#endif
+
+#ifndef STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER
+# define STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER ((NTSTATUS) 0xC00002D8L)
+#endif
+
+#ifndef STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER
+# define STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER ((NTSTATUS) 0xC00002D9L)
+#endif
+
+#ifndef STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER
+# define STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER ((NTSTATUS) 0xC00002DAL)
+#endif
+
+#ifndef STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER
+# define STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER ((NTSTATUS) 0xC00002DBL)
+#endif
+
+#ifndef STATUS_DS_HAVE_PRIMARY_MEMBERS
+# define STATUS_DS_HAVE_PRIMARY_MEMBERS ((NTSTATUS) 0xC00002DCL)
+#endif
+
+#ifndef STATUS_WMI_NOT_SUPPORTED
+# define STATUS_WMI_NOT_SUPPORTED ((NTSTATUS) 0xC00002DDL)
+#endif
+
+#ifndef STATUS_INSUFFICIENT_POWER
+# define STATUS_INSUFFICIENT_POWER ((NTSTATUS) 0xC00002DEL)
+#endif
+
+#ifndef STATUS_SAM_NEED_BOOTKEY_PASSWORD
+# define STATUS_SAM_NEED_BOOTKEY_PASSWORD ((NTSTATUS) 0xC00002DFL)
+#endif
+
+#ifndef STATUS_SAM_NEED_BOOTKEY_FLOPPY
+# define STATUS_SAM_NEED_BOOTKEY_FLOPPY ((NTSTATUS) 0xC00002E0L)
+#endif
+
+#ifndef STATUS_DS_CANT_START
+# define STATUS_DS_CANT_START ((NTSTATUS) 0xC00002E1L)
+#endif
+
+#ifndef STATUS_DS_INIT_FAILURE
+# define STATUS_DS_INIT_FAILURE ((NTSTATUS) 0xC00002E2L)
+#endif
+
+#ifndef STATUS_SAM_INIT_FAILURE
+# define STATUS_SAM_INIT_FAILURE ((NTSTATUS) 0xC00002E3L)
+#endif
+
+#ifndef STATUS_DS_GC_REQUIRED
+# define STATUS_DS_GC_REQUIRED ((NTSTATUS) 0xC00002E4L)
+#endif
+
+#ifndef STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY
+# define STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY ((NTSTATUS) 0xC00002E5L)
+#endif
+
+#ifndef STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS
+# define STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS ((NTSTATUS) 0xC00002E6L)
+#endif
+
+#ifndef STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED
+# define STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED ((NTSTATUS) 0xC00002E7L)
+#endif
+
+#ifndef STATUS_MULTIPLE_FAULT_VIOLATION
+# define STATUS_MULTIPLE_FAULT_VIOLATION ((NTSTATUS) 0xC00002E8L)
+#endif
+
+#ifndef STATUS_CURRENT_DOMAIN_NOT_ALLOWED
+# define STATUS_CURRENT_DOMAIN_NOT_ALLOWED ((NTSTATUS) 0xC00002E9L)
+#endif
+
+#ifndef STATUS_CANNOT_MAKE
+# define STATUS_CANNOT_MAKE ((NTSTATUS) 0xC00002EAL)
+#endif
+
+#ifndef STATUS_SYSTEM_SHUTDOWN
+# define STATUS_SYSTEM_SHUTDOWN ((NTSTATUS) 0xC00002EBL)
+#endif
+
+#ifndef STATUS_DS_INIT_FAILURE_CONSOLE
+# define STATUS_DS_INIT_FAILURE_CONSOLE ((NTSTATUS) 0xC00002ECL)
+#endif
+
+#ifndef STATUS_DS_SAM_INIT_FAILURE_CONSOLE
+# define STATUS_DS_SAM_INIT_FAILURE_CONSOLE ((NTSTATUS) 0xC00002EDL)
+#endif
+
+#ifndef STATUS_UNFINISHED_CONTEXT_DELETED
+# define STATUS_UNFINISHED_CONTEXT_DELETED ((NTSTATUS) 0xC00002EEL)
+#endif
+
+#ifndef STATUS_NO_TGT_REPLY
+# define STATUS_NO_TGT_REPLY ((NTSTATUS) 0xC00002EFL)
+#endif
+
+#ifndef STATUS_OBJECTID_NOT_FOUND
+# define STATUS_OBJECTID_NOT_FOUND ((NTSTATUS) 0xC00002F0L)
+#endif
+
+#ifndef STATUS_NO_IP_ADDRESSES
+# define STATUS_NO_IP_ADDRESSES ((NTSTATUS) 0xC00002F1L)
+#endif
+
+#ifndef STATUS_WRONG_CREDENTIAL_HANDLE
+# define STATUS_WRONG_CREDENTIAL_HANDLE ((NTSTATUS) 0xC00002F2L)
+#endif
+
+#ifndef STATUS_CRYPTO_SYSTEM_INVALID
+# define STATUS_CRYPTO_SYSTEM_INVALID ((NTSTATUS) 0xC00002F3L)
+#endif
+
+#ifndef STATUS_MAX_REFERRALS_EXCEEDED
+# define STATUS_MAX_REFERRALS_EXCEEDED ((NTSTATUS) 0xC00002F4L)
+#endif
+
+#ifndef STATUS_MUST_BE_KDC
+# define STATUS_MUST_BE_KDC ((NTSTATUS) 0xC00002F5L)
+#endif
+
+#ifndef STATUS_STRONG_CRYPTO_NOT_SUPPORTED
+# define STATUS_STRONG_CRYPTO_NOT_SUPPORTED ((NTSTATUS) 0xC00002F6L)
+#endif
+
+#ifndef STATUS_TOO_MANY_PRINCIPALS
+# define STATUS_TOO_MANY_PRINCIPALS ((NTSTATUS) 0xC00002F7L)
+#endif
+
+#ifndef STATUS_NO_PA_DATA
+# define STATUS_NO_PA_DATA ((NTSTATUS) 0xC00002F8L)
+#endif
+
+#ifndef STATUS_PKINIT_NAME_MISMATCH
+# define STATUS_PKINIT_NAME_MISMATCH ((NTSTATUS) 0xC00002F9L)
+#endif
+
+#ifndef STATUS_SMARTCARD_LOGON_REQUIRED
+# define STATUS_SMARTCARD_LOGON_REQUIRED ((NTSTATUS) 0xC00002FAL)
+#endif
+
+#ifndef STATUS_KDC_INVALID_REQUEST
+# define STATUS_KDC_INVALID_REQUEST ((NTSTATUS) 0xC00002FBL)
+#endif
+
+#ifndef STATUS_KDC_UNABLE_TO_REFER
+# define STATUS_KDC_UNABLE_TO_REFER ((NTSTATUS) 0xC00002FCL)
+#endif
+
+#ifndef STATUS_KDC_UNKNOWN_ETYPE
+# define STATUS_KDC_UNKNOWN_ETYPE ((NTSTATUS) 0xC00002FDL)
+#endif
+
+#ifndef STATUS_SHUTDOWN_IN_PROGRESS
+# define STATUS_SHUTDOWN_IN_PROGRESS ((NTSTATUS) 0xC00002FEL)
+#endif
+
+#ifndef STATUS_SERVER_SHUTDOWN_IN_PROGRESS
+# define STATUS_SERVER_SHUTDOWN_IN_PROGRESS ((NTSTATUS) 0xC00002FFL)
+#endif
+
+#ifndef STATUS_NOT_SUPPORTED_ON_SBS
+# define STATUS_NOT_SUPPORTED_ON_SBS ((NTSTATUS) 0xC0000300L)
+#endif
+
+#ifndef STATUS_WMI_GUID_DISCONNECTED
+# define STATUS_WMI_GUID_DISCONNECTED ((NTSTATUS) 0xC0000301L)
+#endif
+
+#ifndef STATUS_WMI_ALREADY_DISABLED
+# define STATUS_WMI_ALREADY_DISABLED ((NTSTATUS) 0xC0000302L)
+#endif
+
+#ifndef STATUS_WMI_ALREADY_ENABLED
+# define STATUS_WMI_ALREADY_ENABLED ((NTSTATUS) 0xC0000303L)
+#endif
+
+#ifndef STATUS_MFT_TOO_FRAGMENTED
+# define STATUS_MFT_TOO_FRAGMENTED ((NTSTATUS) 0xC0000304L)
+#endif
+
+#ifndef STATUS_COPY_PROTECTION_FAILURE
+# define STATUS_COPY_PROTECTION_FAILURE ((NTSTATUS) 0xC0000305L)
+#endif
+
+#ifndef STATUS_CSS_AUTHENTICATION_FAILURE
+# define STATUS_CSS_AUTHENTICATION_FAILURE ((NTSTATUS) 0xC0000306L)
+#endif
+
+#ifndef STATUS_CSS_KEY_NOT_PRESENT
+# define STATUS_CSS_KEY_NOT_PRESENT ((NTSTATUS) 0xC0000307L)
+#endif
+
+#ifndef STATUS_CSS_KEY_NOT_ESTABLISHED
+# define STATUS_CSS_KEY_NOT_ESTABLISHED ((NTSTATUS) 0xC0000308L)
+#endif
+
+#ifndef STATUS_CSS_SCRAMBLED_SECTOR
+# define STATUS_CSS_SCRAMBLED_SECTOR ((NTSTATUS) 0xC0000309L)
+#endif
+
+#ifndef STATUS_CSS_REGION_MISMATCH
+# define STATUS_CSS_REGION_MISMATCH ((NTSTATUS) 0xC000030AL)
+#endif
+
+#ifndef STATUS_CSS_RESETS_EXHAUSTED
+# define STATUS_CSS_RESETS_EXHAUSTED ((NTSTATUS) 0xC000030BL)
+#endif
+
+#ifndef STATUS_PKINIT_FAILURE
+# define STATUS_PKINIT_FAILURE ((NTSTATUS) 0xC0000320L)
+#endif
+
+#ifndef STATUS_SMARTCARD_SUBSYSTEM_FAILURE
+# define STATUS_SMARTCARD_SUBSYSTEM_FAILURE ((NTSTATUS) 0xC0000321L)
+#endif
+
+#ifndef STATUS_NO_KERB_KEY
+# define STATUS_NO_KERB_KEY ((NTSTATUS) 0xC0000322L)
+#endif
+
+#ifndef STATUS_HOST_DOWN
+# define STATUS_HOST_DOWN ((NTSTATUS) 0xC0000350L)
+#endif
+
+#ifndef STATUS_UNSUPPORTED_PREAUTH
+# define STATUS_UNSUPPORTED_PREAUTH ((NTSTATUS) 0xC0000351L)
+#endif
+
+#ifndef STATUS_EFS_ALG_BLOB_TOO_BIG
+# define STATUS_EFS_ALG_BLOB_TOO_BIG ((NTSTATUS) 0xC0000352L)
+#endif
+
+#ifndef STATUS_PORT_NOT_SET
+# define STATUS_PORT_NOT_SET ((NTSTATUS) 0xC0000353L)
+#endif
+
+#ifndef STATUS_DEBUGGER_INACTIVE
+# define STATUS_DEBUGGER_INACTIVE ((NTSTATUS) 0xC0000354L)
+#endif
+
+#ifndef STATUS_DS_VERSION_CHECK_FAILURE
+# define STATUS_DS_VERSION_CHECK_FAILURE ((NTSTATUS) 0xC0000355L)
+#endif
+
+#ifndef STATUS_AUDITING_DISABLED
+# define STATUS_AUDITING_DISABLED ((NTSTATUS) 0xC0000356L)
+#endif
+
+#ifndef STATUS_PRENT4_MACHINE_ACCOUNT
+# define STATUS_PRENT4_MACHINE_ACCOUNT ((NTSTATUS) 0xC0000357L)
+#endif
+
+#ifndef STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER
+# define STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER ((NTSTATUS) 0xC0000358L)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_WIN_32
+# define STATUS_INVALID_IMAGE_WIN_32 ((NTSTATUS) 0xC0000359L)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_WIN_64
+# define STATUS_INVALID_IMAGE_WIN_64 ((NTSTATUS) 0xC000035AL)
+#endif
+
+#ifndef STATUS_BAD_BINDINGS
+# define STATUS_BAD_BINDINGS ((NTSTATUS) 0xC000035BL)
+#endif
+
+#ifndef STATUS_NETWORK_SESSION_EXPIRED
+# define STATUS_NETWORK_SESSION_EXPIRED ((NTSTATUS) 0xC000035CL)
+#endif
+
+#ifndef STATUS_APPHELP_BLOCK
+# define STATUS_APPHELP_BLOCK ((NTSTATUS) 0xC000035DL)
+#endif
+
+#ifndef STATUS_ALL_SIDS_FILTERED
+# define STATUS_ALL_SIDS_FILTERED ((NTSTATUS) 0xC000035EL)
+#endif
+
+#ifndef STATUS_NOT_SAFE_MODE_DRIVER
+# define STATUS_NOT_SAFE_MODE_DRIVER ((NTSTATUS) 0xC000035FL)
+#endif
+
+#ifndef STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT
+# define STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT ((NTSTATUS) 0xC0000361L)
+#endif
+
+#ifndef STATUS_ACCESS_DISABLED_BY_POLICY_PATH
+# define STATUS_ACCESS_DISABLED_BY_POLICY_PATH ((NTSTATUS) 0xC0000362L)
+#endif
+
+#ifndef STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER
+# define STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER ((NTSTATUS) 0xC0000363L)
+#endif
+
+#ifndef STATUS_ACCESS_DISABLED_BY_POLICY_OTHER
+# define STATUS_ACCESS_DISABLED_BY_POLICY_OTHER ((NTSTATUS) 0xC0000364L)
+#endif
+
+#ifndef STATUS_FAILED_DRIVER_ENTRY
+# define STATUS_FAILED_DRIVER_ENTRY ((NTSTATUS) 0xC0000365L)
+#endif
+
+#ifndef STATUS_DEVICE_ENUMERATION_ERROR
+# define STATUS_DEVICE_ENUMERATION_ERROR ((NTSTATUS) 0xC0000366L)
+#endif
+
+#ifndef STATUS_MOUNT_POINT_NOT_RESOLVED
+# define STATUS_MOUNT_POINT_NOT_RESOLVED ((NTSTATUS) 0xC0000368L)
+#endif
+
+#ifndef STATUS_INVALID_DEVICE_OBJECT_PARAMETER
+# define STATUS_INVALID_DEVICE_OBJECT_PARAMETER ((NTSTATUS) 0xC0000369L)
+#endif
+
+#ifndef STATUS_MCA_OCCURED
+# define STATUS_MCA_OCCURED ((NTSTATUS) 0xC000036AL)
+#endif
+
+#ifndef STATUS_DRIVER_BLOCKED_CRITICAL
+# define STATUS_DRIVER_BLOCKED_CRITICAL ((NTSTATUS) 0xC000036BL)
+#endif
+
+#ifndef STATUS_DRIVER_BLOCKED
+# define STATUS_DRIVER_BLOCKED ((NTSTATUS) 0xC000036CL)
+#endif
+
+#ifndef STATUS_DRIVER_DATABASE_ERROR
+# define STATUS_DRIVER_DATABASE_ERROR ((NTSTATUS) 0xC000036DL)
+#endif
+
+#ifndef STATUS_SYSTEM_HIVE_TOO_LARGE
+# define STATUS_SYSTEM_HIVE_TOO_LARGE ((NTSTATUS) 0xC000036EL)
+#endif
+
+#ifndef STATUS_INVALID_IMPORT_OF_NON_DLL
+# define STATUS_INVALID_IMPORT_OF_NON_DLL ((NTSTATUS) 0xC000036FL)
+#endif
+
+#ifndef STATUS_DS_SHUTTING_DOWN
+# define STATUS_DS_SHUTTING_DOWN ((NTSTATUS) 0x40000370L)
+#endif
+
+#ifndef STATUS_NO_SECRETS
+# define STATUS_NO_SECRETS ((NTSTATUS) 0xC0000371L)
+#endif
+
+#ifndef STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY
+# define STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY ((NTSTATUS) 0xC0000372L)
+#endif
+
+#ifndef STATUS_FAILED_STACK_SWITCH
+# define STATUS_FAILED_STACK_SWITCH ((NTSTATUS) 0xC0000373L)
+#endif
+
+#ifndef STATUS_HEAP_CORRUPTION
+# define STATUS_HEAP_CORRUPTION ((NTSTATUS) 0xC0000374L)
+#endif
+
+#ifndef STATUS_SMARTCARD_WRONG_PIN
+# define STATUS_SMARTCARD_WRONG_PIN ((NTSTATUS) 0xC0000380L)
+#endif
+
+#ifndef STATUS_SMARTCARD_CARD_BLOCKED
+# define STATUS_SMARTCARD_CARD_BLOCKED ((NTSTATUS) 0xC0000381L)
+#endif
+
+#ifndef STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED
+# define STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED ((NTSTATUS) 0xC0000382L)
+#endif
+
+#ifndef STATUS_SMARTCARD_NO_CARD
+# define STATUS_SMARTCARD_NO_CARD ((NTSTATUS) 0xC0000383L)
+#endif
+
+#ifndef STATUS_SMARTCARD_NO_KEY_CONTAINER
+# define STATUS_SMARTCARD_NO_KEY_CONTAINER ((NTSTATUS) 0xC0000384L)
+#endif
+
+#ifndef STATUS_SMARTCARD_NO_CERTIFICATE
+# define STATUS_SMARTCARD_NO_CERTIFICATE ((NTSTATUS) 0xC0000385L)
+#endif
+
+#ifndef STATUS_SMARTCARD_NO_KEYSET
+# define STATUS_SMARTCARD_NO_KEYSET ((NTSTATUS) 0xC0000386L)
+#endif
+
+#ifndef STATUS_SMARTCARD_IO_ERROR
+# define STATUS_SMARTCARD_IO_ERROR ((NTSTATUS) 0xC0000387L)
+#endif
+
+#ifndef STATUS_DOWNGRADE_DETECTED
+# define STATUS_DOWNGRADE_DETECTED ((NTSTATUS) 0xC0000388L)
+#endif
+
+#ifndef STATUS_SMARTCARD_CERT_REVOKED
+# define STATUS_SMARTCARD_CERT_REVOKED ((NTSTATUS) 0xC0000389L)
+#endif
+
+#ifndef STATUS_ISSUING_CA_UNTRUSTED
+# define STATUS_ISSUING_CA_UNTRUSTED ((NTSTATUS) 0xC000038AL)
+#endif
+
+#ifndef STATUS_REVOCATION_OFFLINE_C
+# define STATUS_REVOCATION_OFFLINE_C ((NTSTATUS) 0xC000038BL)
+#endif
+
+#ifndef STATUS_PKINIT_CLIENT_FAILURE
+# define STATUS_PKINIT_CLIENT_FAILURE ((NTSTATUS) 0xC000038CL)
+#endif
+
+#ifndef STATUS_SMARTCARD_CERT_EXPIRED
+# define STATUS_SMARTCARD_CERT_EXPIRED ((NTSTATUS) 0xC000038DL)
+#endif
+
+#ifndef STATUS_DRIVER_FAILED_PRIOR_UNLOAD
+# define STATUS_DRIVER_FAILED_PRIOR_UNLOAD ((NTSTATUS) 0xC000038EL)
+#endif
+
+#ifndef STATUS_SMARTCARD_SILENT_CONTEXT
+# define STATUS_SMARTCARD_SILENT_CONTEXT ((NTSTATUS) 0xC000038FL)
+#endif
+
+#ifndef STATUS_PER_USER_TRUST_QUOTA_EXCEEDED
+# define STATUS_PER_USER_TRUST_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000401L)
+#endif
+
+#ifndef STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED
+# define STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000402L)
+#endif
+
+#ifndef STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED
+# define STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000403L)
+#endif
+
+#ifndef STATUS_DS_NAME_NOT_UNIQUE
+# define STATUS_DS_NAME_NOT_UNIQUE ((NTSTATUS) 0xC0000404L)
+#endif
+
+#ifndef STATUS_DS_DUPLICATE_ID_FOUND
+# define STATUS_DS_DUPLICATE_ID_FOUND ((NTSTATUS) 0xC0000405L)
+#endif
+
+#ifndef STATUS_DS_GROUP_CONVERSION_ERROR
+# define STATUS_DS_GROUP_CONVERSION_ERROR ((NTSTATUS) 0xC0000406L)
+#endif
+
+#ifndef STATUS_VOLSNAP_PREPARE_HIBERNATE
+# define STATUS_VOLSNAP_PREPARE_HIBERNATE ((NTSTATUS) 0xC0000407L)
+#endif
+
+#ifndef STATUS_USER2USER_REQUIRED
+# define STATUS_USER2USER_REQUIRED ((NTSTATUS) 0xC0000408L)
+#endif
+
+#ifndef STATUS_STACK_BUFFER_OVERRUN
+# define STATUS_STACK_BUFFER_OVERRUN ((NTSTATUS) 0xC0000409L)
+#endif
+
+#ifndef STATUS_NO_S4U_PROT_SUPPORT
+# define STATUS_NO_S4U_PROT_SUPPORT ((NTSTATUS) 0xC000040AL)
+#endif
+
+#ifndef STATUS_CROSSREALM_DELEGATION_FAILURE
+# define STATUS_CROSSREALM_DELEGATION_FAILURE ((NTSTATUS) 0xC000040BL)
+#endif
+
+#ifndef STATUS_REVOCATION_OFFLINE_KDC
+# define STATUS_REVOCATION_OFFLINE_KDC ((NTSTATUS) 0xC000040CL)
+#endif
+
+#ifndef STATUS_ISSUING_CA_UNTRUSTED_KDC
+# define STATUS_ISSUING_CA_UNTRUSTED_KDC ((NTSTATUS) 0xC000040DL)
+#endif
+
+#ifndef STATUS_KDC_CERT_EXPIRED
+# define STATUS_KDC_CERT_EXPIRED ((NTSTATUS) 0xC000040EL)
+#endif
+
+#ifndef STATUS_KDC_CERT_REVOKED
+# define STATUS_KDC_CERT_REVOKED ((NTSTATUS) 0xC000040FL)
+#endif
+
+#ifndef STATUS_PARAMETER_QUOTA_EXCEEDED
+# define STATUS_PARAMETER_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000410L)
+#endif
+
+#ifndef STATUS_HIBERNATION_FAILURE
+# define STATUS_HIBERNATION_FAILURE ((NTSTATUS) 0xC0000411L)
+#endif
+
+#ifndef STATUS_DELAY_LOAD_FAILED
+# define STATUS_DELAY_LOAD_FAILED ((NTSTATUS) 0xC0000412L)
+#endif
+
+#ifndef STATUS_AUTHENTICATION_FIREWALL_FAILED
+# define STATUS_AUTHENTICATION_FIREWALL_FAILED ((NTSTATUS) 0xC0000413L)
+#endif
+
+#ifndef STATUS_VDM_DISALLOWED
+# define STATUS_VDM_DISALLOWED ((NTSTATUS) 0xC0000414L)
+#endif
+
+#ifndef STATUS_HUNG_DISPLAY_DRIVER_THREAD
+# define STATUS_HUNG_DISPLAY_DRIVER_THREAD ((NTSTATUS) 0xC0000415L)
+#endif
+
+#ifndef STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE
+# define STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE ((NTSTATUS) 0xC0000416L)
+#endif
+
+#ifndef STATUS_INVALID_CRUNTIME_PARAMETER
+# define STATUS_INVALID_CRUNTIME_PARAMETER ((NTSTATUS) 0xC0000417L)
+#endif
+
+#ifndef STATUS_NTLM_BLOCKED
+# define STATUS_NTLM_BLOCKED ((NTSTATUS) 0xC0000418L)
+#endif
+
+#ifndef STATUS_DS_SRC_SID_EXISTS_IN_FOREST
+# define STATUS_DS_SRC_SID_EXISTS_IN_FOREST ((NTSTATUS) 0xC0000419L)
+#endif
+
+#ifndef STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST
+# define STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST ((NTSTATUS) 0xC000041AL)
+#endif
+
+#ifndef STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST
+# define STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST ((NTSTATUS) 0xC000041BL)
+#endif
+
+#ifndef STATUS_INVALID_USER_PRINCIPAL_NAME
+# define STATUS_INVALID_USER_PRINCIPAL_NAME ((NTSTATUS) 0xC000041CL)
+#endif
+
+#ifndef STATUS_FATAL_USER_CALLBACK_EXCEPTION
+# define STATUS_FATAL_USER_CALLBACK_EXCEPTION ((NTSTATUS) 0xC000041DL)
+#endif
+
+#ifndef STATUS_ASSERTION_FAILURE
+# define STATUS_ASSERTION_FAILURE ((NTSTATUS) 0xC0000420L)
+#endif
+
+#ifndef STATUS_VERIFIER_STOP
+# define STATUS_VERIFIER_STOP ((NTSTATUS) 0xC0000421L)
+#endif
+
+#ifndef STATUS_CALLBACK_POP_STACK
+# define STATUS_CALLBACK_POP_STACK ((NTSTATUS) 0xC0000423L)
+#endif
+
+#ifndef STATUS_INCOMPATIBLE_DRIVER_BLOCKED
+# define STATUS_INCOMPATIBLE_DRIVER_BLOCKED ((NTSTATUS) 0xC0000424L)
+#endif
+
+#ifndef STATUS_HIVE_UNLOADED
+# define STATUS_HIVE_UNLOADED ((NTSTATUS) 0xC0000425L)
+#endif
+
+#ifndef STATUS_COMPRESSION_DISABLED
+# define STATUS_COMPRESSION_DISABLED ((NTSTATUS) 0xC0000426L)
+#endif
+
+#ifndef STATUS_FILE_SYSTEM_LIMITATION
+# define STATUS_FILE_SYSTEM_LIMITATION ((NTSTATUS) 0xC0000427L)
+#endif
+
+#ifndef STATUS_INVALID_IMAGE_HASH
+# define STATUS_INVALID_IMAGE_HASH ((NTSTATUS) 0xC0000428L)
+#endif
+
+#ifndef STATUS_NOT_CAPABLE
+# define STATUS_NOT_CAPABLE ((NTSTATUS) 0xC0000429L)
+#endif
+
+#ifndef STATUS_REQUEST_OUT_OF_SEQUENCE
+# define STATUS_REQUEST_OUT_OF_SEQUENCE ((NTSTATUS) 0xC000042AL)
+#endif
+
+#ifndef STATUS_IMPLEMENTATION_LIMIT
+# define STATUS_IMPLEMENTATION_LIMIT ((NTSTATUS) 0xC000042BL)
+#endif
+
+#ifndef STATUS_ELEVATION_REQUIRED
+# define STATUS_ELEVATION_REQUIRED ((NTSTATUS) 0xC000042CL)
+#endif
+
+#ifndef STATUS_NO_SECURITY_CONTEXT
+# define STATUS_NO_SECURITY_CONTEXT ((NTSTATUS) 0xC000042DL)
+#endif
+
+#ifndef STATUS_PKU2U_CERT_FAILURE
+# define STATUS_PKU2U_CERT_FAILURE ((NTSTATUS) 0xC000042FL)
+#endif
+
+#ifndef STATUS_BEYOND_VDL
+# define STATUS_BEYOND_VDL ((NTSTATUS) 0xC0000432L)
+#endif
+
+#ifndef STATUS_ENCOUNTERED_WRITE_IN_PROGRESS
+# define STATUS_ENCOUNTERED_WRITE_IN_PROGRESS ((NTSTATUS) 0xC0000433L)
+#endif
+
+#ifndef STATUS_PTE_CHANGED
+# define STATUS_PTE_CHANGED ((NTSTATUS) 0xC0000434L)
+#endif
+
+#ifndef STATUS_PURGE_FAILED
+# define STATUS_PURGE_FAILED ((NTSTATUS) 0xC0000435L)
+#endif
+
+#ifndef STATUS_CRED_REQUIRES_CONFIRMATION
+# define STATUS_CRED_REQUIRES_CONFIRMATION ((NTSTATUS) 0xC0000440L)
+#endif
+
+#ifndef STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE
+# define STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE ((NTSTATUS) 0xC0000441L)
+#endif
+
+#ifndef STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER
+# define STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER ((NTSTATUS) 0xC0000442L)
+#endif
+
+#ifndef STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE
+# define STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE ((NTSTATUS) 0xC0000443L)
+#endif
+
+#ifndef STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE
+# define STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE ((NTSTATUS) 0xC0000444L)
+#endif
+
+#ifndef STATUS_CS_ENCRYPTION_FILE_NOT_CSE
+# define STATUS_CS_ENCRYPTION_FILE_NOT_CSE ((NTSTATUS) 0xC0000445L)
+#endif
+
+#ifndef STATUS_INVALID_LABEL
+# define STATUS_INVALID_LABEL ((NTSTATUS) 0xC0000446L)
+#endif
+
+#ifndef STATUS_DRIVER_PROCESS_TERMINATED
+# define STATUS_DRIVER_PROCESS_TERMINATED ((NTSTATUS) 0xC0000450L)
+#endif
+
+#ifndef STATUS_AMBIGUOUS_SYSTEM_DEVICE
+# define STATUS_AMBIGUOUS_SYSTEM_DEVICE ((NTSTATUS) 0xC0000451L)
+#endif
+
+#ifndef STATUS_SYSTEM_DEVICE_NOT_FOUND
+# define STATUS_SYSTEM_DEVICE_NOT_FOUND ((NTSTATUS) 0xC0000452L)
+#endif
+
+#ifndef STATUS_RESTART_BOOT_APPLICATION
+# define STATUS_RESTART_BOOT_APPLICATION ((NTSTATUS) 0xC0000453L)
+#endif
+
+#ifndef STATUS_INSUFFICIENT_NVRAM_RESOURCES
+# define STATUS_INSUFFICIENT_NVRAM_RESOURCES ((NTSTATUS) 0xC0000454L)
+#endif
+
+#ifndef STATUS_INVALID_TASK_NAME
+# define STATUS_INVALID_TASK_NAME ((NTSTATUS) 0xC0000500L)
+#endif
+
+#ifndef STATUS_INVALID_TASK_INDEX
+# define STATUS_INVALID_TASK_INDEX ((NTSTATUS) 0xC0000501L)
+#endif
+
+#ifndef STATUS_THREAD_ALREADY_IN_TASK
+# define STATUS_THREAD_ALREADY_IN_TASK ((NTSTATUS) 0xC0000502L)
+#endif
+
+#ifndef STATUS_CALLBACK_BYPASS
+# define STATUS_CALLBACK_BYPASS ((NTSTATUS) 0xC0000503L)
+#endif
+
+#ifndef STATUS_FAIL_FAST_EXCEPTION
+# define STATUS_FAIL_FAST_EXCEPTION ((NTSTATUS) 0xC0000602L)
+#endif
+
+#ifndef STATUS_IMAGE_CERT_REVOKED
+# define STATUS_IMAGE_CERT_REVOKED ((NTSTATUS) 0xC0000603L)
+#endif
+
+#ifndef STATUS_PORT_CLOSED
+# define STATUS_PORT_CLOSED ((NTSTATUS) 0xC0000700L)
+#endif
+
+#ifndef STATUS_MESSAGE_LOST
+# define STATUS_MESSAGE_LOST ((NTSTATUS) 0xC0000701L)
+#endif
+
+#ifndef STATUS_INVALID_MESSAGE
+# define STATUS_INVALID_MESSAGE ((NTSTATUS) 0xC0000702L)
+#endif
+
+#ifndef STATUS_REQUEST_CANCELED
+# define STATUS_REQUEST_CANCELED ((NTSTATUS) 0xC0000703L)
+#endif
+
+#ifndef STATUS_RECURSIVE_DISPATCH
+# define STATUS_RECURSIVE_DISPATCH ((NTSTATUS) 0xC0000704L)
+#endif
+
+#ifndef STATUS_LPC_RECEIVE_BUFFER_EXPECTED
+# define STATUS_LPC_RECEIVE_BUFFER_EXPECTED ((NTSTATUS) 0xC0000705L)
+#endif
+
+#ifndef STATUS_LPC_INVALID_CONNECTION_USAGE
+# define STATUS_LPC_INVALID_CONNECTION_USAGE ((NTSTATUS) 0xC0000706L)
+#endif
+
+#ifndef STATUS_LPC_REQUESTS_NOT_ALLOWED
+# define STATUS_LPC_REQUESTS_NOT_ALLOWED ((NTSTATUS) 0xC0000707L)
+#endif
+
+#ifndef STATUS_RESOURCE_IN_USE
+# define STATUS_RESOURCE_IN_USE ((NTSTATUS) 0xC0000708L)
+#endif
+
+#ifndef STATUS_HARDWARE_MEMORY_ERROR
+# define STATUS_HARDWARE_MEMORY_ERROR ((NTSTATUS) 0xC0000709L)
+#endif
+
+#ifndef STATUS_THREADPOOL_HANDLE_EXCEPTION
+# define STATUS_THREADPOOL_HANDLE_EXCEPTION ((NTSTATUS) 0xC000070AL)
+#endif
+
+#ifndef STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED
+# define STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED ((NTSTATUS) 0xC000070BL)
+#endif
+
+#ifndef STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED
+# define STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED ((NTSTATUS) 0xC000070CL)
+#endif
+
+#ifndef STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED
+# define STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED ((NTSTATUS) 0xC000070DL)
+#endif
+
+#ifndef STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED
+# define STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED ((NTSTATUS) 0xC000070EL)
+#endif
+
+#ifndef STATUS_THREADPOOL_RELEASED_DURING_OPERATION
+# define STATUS_THREADPOOL_RELEASED_DURING_OPERATION ((NTSTATUS) 0xC000070FL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING
+# define STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING ((NTSTATUS) 0xC0000710L)
+#endif
+
+#ifndef STATUS_APC_RETURNED_WHILE_IMPERSONATING
+# define STATUS_APC_RETURNED_WHILE_IMPERSONATING ((NTSTATUS) 0xC0000711L)
+#endif
+
+#ifndef STATUS_PROCESS_IS_PROTECTED
+# define STATUS_PROCESS_IS_PROTECTED ((NTSTATUS) 0xC0000712L)
+#endif
+
+#ifndef STATUS_MCA_EXCEPTION
+# define STATUS_MCA_EXCEPTION ((NTSTATUS) 0xC0000713L)
+#endif
+
+#ifndef STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE
+# define STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE ((NTSTATUS) 0xC0000714L)
+#endif
+
+#ifndef STATUS_SYMLINK_CLASS_DISABLED
+# define STATUS_SYMLINK_CLASS_DISABLED ((NTSTATUS) 0xC0000715L)
+#endif
+
+#ifndef STATUS_INVALID_IDN_NORMALIZATION
+# define STATUS_INVALID_IDN_NORMALIZATION ((NTSTATUS) 0xC0000716L)
+#endif
+
+#ifndef STATUS_NO_UNICODE_TRANSLATION
+# define STATUS_NO_UNICODE_TRANSLATION ((NTSTATUS) 0xC0000717L)
+#endif
+
+#ifndef STATUS_ALREADY_REGISTERED
+# define STATUS_ALREADY_REGISTERED ((NTSTATUS) 0xC0000718L)
+#endif
+
+#ifndef STATUS_CONTEXT_MISMATCH
+# define STATUS_CONTEXT_MISMATCH ((NTSTATUS) 0xC0000719L)
+#endif
+
+#ifndef STATUS_PORT_ALREADY_HAS_COMPLETION_LIST
+# define STATUS_PORT_ALREADY_HAS_COMPLETION_LIST ((NTSTATUS) 0xC000071AL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_THREAD_PRIORITY
+# define STATUS_CALLBACK_RETURNED_THREAD_PRIORITY ((NTSTATUS) 0xC000071BL)
+#endif
+
+#ifndef STATUS_INVALID_THREAD
+# define STATUS_INVALID_THREAD ((NTSTATUS) 0xC000071CL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_TRANSACTION
+# define STATUS_CALLBACK_RETURNED_TRANSACTION ((NTSTATUS) 0xC000071DL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_LDR_LOCK
+# define STATUS_CALLBACK_RETURNED_LDR_LOCK ((NTSTATUS) 0xC000071EL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_LANG
+# define STATUS_CALLBACK_RETURNED_LANG ((NTSTATUS) 0xC000071FL)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_PRI_BACK
+# define STATUS_CALLBACK_RETURNED_PRI_BACK ((NTSTATUS) 0xC0000720L)
+#endif
+
+#ifndef STATUS_CALLBACK_RETURNED_THREAD_AFFINITY
+# define STATUS_CALLBACK_RETURNED_THREAD_AFFINITY ((NTSTATUS) 0xC0000721L)
+#endif
+
+#ifndef STATUS_DISK_REPAIR_DISABLED
+# define STATUS_DISK_REPAIR_DISABLED ((NTSTATUS) 0xC0000800L)
+#endif
+
+#ifndef STATUS_DS_DOMAIN_RENAME_IN_PROGRESS
+# define STATUS_DS_DOMAIN_RENAME_IN_PROGRESS ((NTSTATUS) 0xC0000801L)
+#endif
+
+#ifndef STATUS_DISK_QUOTA_EXCEEDED
+# define STATUS_DISK_QUOTA_EXCEEDED ((NTSTATUS) 0xC0000802L)
+#endif
+
+#ifndef STATUS_DATA_LOST_REPAIR
+# define STATUS_DATA_LOST_REPAIR ((NTSTATUS) 0x80000803L)
+#endif
+
+#ifndef STATUS_CONTENT_BLOCKED
+# define STATUS_CONTENT_BLOCKED ((NTSTATUS) 0xC0000804L)
+#endif
+
+#ifndef STATUS_BAD_CLUSTERS
+# define STATUS_BAD_CLUSTERS ((NTSTATUS) 0xC0000805L)
+#endif
+
+#ifndef STATUS_VOLUME_DIRTY
+# define STATUS_VOLUME_DIRTY ((NTSTATUS) 0xC0000806L)
+#endif
+
+#ifndef STATUS_FILE_CHECKED_OUT
+# define STATUS_FILE_CHECKED_OUT ((NTSTATUS) 0xC0000901L)
+#endif
+
+#ifndef STATUS_CHECKOUT_REQUIRED
+# define STATUS_CHECKOUT_REQUIRED ((NTSTATUS) 0xC0000902L)
+#endif
+
+#ifndef STATUS_BAD_FILE_TYPE
+# define STATUS_BAD_FILE_TYPE ((NTSTATUS) 0xC0000903L)
+#endif
+
+#ifndef STATUS_FILE_TOO_LARGE
+# define STATUS_FILE_TOO_LARGE ((NTSTATUS) 0xC0000904L)
+#endif
+
+#ifndef STATUS_FORMS_AUTH_REQUIRED
+# define STATUS_FORMS_AUTH_REQUIRED ((NTSTATUS) 0xC0000905L)
+#endif
+
+#ifndef STATUS_VIRUS_INFECTED
+# define STATUS_VIRUS_INFECTED ((NTSTATUS) 0xC0000906L)
+#endif
+
+#ifndef STATUS_VIRUS_DELETED
+# define STATUS_VIRUS_DELETED ((NTSTATUS) 0xC0000907L)
+#endif
+
+#ifndef STATUS_BAD_MCFG_TABLE
+# define STATUS_BAD_MCFG_TABLE ((NTSTATUS) 0xC0000908L)
+#endif
+
+#ifndef STATUS_CANNOT_BREAK_OPLOCK
+# define STATUS_CANNOT_BREAK_OPLOCK ((NTSTATUS) 0xC0000909L)
+#endif
+
+#ifndef STATUS_WOW_ASSERTION
+# define STATUS_WOW_ASSERTION ((NTSTATUS) 0xC0009898L)
+#endif
+
+#ifndef STATUS_INVALID_SIGNATURE
+# define STATUS_INVALID_SIGNATURE ((NTSTATUS) 0xC000A000L)
+#endif
+
+#ifndef STATUS_HMAC_NOT_SUPPORTED
+# define STATUS_HMAC_NOT_SUPPORTED ((NTSTATUS) 0xC000A001L)
+#endif
+
+#ifndef STATUS_AUTH_TAG_MISMATCH
+# define STATUS_AUTH_TAG_MISMATCH ((NTSTATUS) 0xC000A002L)
+#endif
+
+#ifndef STATUS_IPSEC_QUEUE_OVERFLOW
+# define STATUS_IPSEC_QUEUE_OVERFLOW ((NTSTATUS) 0xC000A010L)
+#endif
+
+#ifndef STATUS_ND_QUEUE_OVERFLOW
+# define STATUS_ND_QUEUE_OVERFLOW ((NTSTATUS) 0xC000A011L)
+#endif
+
+#ifndef STATUS_HOPLIMIT_EXCEEDED
+# define STATUS_HOPLIMIT_EXCEEDED ((NTSTATUS) 0xC000A012L)
+#endif
+
+#ifndef STATUS_PROTOCOL_NOT_SUPPORTED
+# define STATUS_PROTOCOL_NOT_SUPPORTED ((NTSTATUS) 0xC000A013L)
+#endif
+
+#ifndef STATUS_FASTPATH_REJECTED
+# define STATUS_FASTPATH_REJECTED ((NTSTATUS) 0xC000A014L)
+#endif
+
+#ifndef STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED
+# define STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED ((NTSTATUS) 0xC000A080L)
+#endif
+
+#ifndef STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR
+# define STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR ((NTSTATUS) 0xC000A081L)
+#endif
+
+#ifndef STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR
+# define STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR ((NTSTATUS) 0xC000A082L)
+#endif
+
+#ifndef STATUS_XML_PARSE_ERROR
+# define STATUS_XML_PARSE_ERROR ((NTSTATUS) 0xC000A083L)
+#endif
+
+#ifndef STATUS_XMLDSIG_ERROR
+# define STATUS_XMLDSIG_ERROR ((NTSTATUS) 0xC000A084L)
+#endif
+
+#ifndef STATUS_WRONG_COMPARTMENT
+# define STATUS_WRONG_COMPARTMENT ((NTSTATUS) 0xC000A085L)
+#endif
+
+#ifndef STATUS_AUTHIP_FAILURE
+# define STATUS_AUTHIP_FAILURE ((NTSTATUS) 0xC000A086L)
+#endif
+
+#ifndef STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS
+# define STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS ((NTSTATUS) 0xC000A087L)
+#endif
+
+#ifndef STATUS_DS_OID_NOT_FOUND
+# define STATUS_DS_OID_NOT_FOUND ((NTSTATUS) 0xC000A088L)
+#endif
+
+#ifndef STATUS_HASH_NOT_SUPPORTED
+# define STATUS_HASH_NOT_SUPPORTED ((NTSTATUS) 0xC000A100L)
+#endif
+
+#ifndef STATUS_HASH_NOT_PRESENT
+# define STATUS_HASH_NOT_PRESENT ((NTSTATUS) 0xC000A101L)
+#endif
+
+/* This is not the NTSTATUS_FROM_WIN32 that the DDK provides, because the */
+/* DDK got it wrong! */
+#ifdef NTSTATUS_FROM_WIN32
+# undef NTSTATUS_FROM_WIN32
+#endif
+#define NTSTATUS_FROM_WIN32(error) ((NTSTATUS) (error) <= 0 ? \
+        ((NTSTATUS) (error)) : ((NTSTATUS) (((error) & 0x0000FFFF) | \
+        (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_WARNING)))
+
+#ifndef JOB_OBJECT_LIMIT_PROCESS_MEMORY
+# define JOB_OBJECT_LIMIT_PROCESS_MEMORY             0x00000100
+#endif
+#ifndef JOB_OBJECT_LIMIT_JOB_MEMORY
+# define JOB_OBJECT_LIMIT_JOB_MEMORY                 0x00000200
+#endif
+#ifndef JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION
+# define JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION 0x00000400
+#endif
+#ifndef JOB_OBJECT_LIMIT_BREAKAWAY_OK
+# define JOB_OBJECT_LIMIT_BREAKAWAY_OK               0x00000800
+#endif
+#ifndef JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK
+# define JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK        0x00001000
+#endif
+#ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+# define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE          0x00002000
+#endif
+
+/* from winternl.h */
+typedef struct _UNICODE_STRING {
+  USHORT Length;
+  USHORT MaximumLength;
+  PWSTR  Buffer;
+} UNICODE_STRING, *PUNICODE_STRING;
+
+typedef const UNICODE_STRING *PCUNICODE_STRING;
+
+/* from ntifs.h */
+#ifndef DEVICE_TYPE
+# define DEVICE_TYPE DWORD
+#endif
+
+#ifndef VOLUME_NAME_DOS
+# define VOLUME_NAME_DOS 0x0
+#endif
+
+#ifndef MAPVK_VK_TO_VSC
+# define MAPVK_VK_TO_VSC (0)
+#endif
+
+/* MinGW already has a definition for REPARSE_DATA_BUFFER, but mingw-w64 does
+ * not.
+ */
+#if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
+  typedef struct _REPARSE_DATA_BUFFER {
+    ULONG  ReparseTag;
+    USHORT ReparseDataLength;
+    USHORT Reserved;
+    union {
+      struct {
+        USHORT SubstituteNameOffset;
+        USHORT SubstituteNameLength;
+        USHORT PrintNameOffset;
+        USHORT PrintNameLength;
+        ULONG Flags;
+        WCHAR PathBuffer[1];
+      } SymbolicLinkReparseBuffer;
+      struct {
+        USHORT SubstituteNameOffset;
+        USHORT SubstituteNameLength;
+        USHORT PrintNameOffset;
+        USHORT PrintNameLength;
+        WCHAR PathBuffer[1];
+      } MountPointReparseBuffer;
+      struct {
+        UCHAR  DataBuffer[1];
+      } GenericReparseBuffer;
+    };
+  } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+#endif
+
+typedef struct _IO_STATUS_BLOCK {
+  union {
+    NTSTATUS Status;
+    PVOID Pointer;
+  };
+  ULONG_PTR Information;
+} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
+
+typedef enum _FILE_INFORMATION_CLASS {
+  FileDirectoryInformation = 1,
+  FileFullDirectoryInformation,
+  FileBothDirectoryInformation,
+  FileBasicInformation,
+  FileStandardInformation,
+  FileInternalInformation,
+  FileEaInformation,
+  FileAccessInformation,
+  FileNameInformation,
+  FileRenameInformation,
+  FileLinkInformation,
+  FileNamesInformation,
+  FileDispositionInformation,
+  FilePositionInformation,
+  FileFullEaInformation,
+  FileModeInformation,
+  FileAlignmentInformation,
+  FileAllInformation,
+  FileAllocationInformation,
+  FileEndOfFileInformation,
+  FileAlternateNameInformation,
+  FileStreamInformation,
+  FilePipeInformation,
+  FilePipeLocalInformation,
+  FilePipeRemoteInformation,
+  FileMailslotQueryInformation,
+  FileMailslotSetInformation,
+  FileCompressionInformation,
+  FileObjectIdInformation,
+  FileCompletionInformation,
+  FileMoveClusterInformation,
+  FileQuotaInformation,
+  FileReparsePointInformation,
+  FileNetworkOpenInformation,
+  FileAttributeTagInformation,
+  FileTrackingInformation,
+  FileIdBothDirectoryInformation,
+  FileIdFullDirectoryInformation,
+  FileValidDataLengthInformation,
+  FileShortNameInformation,
+  FileIoCompletionNotificationInformation,
+  FileIoStatusBlockRangeInformation,
+  FileIoPriorityHintInformation,
+  FileSfioReserveInformation,
+  FileSfioVolumeInformation,
+  FileHardLinkInformation,
+  FileProcessIdsUsingFileInformation,
+  FileNormalizedNameInformation,
+  FileNetworkPhysicalNameInformation,
+  FileIdGlobalTxDirectoryInformation,
+  FileIsRemoteDeviceInformation,
+  FileAttributeCacheInformation,
+  FileNumaNodeInformation,
+  FileStandardLinkInformation,
+  FileRemoteProtocolInformation,
+  FileMaximumInformation
+} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
+
+typedef struct _FILE_DIRECTORY_INFORMATION {
+  ULONG NextEntryOffset;
+  ULONG FileIndex;
+  LARGE_INTEGER CreationTime;
+  LARGE_INTEGER LastAccessTime;
+  LARGE_INTEGER LastWriteTime;
+  LARGE_INTEGER ChangeTime;
+  LARGE_INTEGER EndOfFile;
+  LARGE_INTEGER AllocationSize;
+  ULONG FileAttributes;
+  ULONG FileNameLength;
+  WCHAR FileName[1];
+} FILE_DIRECTORY_INFORMATION, *PFILE_DIRECTORY_INFORMATION;
+
+typedef struct _FILE_BOTH_DIR_INFORMATION {
+  ULONG NextEntryOffset;
+  ULONG FileIndex;
+  LARGE_INTEGER CreationTime;
+  LARGE_INTEGER LastAccessTime;
+  LARGE_INTEGER LastWriteTime;
+  LARGE_INTEGER ChangeTime;
+  LARGE_INTEGER EndOfFile;
+  LARGE_INTEGER AllocationSize;
+  ULONG FileAttributes;
+  ULONG FileNameLength;
+  ULONG EaSize;
+  CCHAR ShortNameLength;
+  WCHAR ShortName[12];
+  WCHAR FileName[1];
+} FILE_BOTH_DIR_INFORMATION, *PFILE_BOTH_DIR_INFORMATION;
+
+typedef struct _FILE_BASIC_INFORMATION {
+  LARGE_INTEGER CreationTime;
+  LARGE_INTEGER LastAccessTime;
+  LARGE_INTEGER LastWriteTime;
+  LARGE_INTEGER ChangeTime;
+  DWORD FileAttributes;
+} FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION;
+
+typedef struct _FILE_STANDARD_INFORMATION {
+  LARGE_INTEGER AllocationSize;
+  LARGE_INTEGER EndOfFile;
+  ULONG         NumberOfLinks;
+  BOOLEAN       DeletePending;
+  BOOLEAN       Directory;
+} FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION;
+
+typedef struct _FILE_INTERNAL_INFORMATION {
+  LARGE_INTEGER IndexNumber;
+} FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION;
+
+typedef struct _FILE_EA_INFORMATION {
+  ULONG EaSize;
+} FILE_EA_INFORMATION, *PFILE_EA_INFORMATION;
+
+typedef struct _FILE_ACCESS_INFORMATION {
+  ACCESS_MASK AccessFlags;
+} FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION;
+
+typedef struct _FILE_POSITION_INFORMATION {
+  LARGE_INTEGER CurrentByteOffset;
+} FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION;
+
+typedef struct _FILE_MODE_INFORMATION {
+  ULONG Mode;
+} FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION;
+
+typedef struct _FILE_ALIGNMENT_INFORMATION {
+  ULONG AlignmentRequirement;
+} FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION;
+
+typedef struct _FILE_NAME_INFORMATION {
+  ULONG FileNameLength;
+  WCHAR FileName[1];
+} FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION;
+
+typedef struct _FILE_END_OF_FILE_INFORMATION {
+  LARGE_INTEGER  EndOfFile;
+} FILE_END_OF_FILE_INFORMATION, *PFILE_END_OF_FILE_INFORMATION;
+
+typedef struct _FILE_ALL_INFORMATION {
+  FILE_BASIC_INFORMATION     BasicInformation;
+  FILE_STANDARD_INFORMATION  StandardInformation;
+  FILE_INTERNAL_INFORMATION  InternalInformation;
+  FILE_EA_INFORMATION        EaInformation;
+  FILE_ACCESS_INFORMATION    AccessInformation;
+  FILE_POSITION_INFORMATION  PositionInformation;
+  FILE_MODE_INFORMATION      ModeInformation;
+  FILE_ALIGNMENT_INFORMATION AlignmentInformation;
+  FILE_NAME_INFORMATION      NameInformation;
+} FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION;
+
+typedef struct _FILE_DISPOSITION_INFORMATION {
+  BOOLEAN DeleteFile;
+} FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION;
+
+typedef struct _FILE_PIPE_LOCAL_INFORMATION {
+  ULONG NamedPipeType;
+  ULONG NamedPipeConfiguration;
+  ULONG MaximumInstances;
+  ULONG CurrentInstances;
+  ULONG InboundQuota;
+  ULONG ReadDataAvailable;
+  ULONG OutboundQuota;
+  ULONG WriteQuotaAvailable;
+  ULONG NamedPipeState;
+  ULONG NamedPipeEnd;
+} FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
+
+#define FILE_SYNCHRONOUS_IO_ALERT               0x00000010
+#define FILE_SYNCHRONOUS_IO_NONALERT            0x00000020
+
+typedef enum _FS_INFORMATION_CLASS {
+  FileFsVolumeInformation       = 1,
+  FileFsLabelInformation        = 2,
+  FileFsSizeInformation         = 3,
+  FileFsDeviceInformation       = 4,
+  FileFsAttributeInformation    = 5,
+  FileFsControlInformation      = 6,
+  FileFsFullSizeInformation     = 7,
+  FileFsObjectIdInformation     = 8,
+  FileFsDriverPathInformation   = 9,
+  FileFsVolumeFlagsInformation  = 10,
+  FileFsSectorSizeInformation   = 11
+} FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS;
+
+typedef struct _FILE_FS_VOLUME_INFORMATION {
+  LARGE_INTEGER VolumeCreationTime;
+  ULONG         VolumeSerialNumber;
+  ULONG         VolumeLabelLength;
+  BOOLEAN       SupportsObjects;
+  WCHAR         VolumeLabel[1];
+} FILE_FS_VOLUME_INFORMATION, *PFILE_FS_VOLUME_INFORMATION;
+
+typedef struct _FILE_FS_LABEL_INFORMATION {
+  ULONG VolumeLabelLength;
+  WCHAR VolumeLabel[1];
+} FILE_FS_LABEL_INFORMATION, *PFILE_FS_LABEL_INFORMATION;
+
+typedef struct _FILE_FS_SIZE_INFORMATION {
+  LARGE_INTEGER TotalAllocationUnits;
+  LARGE_INTEGER AvailableAllocationUnits;
+  ULONG         SectorsPerAllocationUnit;
+  ULONG         BytesPerSector;
+} FILE_FS_SIZE_INFORMATION, *PFILE_FS_SIZE_INFORMATION;
+
+typedef struct _FILE_FS_DEVICE_INFORMATION {
+  DEVICE_TYPE DeviceType;
+  ULONG       Characteristics;
+} FILE_FS_DEVICE_INFORMATION, *PFILE_FS_DEVICE_INFORMATION;
+
+typedef struct _FILE_FS_ATTRIBUTE_INFORMATION {
+  ULONG FileSystemAttributes;
+  LONG  MaximumComponentNameLength;
+  ULONG FileSystemNameLength;
+  WCHAR FileSystemName[1];
+} FILE_FS_ATTRIBUTE_INFORMATION, *PFILE_FS_ATTRIBUTE_INFORMATION;
+
+typedef struct _FILE_FS_CONTROL_INFORMATION {
+  LARGE_INTEGER FreeSpaceStartFiltering;
+  LARGE_INTEGER FreeSpaceThreshold;
+  LARGE_INTEGER FreeSpaceStopFiltering;
+  LARGE_INTEGER DefaultQuotaThreshold;
+  LARGE_INTEGER DefaultQuotaLimit;
+  ULONG         FileSystemControlFlags;
+} FILE_FS_CONTROL_INFORMATION, *PFILE_FS_CONTROL_INFORMATION;
+
+typedef struct _FILE_FS_FULL_SIZE_INFORMATION {
+  LARGE_INTEGER TotalAllocationUnits;
+  LARGE_INTEGER CallerAvailableAllocationUnits;
+  LARGE_INTEGER ActualAvailableAllocationUnits;
+  ULONG         SectorsPerAllocationUnit;
+  ULONG         BytesPerSector;
+} FILE_FS_FULL_SIZE_INFORMATION, *PFILE_FS_FULL_SIZE_INFORMATION;
+
+typedef struct _FILE_FS_OBJECTID_INFORMATION {
+  UCHAR ObjectId[16];
+  UCHAR ExtendedInfo[48];
+} FILE_FS_OBJECTID_INFORMATION, *PFILE_FS_OBJECTID_INFORMATION;
+
+typedef struct _FILE_FS_DRIVER_PATH_INFORMATION {
+  BOOLEAN DriverInPath;
+  ULONG   DriverNameLength;
+  WCHAR   DriverName[1];
+} FILE_FS_DRIVER_PATH_INFORMATION, *PFILE_FS_DRIVER_PATH_INFORMATION;
+
+typedef struct _FILE_FS_VOLUME_FLAGS_INFORMATION {
+  ULONG Flags;
+} FILE_FS_VOLUME_FLAGS_INFORMATION, *PFILE_FS_VOLUME_FLAGS_INFORMATION;
+
+typedef struct _FILE_FS_SECTOR_SIZE_INFORMATION {
+  ULONG LogicalBytesPerSector;
+  ULONG PhysicalBytesPerSectorForAtomicity;
+  ULONG PhysicalBytesPerSectorForPerformance;
+  ULONG FileSystemEffectivePhysicalBytesPerSectorForAtomicity;
+  ULONG Flags;
+  ULONG ByteOffsetForSectorAlignment;
+  ULONG ByteOffsetForPartitionAlignment;
+} FILE_FS_SECTOR_SIZE_INFORMATION, *PFILE_FS_SECTOR_SIZE_INFORMATION;
+
+typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
+    LARGE_INTEGER IdleTime;
+    LARGE_INTEGER KernelTime;
+    LARGE_INTEGER UserTime;
+    LARGE_INTEGER DpcTime;
+    LARGE_INTEGER InterruptTime;
+    ULONG InterruptCount;
+} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
+
+#ifndef SystemProcessorPerformanceInformation
+# define SystemProcessorPerformanceInformation 8
+#endif
+
+#ifndef FILE_DEVICE_FILE_SYSTEM
+# define FILE_DEVICE_FILE_SYSTEM 0x00000009
+#endif
+
+#ifndef FILE_DEVICE_NETWORK
+# define FILE_DEVICE_NETWORK 0x00000012
+#endif
+
+#ifndef METHOD_BUFFERED
+# define METHOD_BUFFERED 0
+#endif
+
+#ifndef METHOD_IN_DIRECT
+# define METHOD_IN_DIRECT 1
+#endif
+
+#ifndef METHOD_OUT_DIRECT
+# define METHOD_OUT_DIRECT 2
+#endif
+
+#ifndef METHOD_NEITHER
+#define METHOD_NEITHER 3
+#endif
+
+#ifndef METHOD_DIRECT_TO_HARDWARE
+# define METHOD_DIRECT_TO_HARDWARE METHOD_IN_DIRECT
+#endif
+
+#ifndef METHOD_DIRECT_FROM_HARDWARE
+# define METHOD_DIRECT_FROM_HARDWARE METHOD_OUT_DIRECT
+#endif
+
+#ifndef FILE_ANY_ACCESS
+# define FILE_ANY_ACCESS 0
+#endif
+
+#ifndef FILE_SPECIAL_ACCESS
+# define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS)
+#endif
+
+#ifndef FILE_READ_ACCESS
+# define FILE_READ_ACCESS 0x0001
+#endif
+
+#ifndef FILE_WRITE_ACCESS
+# define FILE_WRITE_ACCESS 0x0002
+#endif
+
+#ifndef CTL_CODE
+# define CTL_CODE(device_type, function, method, access)                      \
+    (((device_type) << 16) | ((access) << 14) | ((function) << 2) | (method))
+#endif
+
+#ifndef FSCTL_SET_REPARSE_POINT
+# define FSCTL_SET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM,            \
+                                          41,                                 \
+                                          METHOD_BUFFERED,                    \
+                                          FILE_SPECIAL_ACCESS)
+#endif
+
+#ifndef FSCTL_GET_REPARSE_POINT
+# define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM,            \
+                                          42,                                 \
+                                          METHOD_BUFFERED,                    \
+                                          FILE_ANY_ACCESS)
+#endif
+
+#ifndef FSCTL_DELETE_REPARSE_POINT
+# define FSCTL_DELETE_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM,         \
+                                             43,                              \
+                                             METHOD_BUFFERED,                 \
+                                             FILE_SPECIAL_ACCESS)
+#endif
+
+#ifndef IO_REPARSE_TAG_SYMLINK
+# define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
+#endif
+
+typedef VOID (NTAPI *PIO_APC_ROUTINE)
+             (PVOID ApcContext,
+              PIO_STATUS_BLOCK IoStatusBlock,
+              ULONG Reserved);
+
+typedef ULONG (NTAPI *sRtlNtStatusToDosError)
+              (NTSTATUS Status);
+
+typedef NTSTATUS (NTAPI *sNtDeviceIoControlFile)
+                 (HANDLE FileHandle,
+                  HANDLE Event,
+                  PIO_APC_ROUTINE ApcRoutine,
+                  PVOID ApcContext,
+                  PIO_STATUS_BLOCK IoStatusBlock,
+                  ULONG IoControlCode,
+                  PVOID InputBuffer,
+                  ULONG InputBufferLength,
+                  PVOID OutputBuffer,
+                  ULONG OutputBufferLength);
+
+typedef NTSTATUS (NTAPI *sNtQueryInformationFile)
+                 (HANDLE FileHandle,
+                  PIO_STATUS_BLOCK IoStatusBlock,
+                  PVOID FileInformation,
+                  ULONG Length,
+                  FILE_INFORMATION_CLASS FileInformationClass);
+
+typedef NTSTATUS (NTAPI *sNtSetInformationFile)
+                 (HANDLE FileHandle,
+                  PIO_STATUS_BLOCK IoStatusBlock,
+                  PVOID FileInformation,
+                  ULONG Length,
+                  FILE_INFORMATION_CLASS FileInformationClass);
+
+typedef NTSTATUS (NTAPI *sNtQueryVolumeInformationFile)
+                 (HANDLE FileHandle,
+                  PIO_STATUS_BLOCK IoStatusBlock,
+                  PVOID FsInformation,
+                  ULONG Length,
+                  FS_INFORMATION_CLASS FsInformationClass);
+
+typedef NTSTATUS (NTAPI *sNtQuerySystemInformation)
+                 (UINT SystemInformationClass,
+                  PVOID SystemInformation,
+                  ULONG SystemInformationLength,
+                  PULONG ReturnLength);
+
+typedef NTSTATUS (NTAPI *sNtQueryDirectoryFile)
+                 (HANDLE FileHandle,
+                  HANDLE Event,
+                  PIO_APC_ROUTINE ApcRoutine,
+                  PVOID ApcContext,
+                  PIO_STATUS_BLOCK IoStatusBlock,
+                  PVOID FileInformation,
+                  ULONG Length,
+                  FILE_INFORMATION_CLASS FileInformationClass,
+                  BOOLEAN ReturnSingleEntry,
+                  PUNICODE_STRING FileName,
+                  BOOLEAN RestartScan
+                );
+
+/*
+ * Kernel32 headers
+ */
+#ifndef FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
+# define FILE_SKIP_COMPLETION_PORT_ON_SUCCESS 0x1
+#endif
+
+#ifndef FILE_SKIP_SET_EVENT_ON_HANDLE
+# define FILE_SKIP_SET_EVENT_ON_HANDLE 0x2
+#endif
+
+#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
+# define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
+#endif
+
+#if (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) \
+ || (defined(_MSC_VER) && _MSC_VER < 1500)
+  typedef struct _OVERLAPPED_ENTRY {
+      ULONG_PTR lpCompletionKey;
+      LPOVERLAPPED lpOverlapped;
+      ULONG_PTR Internal;
+      DWORD dwNumberOfBytesTransferred;
+  } OVERLAPPED_ENTRY, *LPOVERLAPPED_ENTRY;
+#endif
+
+/* from wincon.h */
+#ifndef ENABLE_INSERT_MODE
+# define ENABLE_INSERT_MODE 0x20
+#endif
+
+#ifndef ENABLE_QUICK_EDIT_MODE
+# define ENABLE_QUICK_EDIT_MODE 0x40
+#endif
+
+#ifndef ENABLE_EXTENDED_FLAGS
+# define ENABLE_EXTENDED_FLAGS 0x80
+#endif
+
+/* from winerror.h */
+#ifndef ERROR_SYMLINK_NOT_SUPPORTED
+# define ERROR_SYMLINK_NOT_SUPPORTED 1464
+#endif
+
+#ifndef ERROR_MUI_FILE_NOT_FOUND
+# define ERROR_MUI_FILE_NOT_FOUND 15100
+#endif
+
+#ifndef ERROR_MUI_INVALID_FILE
+# define ERROR_MUI_INVALID_FILE 15101
+#endif
+
+#ifndef ERROR_MUI_INVALID_RC_CONFIG
+# define ERROR_MUI_INVALID_RC_CONFIG 15102
+#endif
+
+#ifndef ERROR_MUI_INVALID_LOCALE_NAME
+# define ERROR_MUI_INVALID_LOCALE_NAME 15103
+#endif
+
+#ifndef ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME
+# define ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME 15104
+#endif
+
+#ifndef ERROR_MUI_FILE_NOT_LOADED
+# define ERROR_MUI_FILE_NOT_LOADED 15105
+#endif
+
+typedef BOOL (WINAPI *sGetQueuedCompletionStatusEx)
+             (HANDLE CompletionPort,
+              LPOVERLAPPED_ENTRY lpCompletionPortEntries,
+              ULONG ulCount,
+              PULONG ulNumEntriesRemoved,
+              DWORD dwMilliseconds,
+              BOOL fAlertable);
+
+typedef BOOL (WINAPI* sSetFileCompletionNotificationModes)
+             (HANDLE FileHandle,
+              UCHAR Flags);
+
+typedef BOOLEAN (WINAPI* sCreateSymbolicLinkW)
+                (LPCWSTR lpSymlinkFileName,
+                 LPCWSTR lpTargetFileName,
+                 DWORD dwFlags);
+
+typedef BOOL (WINAPI* sCancelIoEx)
+             (HANDLE hFile,
+              LPOVERLAPPED lpOverlapped);
+
+typedef VOID (WINAPI* sInitializeConditionVariable)
+             (PCONDITION_VARIABLE ConditionVariable);
+
+typedef BOOL (WINAPI* sSleepConditionVariableCS)
+             (PCONDITION_VARIABLE ConditionVariable,
+              PCRITICAL_SECTION CriticalSection,
+              DWORD dwMilliseconds);
+
+typedef BOOL (WINAPI* sSleepConditionVariableSRW)
+             (PCONDITION_VARIABLE ConditionVariable,
+              PSRWLOCK SRWLock,
+              DWORD dwMilliseconds,
+              ULONG Flags);
+
+typedef VOID (WINAPI* sWakeAllConditionVariable)
+             (PCONDITION_VARIABLE ConditionVariable);
+
+typedef VOID (WINAPI* sWakeConditionVariable)
+             (PCONDITION_VARIABLE ConditionVariable);
+
+typedef BOOL (WINAPI* sCancelSynchronousIo)
+             (HANDLE hThread);
+
+typedef DWORD (WINAPI* sGetFinalPathNameByHandleW)
+             (HANDLE hFile,
+              LPWSTR lpszFilePath,
+              DWORD cchFilePath,
+              DWORD dwFlags);
+
+/* from powerbase.h */
+#ifndef DEVICE_NOTIFY_CALLBACK
+# define DEVICE_NOTIFY_CALLBACK 2
+#endif
+
+#ifndef PBT_APMRESUMEAUTOMATIC
+# define PBT_APMRESUMEAUTOMATIC 18
+#endif
+
+#ifndef PBT_APMRESUMESUSPEND
+# define PBT_APMRESUMESUSPEND 7
+#endif
+
+typedef ULONG CALLBACK _DEVICE_NOTIFY_CALLBACK_ROUTINE(
+  PVOID Context,
+  ULONG Type,
+  PVOID Setting
+);
+typedef _DEVICE_NOTIFY_CALLBACK_ROUTINE* _PDEVICE_NOTIFY_CALLBACK_ROUTINE;
+
+typedef struct _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS {
+  _PDEVICE_NOTIFY_CALLBACK_ROUTINE Callback;
+  PVOID Context;
+} _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS, *_PDEVICE_NOTIFY_SUBSCRIBE_PARAMETERS;
+
+typedef PVOID _HPOWERNOTIFY;
+typedef _HPOWERNOTIFY *_PHPOWERNOTIFY;
+
+typedef DWORD (WINAPI *sPowerRegisterSuspendResumeNotification)
+              (DWORD         Flags,
+               HANDLE        Recipient,
+               _PHPOWERNOTIFY RegistrationHandle);
+
+
+/* Ntdll function pointers */
+extern sRtlNtStatusToDosError pRtlNtStatusToDosError;
+extern sNtDeviceIoControlFile pNtDeviceIoControlFile;
+extern sNtQueryInformationFile pNtQueryInformationFile;
+extern sNtSetInformationFile pNtSetInformationFile;
+extern sNtQueryVolumeInformationFile pNtQueryVolumeInformationFile;
+extern sNtQueryDirectoryFile pNtQueryDirectoryFile;
+extern sNtQuerySystemInformation pNtQuerySystemInformation;
+
+
+/* Kernel32 function pointers */
+extern sGetQueuedCompletionStatusEx pGetQueuedCompletionStatusEx;
+extern sSetFileCompletionNotificationModes pSetFileCompletionNotificationModes;
+extern sCreateSymbolicLinkW pCreateSymbolicLinkW;
+extern sCancelIoEx pCancelIoEx;
+extern sInitializeConditionVariable pInitializeConditionVariable;
+extern sSleepConditionVariableCS pSleepConditionVariableCS;
+extern sSleepConditionVariableSRW pSleepConditionVariableSRW;
+extern sWakeAllConditionVariable pWakeAllConditionVariable;
+extern sWakeConditionVariable pWakeConditionVariable;
+extern sCancelSynchronousIo pCancelSynchronousIo;
+extern sGetFinalPathNameByHandleW pGetFinalPathNameByHandleW;
+
+
+/* Powrprof.dll function pointer */
+extern sPowerRegisterSuspendResumeNotification pPowerRegisterSuspendResumeNotification;
+
+#endif /* UV_WIN_WINAPI_H_ */
diff --git a/Utilities/cmlibuv/src/win/winsock.c b/Utilities/cmlibuv/src/win/winsock.c
new file mode 100644
index 0000000..d2e667e
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/winsock.c
@@ -0,0 +1,561 @@
+/* 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 <assert.h>
+#include <stdlib.h>
+
+#include "uv.h"
+#include "internal.h"
+
+
+/* Whether there are any non-IFS LSPs stacked on TCP */
+int uv_tcp_non_ifs_lsp_ipv4;
+int uv_tcp_non_ifs_lsp_ipv6;
+
+/* Ip address used to bind to any port at any interface */
+struct sockaddr_in uv_addr_ip4_any_;
+struct sockaddr_in6 uv_addr_ip6_any_;
+
+
+/*
+ * Retrieves the pointer to a winsock extension function.
+ */
+static BOOL uv_get_extension_function(SOCKET socket, GUID guid,
+    void **target) {
+  int result;
+  DWORD bytes;
+
+  result = WSAIoctl(socket,
+                    SIO_GET_EXTENSION_FUNCTION_POINTER,
+                    &guid,
+                    sizeof(guid),
+                    (void*)target,
+                    sizeof(*target),
+                    &bytes,
+                    NULL,
+                    NULL);
+
+  if (result == SOCKET_ERROR) {
+    *target = NULL;
+    return FALSE;
+  } else {
+    return TRUE;
+  }
+}
+
+
+BOOL uv_get_acceptex_function(SOCKET socket, LPFN_ACCEPTEX* target) {
+  const GUID wsaid_acceptex = WSAID_ACCEPTEX;
+  return uv_get_extension_function(socket, wsaid_acceptex, (void**)target);
+}
+
+
+BOOL uv_get_connectex_function(SOCKET socket, LPFN_CONNECTEX* target) {
+  const GUID wsaid_connectex = WSAID_CONNECTEX;
+  return uv_get_extension_function(socket, wsaid_connectex, (void**)target);
+}
+
+
+static int error_means_no_support(DWORD error) {
+  return error == WSAEPROTONOSUPPORT || error == WSAESOCKTNOSUPPORT ||
+         error == WSAEPFNOSUPPORT || error == WSAEAFNOSUPPORT;
+}
+
+
+void uv_winsock_init() {
+  WSADATA wsa_data;
+  int errorno;
+  SOCKET dummy;
+  WSAPROTOCOL_INFOW protocol_info;
+  int opt_len;
+
+  /* Initialize winsock */
+  errorno = WSAStartup(MAKEWORD(2, 2), &wsa_data);
+  if (errorno != 0) {
+    uv_fatal_error(errorno, "WSAStartup");
+  }
+
+  /* Set implicit binding address used by connectEx */
+  if (uv_ip4_addr("0.0.0.0", 0, &uv_addr_ip4_any_)) {
+    abort();
+  }
+
+  if (uv_ip6_addr("::", 0, &uv_addr_ip6_any_)) {
+    abort();
+  }
+
+  /* Detect non-IFS LSPs */
+  dummy = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
+
+  if (dummy != INVALID_SOCKET) {
+    opt_len = (int) sizeof protocol_info;
+    if (getsockopt(dummy,
+                   SOL_SOCKET,
+                   SO_PROTOCOL_INFOW,
+                   (char*) &protocol_info,
+                   &opt_len) == SOCKET_ERROR)
+      uv_fatal_error(WSAGetLastError(), "getsockopt");
+
+    if (!(protocol_info.dwServiceFlags1 & XP1_IFS_HANDLES))
+      uv_tcp_non_ifs_lsp_ipv4 = 1;
+
+    if (closesocket(dummy) == SOCKET_ERROR)
+      uv_fatal_error(WSAGetLastError(), "closesocket");
+
+  } else if (!error_means_no_support(WSAGetLastError())) {
+    /* Any error other than "socket type not supported" is fatal. */
+    uv_fatal_error(WSAGetLastError(), "socket");
+  }
+
+  /* Detect IPV6 support and non-IFS LSPs */
+  dummy = socket(AF_INET6, SOCK_STREAM, IPPROTO_IP);
+
+  if (dummy != INVALID_SOCKET) {
+    opt_len = (int) sizeof protocol_info;
+    if (getsockopt(dummy,
+                   SOL_SOCKET,
+                   SO_PROTOCOL_INFOW,
+                   (char*) &protocol_info,
+                   &opt_len) == SOCKET_ERROR)
+      uv_fatal_error(WSAGetLastError(), "getsockopt");
+
+    if (!(protocol_info.dwServiceFlags1 & XP1_IFS_HANDLES))
+      uv_tcp_non_ifs_lsp_ipv6 = 1;
+
+    if (closesocket(dummy) == SOCKET_ERROR)
+      uv_fatal_error(WSAGetLastError(), "closesocket");
+
+  } else if (!error_means_no_support(WSAGetLastError())) {
+    /* Any error other than "socket type not supported" is fatal. */
+    uv_fatal_error(WSAGetLastError(), "socket");
+  }
+}
+
+
+int uv_ntstatus_to_winsock_error(NTSTATUS status) {
+  switch (status) {
+    case STATUS_SUCCESS:
+      return ERROR_SUCCESS;
+
+    case STATUS_PENDING:
+      return ERROR_IO_PENDING;
+
+    case STATUS_INVALID_HANDLE:
+    case STATUS_OBJECT_TYPE_MISMATCH:
+      return WSAENOTSOCK;
+
+    case STATUS_INSUFFICIENT_RESOURCES:
+    case STATUS_PAGEFILE_QUOTA:
+    case STATUS_COMMITMENT_LIMIT:
+    case STATUS_WORKING_SET_QUOTA:
+    case STATUS_NO_MEMORY:
+    case STATUS_QUOTA_EXCEEDED:
+    case STATUS_TOO_MANY_PAGING_FILES:
+    case STATUS_REMOTE_RESOURCES:
+      return WSAENOBUFS;
+
+    case STATUS_TOO_MANY_ADDRESSES:
+    case STATUS_SHARING_VIOLATION:
+    case STATUS_ADDRESS_ALREADY_EXISTS:
+      return WSAEADDRINUSE;
+
+    case STATUS_LINK_TIMEOUT:
+    case STATUS_IO_TIMEOUT:
+    case STATUS_TIMEOUT:
+      return WSAETIMEDOUT;
+
+    case STATUS_GRACEFUL_DISCONNECT:
+      return WSAEDISCON;
+
+    case STATUS_REMOTE_DISCONNECT:
+    case STATUS_CONNECTION_RESET:
+    case STATUS_LINK_FAILED:
+    case STATUS_CONNECTION_DISCONNECTED:
+    case STATUS_PORT_UNREACHABLE:
+    case STATUS_HOPLIMIT_EXCEEDED:
+      return WSAECONNRESET;
+
+    case STATUS_LOCAL_DISCONNECT:
+    case STATUS_TRANSACTION_ABORTED:
+    case STATUS_CONNECTION_ABORTED:
+      return WSAECONNABORTED;
+
+    case STATUS_BAD_NETWORK_PATH:
+    case STATUS_NETWORK_UNREACHABLE:
+    case STATUS_PROTOCOL_UNREACHABLE:
+      return WSAENETUNREACH;
+
+    case STATUS_HOST_UNREACHABLE:
+      return WSAEHOSTUNREACH;
+
+    case STATUS_CANCELLED:
+    case STATUS_REQUEST_ABORTED:
+      return WSAEINTR;
+
+    case STATUS_BUFFER_OVERFLOW:
+    case STATUS_INVALID_BUFFER_SIZE:
+      return WSAEMSGSIZE;
+
+    case STATUS_BUFFER_TOO_SMALL:
+    case STATUS_ACCESS_VIOLATION:
+      return WSAEFAULT;
+
+    case STATUS_DEVICE_NOT_READY:
+    case STATUS_REQUEST_NOT_ACCEPTED:
+      return WSAEWOULDBLOCK;
+
+    case STATUS_INVALID_NETWORK_RESPONSE:
+    case STATUS_NETWORK_BUSY:
+    case STATUS_NO_SUCH_DEVICE:
+    case STATUS_NO_SUCH_FILE:
+    case STATUS_OBJECT_PATH_NOT_FOUND:
+    case STATUS_OBJECT_NAME_NOT_FOUND:
+    case STATUS_UNEXPECTED_NETWORK_ERROR:
+      return WSAENETDOWN;
+
+    case STATUS_INVALID_CONNECTION:
+      return WSAENOTCONN;
+
+    case STATUS_REMOTE_NOT_LISTENING:
+    case STATUS_CONNECTION_REFUSED:
+      return WSAECONNREFUSED;
+
+    case STATUS_PIPE_DISCONNECTED:
+      return WSAESHUTDOWN;
+
+    case STATUS_CONFLICTING_ADDRESSES:
+    case STATUS_INVALID_ADDRESS:
+    case STATUS_INVALID_ADDRESS_COMPONENT:
+      return WSAEADDRNOTAVAIL;
+
+    case STATUS_NOT_SUPPORTED:
+    case STATUS_NOT_IMPLEMENTED:
+      return WSAEOPNOTSUPP;
+
+    case STATUS_ACCESS_DENIED:
+      return WSAEACCES;
+
+    default:
+      if ((status & (FACILITY_NTWIN32 << 16)) == (FACILITY_NTWIN32 << 16) &&
+          (status & (ERROR_SEVERITY_ERROR | ERROR_SEVERITY_WARNING))) {
+        /* It's a windows error that has been previously mapped to an */
+        /* ntstatus code. */
+        return (DWORD) (status & 0xffff);
+      } else {
+        /* The default fallback for unmappable ntstatus codes. */
+        return WSAEINVAL;
+      }
+  }
+}
+
+
+/*
+ * This function provides a workaround for a bug in the winsock implementation
+ * of WSARecv. The problem is that when SetFileCompletionNotificationModes is
+ * used to avoid IOCP notifications of completed reads, WSARecv does not
+ * reliably indicate whether we can expect a completion package to be posted
+ * when the receive buffer is smaller than the received datagram.
+ *
+ * However it is desirable to use SetFileCompletionNotificationModes because
+ * it yields a massive performance increase.
+ *
+ * This function provides a workaround for that bug, but it only works for the
+ * specific case that we need it for. E.g. it assumes that the "avoid iocp"
+ * bit has been set, and supports only overlapped operation. It also requires
+ * the user to use the default msafd driver, doesn't work when other LSPs are
+ * stacked on top of it.
+ */
+int WSAAPI uv_wsarecv_workaround(SOCKET socket, WSABUF* buffers,
+    DWORD buffer_count, DWORD* bytes, DWORD* flags, WSAOVERLAPPED *overlapped,
+    LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine) {
+  NTSTATUS status;
+  void* apc_context;
+  IO_STATUS_BLOCK* iosb = (IO_STATUS_BLOCK*) &overlapped->Internal;
+  AFD_RECV_INFO info;
+  DWORD error;
+
+  if (overlapped == NULL || completion_routine != NULL) {
+    WSASetLastError(WSAEINVAL);
+    return SOCKET_ERROR;
+  }
+
+  info.BufferArray = buffers;
+  info.BufferCount = buffer_count;
+  info.AfdFlags = AFD_OVERLAPPED;
+  info.TdiFlags = TDI_RECEIVE_NORMAL;
+
+  if (*flags & MSG_PEEK) {
+    info.TdiFlags |= TDI_RECEIVE_PEEK;
+  }
+
+  if (*flags & MSG_PARTIAL) {
+    info.TdiFlags |= TDI_RECEIVE_PARTIAL;
+  }
+
+  if (!((intptr_t) overlapped->hEvent & 1)) {
+    apc_context = (void*) overlapped;
+  } else {
+    apc_context = NULL;
+  }
+
+  iosb->Status = STATUS_PENDING;
+  iosb->Pointer = 0;
+
+  status = pNtDeviceIoControlFile((HANDLE) socket,
+                                  overlapped->hEvent,
+                                  NULL,
+                                  apc_context,
+                                  iosb,
+                                  IOCTL_AFD_RECEIVE,
+                                  &info,
+                                  sizeof(info),
+                                  NULL,
+                                  0);
+
+  *flags = 0;
+  *bytes = (DWORD) iosb->Information;
+
+  switch (status) {
+    case STATUS_SUCCESS:
+      error = ERROR_SUCCESS;
+      break;
+
+    case STATUS_PENDING:
+      error = WSA_IO_PENDING;
+      break;
+
+    case STATUS_BUFFER_OVERFLOW:
+      error = WSAEMSGSIZE;
+      break;
+
+    case STATUS_RECEIVE_EXPEDITED:
+      error = ERROR_SUCCESS;
+      *flags = MSG_OOB;
+      break;
+
+    case STATUS_RECEIVE_PARTIAL_EXPEDITED:
+      error = ERROR_SUCCESS;
+      *flags = MSG_PARTIAL | MSG_OOB;
+      break;
+
+    case STATUS_RECEIVE_PARTIAL:
+      error = ERROR_SUCCESS;
+      *flags = MSG_PARTIAL;
+      break;
+
+    default:
+      error = uv_ntstatus_to_winsock_error(status);
+      break;
+  }
+
+  WSASetLastError(error);
+
+  if (error == ERROR_SUCCESS) {
+    return 0;
+  } else {
+    return SOCKET_ERROR;
+  }
+}
+
+
+/* See description of uv_wsarecv_workaround. */
+int WSAAPI uv_wsarecvfrom_workaround(SOCKET socket, WSABUF* buffers,
+    DWORD buffer_count, DWORD* bytes, DWORD* flags, struct sockaddr* addr,
+    int* addr_len, WSAOVERLAPPED *overlapped,
+    LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine) {
+  NTSTATUS status;
+  void* apc_context;
+  IO_STATUS_BLOCK* iosb = (IO_STATUS_BLOCK*) &overlapped->Internal;
+  AFD_RECV_DATAGRAM_INFO info;
+  DWORD error;
+
+  if (overlapped == NULL || addr == NULL || addr_len == NULL ||
+      completion_routine != NULL) {
+    WSASetLastError(WSAEINVAL);
+    return SOCKET_ERROR;
+  }
+
+  info.BufferArray = buffers;
+  info.BufferCount = buffer_count;
+  info.AfdFlags = AFD_OVERLAPPED;
+  info.TdiFlags = TDI_RECEIVE_NORMAL;
+  info.Address = addr;
+  info.AddressLength = addr_len;
+
+  if (*flags & MSG_PEEK) {
+    info.TdiFlags |= TDI_RECEIVE_PEEK;
+  }
+
+  if (*flags & MSG_PARTIAL) {
+    info.TdiFlags |= TDI_RECEIVE_PARTIAL;
+  }
+
+  if (!((intptr_t) overlapped->hEvent & 1)) {
+    apc_context = (void*) overlapped;
+  } else {
+    apc_context = NULL;
+  }
+
+  iosb->Status = STATUS_PENDING;
+  iosb->Pointer = 0;
+
+  status = pNtDeviceIoControlFile((HANDLE) socket,
+                                  overlapped->hEvent,
+                                  NULL,
+                                  apc_context,
+                                  iosb,
+                                  IOCTL_AFD_RECEIVE_DATAGRAM,
+                                  &info,
+                                  sizeof(info),
+                                  NULL,
+                                  0);
+
+  *flags = 0;
+  *bytes = (DWORD) iosb->Information;
+
+  switch (status) {
+    case STATUS_SUCCESS:
+      error = ERROR_SUCCESS;
+      break;
+
+    case STATUS_PENDING:
+      error = WSA_IO_PENDING;
+      break;
+
+    case STATUS_BUFFER_OVERFLOW:
+      error = WSAEMSGSIZE;
+      break;
+
+    case STATUS_RECEIVE_EXPEDITED:
+      error = ERROR_SUCCESS;
+      *flags = MSG_OOB;
+      break;
+
+    case STATUS_RECEIVE_PARTIAL_EXPEDITED:
+      error = ERROR_SUCCESS;
+      *flags = MSG_PARTIAL | MSG_OOB;
+      break;
+
+    case STATUS_RECEIVE_PARTIAL:
+      error = ERROR_SUCCESS;
+      *flags = MSG_PARTIAL;
+      break;
+
+    default:
+      error = uv_ntstatus_to_winsock_error(status);
+      break;
+  }
+
+  WSASetLastError(error);
+
+  if (error == ERROR_SUCCESS) {
+    return 0;
+  } else {
+    return SOCKET_ERROR;
+  }
+}
+
+
+int WSAAPI uv_msafd_poll(SOCKET socket, AFD_POLL_INFO* info_in,
+    AFD_POLL_INFO* info_out, OVERLAPPED* overlapped) {
+  IO_STATUS_BLOCK iosb;
+  IO_STATUS_BLOCK* iosb_ptr;
+  HANDLE event = NULL;
+  void* apc_context;
+  NTSTATUS status;
+  DWORD error;
+
+  if (overlapped != NULL) {
+    /* Overlapped operation. */
+    iosb_ptr = (IO_STATUS_BLOCK*) &overlapped->Internal;
+    event = overlapped->hEvent;
+
+    /* Do not report iocp completion if hEvent is tagged. */
+    if ((uintptr_t) event & 1) {
+      event = (HANDLE)((uintptr_t) event & ~(uintptr_t) 1);
+      apc_context = NULL;
+    } else {
+      apc_context = overlapped;
+    }
+
+  } else {
+    /* Blocking operation. */
+    iosb_ptr = &iosb;
+    event = CreateEvent(NULL, FALSE, FALSE, NULL);
+    if (event == NULL) {
+      return SOCKET_ERROR;
+    }
+    apc_context = NULL;
+  }
+
+  iosb_ptr->Status = STATUS_PENDING;
+  status = pNtDeviceIoControlFile((HANDLE) socket,
+                                  event,
+                                  NULL,
+                                  apc_context,
+                                  iosb_ptr,
+                                  IOCTL_AFD_POLL,
+                                  info_in,
+                                  sizeof *info_in,
+                                  info_out,
+                                  sizeof *info_out);
+
+  if (overlapped == NULL) {
+    /* If this is a blocking operation, wait for the event to become */
+    /* signaled, and then grab the real status from the io status block. */
+    if (status == STATUS_PENDING) {
+      DWORD r = WaitForSingleObject(event, INFINITE);
+
+      if (r == WAIT_FAILED) {
+        DWORD saved_error = GetLastError();
+        CloseHandle(event);
+        WSASetLastError(saved_error);
+        return SOCKET_ERROR;
+      }
+
+      status = iosb.Status;
+    }
+
+    CloseHandle(event);
+  }
+
+  switch (status) {
+    case STATUS_SUCCESS:
+      error = ERROR_SUCCESS;
+      break;
+
+    case STATUS_PENDING:
+      error = WSA_IO_PENDING;
+      break;
+
+    default:
+      error = uv_ntstatus_to_winsock_error(status);
+      break;
+  }
+
+  WSASetLastError(error);
+
+  if (error == ERROR_SUCCESS) {
+    return 0;
+  } else {
+    return SOCKET_ERROR;
+  }
+}
diff --git a/Utilities/cmlibuv/src/win/winsock.h b/Utilities/cmlibuv/src/win/winsock.h
new file mode 100644
index 0000000..3115fe3
--- /dev/null
+++ b/Utilities/cmlibuv/src/win/winsock.h
@@ -0,0 +1,191 @@
+/* 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_WIN_WINSOCK_H_
+#define UV_WIN_WINSOCK_H_
+
+#include <winsock2.h>
+#include <iptypes.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include "winapi.h"
+
+
+/*
+ * MinGW is missing these too
+ */
+#ifndef SO_UPDATE_CONNECT_CONTEXT
+# define SO_UPDATE_CONNECT_CONTEXT 0x7010
+#endif
+
+#ifndef TCP_KEEPALIVE
+# define TCP_KEEPALIVE 3
+#endif
+
+#ifndef IPV6_V6ONLY
+# define IPV6_V6ONLY 27
+#endif
+
+#ifndef IPV6_HOPLIMIT
+# define IPV6_HOPLIMIT 21
+#endif
+
+#ifndef SIO_BASE_HANDLE
+# define SIO_BASE_HANDLE 0x48000022
+#endif
+
+/*
+ * TDI defines that are only in the DDK.
+ * We only need receive flags so far.
+ */
+#ifndef TDI_RECEIVE_NORMAL
+  #define TDI_RECEIVE_BROADCAST           0x00000004
+  #define TDI_RECEIVE_MULTICAST           0x00000008
+  #define TDI_RECEIVE_PARTIAL             0x00000010
+  #define TDI_RECEIVE_NORMAL              0x00000020
+  #define TDI_RECEIVE_EXPEDITED           0x00000040
+  #define TDI_RECEIVE_PEEK                0x00000080
+  #define TDI_RECEIVE_NO_RESPONSE_EXP     0x00000100
+  #define TDI_RECEIVE_COPY_LOOKAHEAD      0x00000200
+  #define TDI_RECEIVE_ENTIRE_MESSAGE      0x00000400
+  #define TDI_RECEIVE_AT_DISPATCH_LEVEL   0x00000800
+  #define TDI_RECEIVE_CONTROL_INFO        0x00001000
+  #define TDI_RECEIVE_FORCE_INDICATION    0x00002000
+  #define TDI_RECEIVE_NO_PUSH             0x00004000
+#endif
+
+/*
+ * The "Auxiliary Function Driver" is the windows kernel-mode driver that does
+ * TCP, UDP etc. Winsock is just a layer that dispatches requests to it.
+ * Having these definitions allows us to bypass winsock and make an AFD kernel
+ * call directly, avoiding a bug in winsock's recvfrom implementation.
+ */
+
+#define AFD_NO_FAST_IO   0x00000001
+#define AFD_OVERLAPPED   0x00000002
+#define AFD_IMMEDIATE    0x00000004
+
+#define AFD_POLL_RECEIVE_BIT            0
+#define AFD_POLL_RECEIVE                (1 << AFD_POLL_RECEIVE_BIT)
+#define AFD_POLL_RECEIVE_EXPEDITED_BIT  1
+#define AFD_POLL_RECEIVE_EXPEDITED      (1 << AFD_POLL_RECEIVE_EXPEDITED_BIT)
+#define AFD_POLL_SEND_BIT               2
+#define AFD_POLL_SEND                   (1 << AFD_POLL_SEND_BIT)
+#define AFD_POLL_DISCONNECT_BIT         3
+#define AFD_POLL_DISCONNECT             (1 << AFD_POLL_DISCONNECT_BIT)
+#define AFD_POLL_ABORT_BIT              4
+#define AFD_POLL_ABORT                  (1 << AFD_POLL_ABORT_BIT)
+#define AFD_POLL_LOCAL_CLOSE_BIT        5
+#define AFD_POLL_LOCAL_CLOSE            (1 << AFD_POLL_LOCAL_CLOSE_BIT)
+#define AFD_POLL_CONNECT_BIT            6
+#define AFD_POLL_CONNECT                (1 << AFD_POLL_CONNECT_BIT)
+#define AFD_POLL_ACCEPT_BIT             7
+#define AFD_POLL_ACCEPT                 (1 << AFD_POLL_ACCEPT_BIT)
+#define AFD_POLL_CONNECT_FAIL_BIT       8
+#define AFD_POLL_CONNECT_FAIL           (1 << AFD_POLL_CONNECT_FAIL_BIT)
+#define AFD_POLL_QOS_BIT                9
+#define AFD_POLL_QOS                    (1 << AFD_POLL_QOS_BIT)
+#define AFD_POLL_GROUP_QOS_BIT          10
+#define AFD_POLL_GROUP_QOS              (1 << AFD_POLL_GROUP_QOS_BIT)
+
+#define AFD_NUM_POLL_EVENTS             11
+#define AFD_POLL_ALL                    ((1 << AFD_NUM_POLL_EVENTS) - 1)
+
+typedef struct _AFD_RECV_DATAGRAM_INFO {
+    LPWSABUF BufferArray;
+    ULONG BufferCount;
+    ULONG AfdFlags;
+    ULONG TdiFlags;
+    struct sockaddr* Address;
+    int* AddressLength;
+} AFD_RECV_DATAGRAM_INFO, *PAFD_RECV_DATAGRAM_INFO;
+
+typedef struct _AFD_RECV_INFO {
+    LPWSABUF BufferArray;
+    ULONG BufferCount;
+    ULONG AfdFlags;
+    ULONG TdiFlags;
+} AFD_RECV_INFO, *PAFD_RECV_INFO;
+
+
+#define _AFD_CONTROL_CODE(operation, method) \
+    ((FSCTL_AFD_BASE) << 12 | (operation << 2) | method)
+
+#define FSCTL_AFD_BASE FILE_DEVICE_NETWORK
+
+#define AFD_RECEIVE            5
+#define AFD_RECEIVE_DATAGRAM   6
+#define AFD_POLL               9
+
+#define IOCTL_AFD_RECEIVE \
+    _AFD_CONTROL_CODE(AFD_RECEIVE, METHOD_NEITHER)
+
+#define IOCTL_AFD_RECEIVE_DATAGRAM \
+    _AFD_CONTROL_CODE(AFD_RECEIVE_DATAGRAM, METHOD_NEITHER)
+
+#define IOCTL_AFD_POLL \
+    _AFD_CONTROL_CODE(AFD_POLL, METHOD_BUFFERED)
+
+#if (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) \
+ || (defined(_MSC_VER) && _MSC_VER < 1500)
+typedef struct _IP_ADAPTER_UNICAST_ADDRESS_XP {
+  /* FIXME: __C89_NAMELESS was removed */
+  /* __C89_NAMELESS */ union {
+    ULONGLONG Alignment;
+    /* __C89_NAMELESS */ struct {
+      ULONG Length;
+      DWORD Flags;
+    };
+  };
+  struct _IP_ADAPTER_UNICAST_ADDRESS_XP *Next;
+  SOCKET_ADDRESS Address;
+  IP_PREFIX_ORIGIN PrefixOrigin;
+  IP_SUFFIX_ORIGIN SuffixOrigin;
+  IP_DAD_STATE DadState;
+  ULONG ValidLifetime;
+  ULONG PreferredLifetime;
+  ULONG LeaseLifetime;
+} IP_ADAPTER_UNICAST_ADDRESS_XP,*PIP_ADAPTER_UNICAST_ADDRESS_XP;
+
+typedef struct _IP_ADAPTER_UNICAST_ADDRESS_LH {
+  union {
+    ULONGLONG Alignment;
+    struct {
+      ULONG Length;
+      DWORD Flags;
+    };
+  };
+  struct _IP_ADAPTER_UNICAST_ADDRESS_LH *Next;
+  SOCKET_ADDRESS Address;
+  IP_PREFIX_ORIGIN PrefixOrigin;
+  IP_SUFFIX_ORIGIN SuffixOrigin;
+  IP_DAD_STATE DadState;
+  ULONG ValidLifetime;
+  ULONG PreferredLifetime;
+  ULONG LeaseLifetime;
+  UINT8 OnLinkPrefixLength;
+} IP_ADAPTER_UNICAST_ADDRESS_LH,*PIP_ADAPTER_UNICAST_ADDRESS_LH;
+
+#endif
+
+#endif /* UV_WIN_WINSOCK_H_ */
diff --git a/bootstrap b/bootstrap
index b3f06a1..889cc33 100755
--- a/bootstrap
+++ b/bootstrap
@@ -1,15 +1,6 @@
 #!/bin/sh
-#=============================================================================
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
 
 die() {
   echo "$@" 1>&2 ; exit 1
@@ -60,10 +51,12 @@ fi
 
 cmake_copyright="`grep '^Copyright .* Kitware' "${cmake_source_dir}/Copyright.txt"`"
 
+cmake_bin_dir_keyword="OTHER"
 cmake_data_dir_keyword="OTHER"
 cmake_doc_dir_keyword="OTHER"
 cmake_man_dir_keyword="OTHER"
 cmake_xdgdata_dir_keyword="OTHER"
+cmake_bin_dir=""
 cmake_data_dir=""
 cmake_doc_dir=""
 cmake_man_dir=""
@@ -72,6 +65,7 @@ cmake_init_file=""
 cmake_bootstrap_system_libs=""
 cmake_bootstrap_qt_gui=""
 cmake_bootstrap_qt_qmake=""
+cmake_bootstrap_server=""
 cmake_sphinx_man=""
 cmake_sphinx_html=""
 cmake_sphinx_qthelp=""
@@ -88,7 +82,7 @@ else
 fi
 
 # Determine whether this is a MinGW environment.
-if echo "${cmake_system}" | grep MINGW >/dev/null 2>&1; then
+if echo "${cmake_system}" | grep 'MINGW\|MSYS' >/dev/null 2>&1; then
   cmake_system_mingw=true
 else
   cmake_system_mingw=false
@@ -213,6 +207,7 @@ else
 fi
 
 # Lookup default install destinations.
+cmake_bin_dir_default="`cmake_install_dest_default BIN ${cmake_bin_dir_keyword}`"
 cmake_data_dir_default="`cmake_install_dest_default DATA ${cmake_data_dir_keyword}`"
 cmake_doc_dir_default="`cmake_install_dest_default DOC ${cmake_doc_dir_keyword}`"
 cmake_man_dir_default="`cmake_install_dest_default MAN ${cmake_man_dir_keyword}`"
@@ -263,6 +258,7 @@ CMAKE_CXX_SOURCES="\
   cmPropertyDefinition \
   cmPropertyDefinitionMap \
   cmMakefile \
+  cmMessenger \
   cmExportBuildFileGenerator \
   cmExportFileGenerator \
   cmExportInstallFileGenerator \
@@ -362,7 +358,6 @@ KWSYS_CXX_SOURCES="\
   SystemTools"
 
 KWSYS_FILES="\
-  auto_ptr.hxx \
   Directory.hxx \
   Encoding.h \
   Encoding.hxx \
@@ -413,6 +408,9 @@ Configuration:
   --no-qt-gui             do not build the Qt-based GUI (default)
   --qt-qmake=<qmake>      use <qmake> as the qmake executable to find Qt
 
+  --server                enable the server mode (default if supported)
+  --no-server             disable the server mode
+
   --sphinx-man            build man pages with Sphinx
   --sphinx-html           build html help with Sphinx
   --sphinx-qthelp         build qch help with Sphinx
@@ -422,6 +420,8 @@ Configuration:
 Directory and file names:
   --prefix=PREFIX         install files in tree rooted at PREFIX
                           ['"${cmake_default_prefix}"']
+  --bindir=DIR            install binaries in PREFIX/DIR
+                          ['"${cmake_bin_dir_default}"']
   --datadir=DIR           install data files in PREFIX/DIR
                           ['"${cmake_data_dir_default}"']
   --docdir=DIR            install documentation files in PREFIX/DIR
@@ -507,6 +507,7 @@ cmake_kwsys_config_replace_string ()
                 s/@KWSYS_LFS_REQUESTED@/${KWSYS_LFS_REQUESTED}/g;
                 s/@KWSYS_NAME_IS_KWSYS@/${KWSYS_NAME_IS_KWSYS}/g;
                 s/@KWSYS_STL_HAS_WSTRING@/${KWSYS_STL_HAS_WSTRING}/g;
+                s/@KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@/${KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H}/g;
                }" >> "${OUTFILE}${_tmp}"
     if [ -f "${OUTFILE}${_tmp}" ]; then
       if "${_diff}" "${OUTFILE}" "${OUTFILE}${_tmp}" > /dev/null 2> /dev/null ; then
@@ -627,6 +628,7 @@ while test $# != 0; do
   --prefix=*) dir=`cmake_arg "$1"`
               cmake_prefix_dir=`cmake_fix_slashes "$dir"` ;;
   --parallel=*) cmake_parallel_make=`cmake_arg "$1"` ;;
+  --bindir=*) cmake_bin_dir=`cmake_arg "$1"` ;;
   --datadir=*) cmake_data_dir=`cmake_arg "$1"` ;;
   --docdir=*) cmake_doc_dir=`cmake_arg "$1"` ;;
   --mandir=*) cmake_man_dir=`cmake_arg "$1"` ;;
@@ -643,6 +645,8 @@ while test $# != 0; do
   --qt-gui) cmake_bootstrap_qt_gui="1" ;;
   --no-qt-gui) cmake_bootstrap_qt_gui="0" ;;
   --qt-qmake=*) cmake_bootstrap_qt_qmake=`cmake_arg "$1"` ;;
+  --server) cmake_bootstrap_server="1" ;;
+  --no-server) cmake_bootstrap_server="0" ;;
   --sphinx-man) cmake_sphinx_man="1" ;;
   --sphinx-html) cmake_sphinx_html="1" ;;
   --sphinx-qthelp) cmake_sphinx_qthelp="1" ;;
@@ -1177,6 +1181,7 @@ KWSYS_BUILD_SHARED=0
 KWSYS_LFS_AVAILABLE=0
 KWSYS_LFS_REQUESTED=0
 KWSYS_STL_HAS_WSTRING=0
+KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H=0
 KWSYS_CXX_HAS_SETENV=0
 KWSYS_CXX_HAS_UNSETENV=0
 KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H=0
@@ -1219,6 +1224,15 @@ else
   echo "${cmake_cxx_compiler} does not have stl wstring"
 fi
 
+if cmake_try_run "${cmake_cxx_compiler}" \
+  "${cmake_cxx_flags} -DTEST_KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H" \
+  "${cmake_source_dir}/Source/kwsys/kwsysPlatformTestsCXX.cxx" >> cmake_bootstrap.log 2>&1; then
+  KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H=1
+  echo "${cmake_cxx_compiler} has <ext/stdio_filebuf.h>"
+else
+  echo "${cmake_cxx_compiler} does not have <ext/stdio_filebuf.h>"
+fi
+
 # Just to be safe, let us store compiler and flags to the header file
 
 cmake_bootstrap_version='$Revision$'
@@ -1263,8 +1277,11 @@ cmake_report cmVersionConfig.h${_tmp} "#define CMake_VERSION_PATCH ${cmake_versi
 cmake_report cmVersionConfig.h${_tmp} "#define CMake_VERSION \"${cmake_version}\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP_SOURCE_DIR \"${CMAKE_BOOTSTRAP_SOURCE_DIR}\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP_BINARY_DIR \"${CMAKE_BOOTSTRAP_BINARY_DIR}\""
+cmake_report cmConfigure.h${_tmp} "#define CMAKE_BIN_DIR \"/bootstrap-not-insalled\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_DATA_DIR \"/bootstrap-not-insalled\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP"
+cmake_report cmConfigure.h${_tmp} "#define CM_NULLPTR 0"
+cmake_report cmConfigure.h${_tmp} "#define CM_OVERRIDE"
 
 # Regenerate configured headers
 for h in Configure VersionConfig; do
@@ -1374,6 +1391,7 @@ echo '
 set (CMAKE_INSTALL_PREFIX "'"${cmake_prefix_dir}"'" CACHE PATH "Install path prefix, prepended onto install directories." FORCE)
 set (CMAKE_DOC_DIR "'"${cmake_doc_dir}"'" CACHE PATH "Install location for documentation (relative to prefix)." FORCE)
 set (CMAKE_MAN_DIR "'"${cmake_man_dir}"'" CACHE PATH "Install location for man pages (relative to prefix)." FORCE)
+set (CMAKE_BIN_DIR "'"${cmake_bin_dir}"'" CACHE PATH "Install location for binaries (relative to prefix)." FORCE)
 set (CMAKE_DATA_DIR "'"${cmake_data_dir}"'" CACHE PATH "Install location for data (relative to prefix)." FORCE)
 set (CMAKE_XDGDATA_DIR "'"${cmake_xdgdata_dir}"'" CACHE PATH "Install location for XDG specific files (relative to prefix)." FORCE)
 ' > "${cmake_bootstrap_dir}/InitialCacheFlags.cmake"
@@ -1389,6 +1407,11 @@ if [ "x${cmake_bootstrap_qt_qmake}" != "x" ]; then
 set (QT_QMAKE_EXECUTABLE "'"${cmake_bootstrap_qt_qmake}"'" CACHE FILEPATH "Location of Qt qmake" FORCE)
 ' >> "${cmake_bootstrap_dir}/InitialCacheFlags.cmake"
 fi
+if [ "x${cmake_bootstrap_server}" != "x" ]; then
+  echo '
+set (CMake_ENABLE_SERVER_MODE '"${cmake_bootstrap_server}"' CACHE BOOL "Enable server mode" FORCE)
+' >> "${cmake_bootstrap_dir}/InitialCacheFlags.cmake"
+fi
 if [ "x${cmake_sphinx_man}" != "x" ]; then
   echo '
 set (SPHINX_MAN "'"${cmake_sphinx_man}"'" CACHE BOOL "Build man pages with Sphinx" FORCE)

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-cmake/cmake.git



More information about the Pkg-cmake-commits mailing list